c#中应用程序的单个实例

Single instance of an app in c#

我知道这个问题可能有点傻,但我是 c# 的新手,也是一般编码的新手。 我最近做了一个应用程序,我想限制它一次只有一个 运行 实例,这样用户就不能多次启动它。 我在 Whosebug 上找到了 michalczerwinski 的这个答案:

[STAThread]
static void Main()
{
    bool result;
    var mutex = new System.Threading.Mutex(true, "UniqueAppId", out result);

    if (!result)
    {
        MessageBox.Show("Another instance is already running.");
        return;
    }

    Application.Run(new Form1());

    GC.KeepAlive(mutex);                // mutex shouldn't be released - important line
}

谁能告诉我应该在哪里添加这个?我已经尝试将它添加到 Form1.cs 中的任何地方,但它不起作用。

static void Main()

是主函数的名称。您应该将此添加到 "Program.cs" 文件(标准名称)到此特定函数 (在函数中的其他所有内容之前).

释放资源是一种很好的做法。因此,最好在函数末尾添加 mutex.Dispose();using (mutex) { }(不是两者,只是这些选项之一)。

(更新:我显然没有仔细阅读你的问题,因为你有一个单一实例的方法,只是想知道在哪里添加它。无论如何,我认为这个答案仍然有帮助因为它为 single-instance-apps 提供了一种具有更多可能性的好方法,并且无需在您自己的代码中处理互斥量。

您可以从 WindowsFormsApplicationBase 派生 class,将 IsSingleInstance 属性 设置为 true 并覆盖 OnCreateMainForm 方法。 您将需要引用 Microsoft.VisualBasic.dll 到您的项目。

Here 是一个很好的例子,说明如何使用 WindowsFormsApplicationBase 来处理进一步的进程启动并调用已经 运行 的实例。

继承class:

public class App : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
    public App()
    {
        // Make this a single-instance application
        this.IsSingleInstance = true; 
        this.EnableVisualStyles = true;
    }

    protected override void OnCreateMainForm()
    {
        // Create an instance of the main form 
        // and set it in the application; 
        // but don't try to run() it.
        this.MainForm = new Form1();
    }
}

你的主要方法现在看起来像这样:

static void Main(string[] args)
{
    App myApp = new App();
    myApp.Run(args); 
}

对我来说,Mutex 解决方案不起作用,所以我改用了 Process 方法。它基本上检查是否有其他实例 运行。您必须将它放在 Program.cs 文件中,在 Application.Run().

之前
if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1)
        {
            MessageBox.Show("Another instance of this program is already running. Cannot proceed further.", "Warning!");
            return;
        }

这是迄今为止最简单的方法,至少对我来说是这样。

编辑:此方法最初已发布here