如何確保C#的應用程式只被開啟一次

來源:互聯網
上載者:User

標籤:

http://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows

using System.Threading;[DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)]static extern bool SetForegroundWindow(IntPtr hWnd);/// <summary>/// The main entry point for the application./// </summary>[STAThread]static void Main(){   bool createdNew = true;   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))   {      if (createdNew)      {         Application.EnableVisualStyles();         Application.SetCompatibleTextRenderingDefault(false);         Application.Run(new MainForm());      }      else      {         Process current = Process.GetCurrentProcess();         foreach (Process process in Process.GetProcessesByName(current.ProcessName))         {            if (process.Id != current.Id)            {               SetForegroundWindow(process.MainWindowHandle);               break;            }         }      }   }}

上面代碼的MyApplicationName需要確保是唯一識別的,使用Process.GetCurrentProcess().MainModule.FileName提示說找不到檔案

http://stackoverflow.com/questions/4313756/creating-a-mutex-throws-a-directorynotfoundexception

My mutex name had \ in it, which windows was interpreting as a path character. Running:

將路徑名中的反斜線替換成_就可以了

 

 

坑爹的是又出現新問題

問題1:

bool createdNew;
string appName;
appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
appName = @"Local\" + appName;    //Local\ZITaker
using (Mutex mutex = new Mutex(true, appName, out createdNew))

此段代碼的問題在於,兩個程式的Assembly.GetExecutingAssembly().GetName().Name會是一致的

 

問題2:

bool createdNew;
string appName;
appName = Process.GetCurrentProcess().MainModule.FileName;
appName = @"Local\" + appName;
using (Mutex mutex = new Mutex(true, appName, out createdNew))

這個會提示未能找到路徑

 

正確的做法:

string appName;
appName = Process.GetCurrentProcess().MainModule.FileName;
appName = appName.Replace(Path.DirectorySeparatorChar, ‘_‘);
using (Mutex mutex = new Mutex(true, appName, out createdNew))

 

如何確保C#的應用程式只被開啟一次

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.