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

吃可爱长大的小学妹 提交于 2019-12-01 06:42:58

The .NET framework offers a very good generic solution for this. Check the bottom of this MSDN magazine article. Use the StartupNextInstanceHandler() event handler to pass arbitrary commands to the running instance, like "quit".

Matt

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

This is a somewhat quick-and-dirty solution which you would probably want to refine:

[STAThread]
static void Main()
{
    var me = Process.GetCurrentProcess();
    var otherMe = Process.GetProcessesByName(me.ProcessName).Where(p => p.Id != me.Id).FirstOrDefault();

    if (otherMe != null)
    {
        otherMe.Kill();
    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

If an instance of the app is already started, that process is killed; otherwise the app starts normally.

I think the easiest way is the following

see the link

http://codenicely.blogspot.com/2010/04/creating-forms-object.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!