How can I prevent launching my app multiple times?

后端 未结 10 1837
北荒
北荒 2020-12-13 18:42

I deployed my C# WinForms application using ClickOnce installation. Everything works fine with it (after a lot of work) :), but now I\'m facing a problem:

Whenever

10条回答
  •  失恋的感觉
    2020-12-13 19:04

    There are times **Mutex** is not working in some areas. Like using in console application. So I tried using WMI Query.

    Try this and it will work.

            /// 
            /// The main entry point for the application.
            /// 
            [STAThread]
            static void Main()
            {
                if (!isStillRunning())
                {
                   Application.Run(new Form1());
                 }
                 else {
                     MessageBox.Show("Previous process still running.",
                        "Application Halted", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                     Application.Exit();
                 }      
            }
    
            //***Uses WMI Query
            static bool isStillRunning() {
                string processName = Process.GetCurrentProcess().MainModule.ModuleName;
                ManagementObjectSearcher mos = new ManagementObjectSearcher();
                mos.Query.QueryString = @"SELECT * FROM Win32_Process WHERE Name = '" + processName + @"'";
                if (mos.Get().Count > 1)
                {
                   return true;
                }
                else
                   return false;
            }
    

    Hope it helps.

提交回复
热议问题