单实例Windows窗体应用程序以及如何获取引用? [英] Single instance windows forms application and how to get reference on it?

查看:229
本文介绍了单实例Windows窗体应用程序以及如何获取引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows Forms应用程序,该应用程序当时仅允许运行一个实例.我已经通过使用Mutex实现了Singleton.该应用程序必须可从命令行启动(带有或不带有参数).应用程序通过脚本启动和退出.用户无法对其执行任何操作.

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 from commandline (with or without parameters). Application is started and exited by script. User can not take any action on it.

因此,应用程序的目的是简单的指示器"应用程序,它将仅显示最终用户的一些视觉和图形信息.最终用户无法对其进行任何操作,只能看到它.它是Windows窗体应用程序,因为这样视觉和图形外观就相对容易实现(您可以将其置顶,无边界等).

So, application purpose is simple "indicator" application that will just display some visual and graphical information for the enduser. End user can not do anything with it, just see it. It is windows forms application because then visual and graphical appearance is relatively easy implement (you can get it topmost, borderless, etc.).

简单地说: 当有人尝试使用exit命令行参数运行同一应用程序时,如何退出当前正在运行的应用程序?

To put it simply: How can I exit the current running application when someone tries to run same application with exit commandline parameter?

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());
        }
    }
}

推荐答案

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

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".

这篇关于单实例Windows窗体应用程序以及如何获取引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆