单实例窗口形成应用程序以及如何获取它的参考?

Cla*_*ack 5 c# singleton mutex winforms

我有一个Windows窗体应用程序,当时只允许一个实例运行.我已经使用Mutex实现了Singleton.应用程序必须可以从命令行启动(带或不带参数).应用程序由脚本启动和退出.用户不能对其采取任何行动.

因此,应用程序的目的是简单的"指标"应用程序,它将为最终用户显示一些视觉和图形信息.最终用户无法对其进行任何操作,只需查看即可.它是Windows窗体应用程序,因为视觉和图形外观是相对容易的实现(你可以得到它最顶层,无边框等).

简单地说:当有人试图用退出命令行参数运行相同的应用程序时,如何退出当前运行的应用程序?

bool quit = (args.Length > 0 && args[0] == "quit") ? true : false;
using (Mutex mutex = new Mutex(false, sExeName))
{
    if (!mutex.WaitOne(0, true)) 
    {
        if (quit)
        {
            // This is the tricky part?
            // How can I get reference to "previous" launced 
            // Windows Forms application and call it's Exit() method.
        }
    } 
    else 
    {
        if (!quit)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 6

.NET框架为此提供了非常好的通用解决方案.查看本MSDN杂志文章的底部.使用StartupNextInstanceHandler()事件处理程序将任意命令传递给正在运行的实例,如"quit".

  • Microsoft已销毁了另一个链接。他们会学吗? (2认同)

Mat*_*att 5

这不是复杂的事情吗?您是否可以重新激活现有实例,而不是关闭现有实例并启动新实例?无论哪种方式围绕下面的代码应该给你一些关于如何去做的想法...?

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
        }
Run Code Online (Sandbox Code Playgroud)

有关于这一个问题在这里