只能保证唯一一个程序运行

Process instance = RunningInstance();
            if (instance == null)
            {
                if (args != null && args.Length >= 1 && args[0] == "Startup")
                {
                    Form1.bStartup = true;
                    using (new Form1())
                    {
                        Application.Run();
                    }
                }
                else
                {
                    Application.Run(new Form1());
                }
            }
            else
            {
                HandleRunningInstance(instance);
                Application.Exit();
            }
private static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    try
                    {
                        if (current.MainModule.FileName == process.MainModule.FileName)
                        {
                            return process;
                        }
                    }
                    catch { }
                    break;
                }
            }
            return null;
        }
private static void HandleRunningInstance(Process instance)
        {
            IntPtr ihand = instance.MainWindowHandle;
            if (ihand == IntPtr.Zero)
                ihand = Program.FindWindow("WindowsForms10.Window.8.app.0.141b42a_r6_ad1", null);
            if (ihand == IntPtr.Zero)
            {
                MessageBox.Show("已经启动了此程序,请不要同时运行多个本程序。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                ShowWindowAsync(ihand, SW_SHOWNOMAL);
                SetForegroundWindow(ihand);
            }
        }

 

posted @ 2022-02-16 16:39  黄立明02  阅读(49)  评论(0编辑  收藏  举报