c#winform 避免打开多个相同窗口!

public Form1()
        {
            InitializeComponent();
        }
        ///


        /// 获取窗体句柄
        ///

        ///
        /// 窗体名称
        /// IntPtr 句柄
        [DllImport("User32.dll")]
        private static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
        [DllImport("User32.dll")]
        public static extern int IsWindow(IntPtr hWnd);
        ///
        ///  该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。
        ///  系统给创建前台窗口的线程分配的权限稍高于其他线程。
        ///

        /// 将被激活并被调入前台的窗口句柄
        /// 如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr handle = FindWindow(null, "Form2");
            if (IsWindow(handle) > 0)
            {
                SetForegroundWindow(handle);
            }
            else
            {
                Form2 f = new Form2();
                f.Show();
            }
        }

你可能感兴趣的:(c#winform 避免打开多个相同窗口!)