簡體   English   中英

c#中應用程序的單個實例

[英]Single instance of an app in c#

我知道這個問題可能有點傻,但我是 c# 的新手,也是一般編碼的新手。 我最近做了一個應用程序,我想限制它一次只能運行一個實例,這樣用戶就不能多次啟動它。 我在 stackoverflow 上找到了 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) { } (不是兩者,只有這些選項之一)。

(更新:我顯然沒有仔細閱讀你的問題,因為你有一個單一實例的方法,只是想知道在哪里添加它。無論如何,我認為這個答案仍然有幫助,因為它為單一實例提供了一個很好的方法- 具有更多可能性的應用程序,無需在您自己的代碼中處理互斥鎖。

您可以從WindowsFormsApplicationBase派生一個類,將IsSingleInstance屬性設置為true並覆蓋OnCreateMainForm方法。 您需要將Microsoft.VisualBasic.dll引用到您的項目中。

是一個很好的示例,說明如何使用WindowsFormsApplicationBase來處理進一步的進程啟動並調用已經運行的實例。

繼承類:

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

這是迄今為止最簡單的方法,至少對我而言。

編輯:此方法最初發布於此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM