Single instance windows forms application and how to get reference on it?

前端 未结 4 413
轮回少年
轮回少年 2021-01-06 02:09

I have a Windows Forms application that allows only one instance to be running at the time. I have implemented Singleton by using Mutex. The Application must be startable fr

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 02:51

    Is this not over complicating things ? Rather than closing the existing instance and starting a new one, can you not just re-activate the existing instance? Either way round the code below should give you some ideas on how to go about it...?

    Process thisProcess = Process.GetCurrentProcess();
            Process[] allProcesses = Process.GetProcessesByName(thisProcess.ProcessName);
            Process otherProcess = null;
            foreach (Process p in allProcesses )
            {
                if ((p.Id != thisProcess.Id) && (p.MainModule.FileName == thisProcess.MainModule.FileName))
                {
                    otherProcess = p;
                    break;
                }
            }
    
           if (otherProcess != null)
           {
               //note IntPtr expected by API calls.
               IntPtr hWnd = otherProcess.MainWindowHandle;
               //restore if minimized
               ShowWindow(hWnd ,1);
               //bring to the front
               SetForegroundWindow (hWnd);
           }
            else
            {
                //run your app here
            }
    

    There is another question about this here

提交回复
热议问题