码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2018-11-09 16:26:16      阅读:237      评论:0      收藏:0      [点我收藏+]

标签: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);
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!