winform,同个程序只允许启动一次

2021-07-02 07:06

阅读:489

标签:out   函数   div   location   getc   user   oca   遍历   cmd   

static class Program
    {
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);
        /// 
        /// 应用程序的主入口点。
        /// 
        [STAThread]
        static void Main()
        {
            bool createNew;
            using (System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out createNew))
            {
                if (createNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Main());
                }
                else
                {
                    MessageBox.Show("Only one instance of this application is allowed!");
                    Process current = Process.GetCurrentProcess();
                    Process[] processes = Process.GetProcessesByName(current.ProcessName);
                    //遍历与当前进程名称相同的进程列表 
                    foreach (Process process in processes)
                    {
                        //如果实例已经存在则忽略当前进程 
                        if (process.Id != current.Id)
                        {
                            //保证要打开的进程同已经存在的进程来自同一文件路径
                            if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                            {
                                ShowWindowAsync(process.MainWindowHandle, 1);  //调用api函数,正常显示窗口
                                SetForegroundWindow(process.MainWindowHandle); //将窗口放置最前端
                            }
                        }
                    }
                }
            }
        }
    }

 

winform,同个程序只允许启动一次

标签:out   函数   div   location   getc   user   oca   遍历   cmd   

原文地址:https://www.cnblogs.com/ives/p/9934854.html


评论


亲,登录后才可以留言!