C# 禁止應(yīng)用程序多次啟動的實(shí)例
通常我們的情況是,雙擊一個exe文件,就運(yùn)行一個程序的實(shí)體,再雙擊一次這個exe文件,又運(yùn)行這個應(yīng)用程序的另一個實(shí)體。就拿QQ游戲來說吧,一臺電腦上一般只能運(yùn)行一個QQ游戲大廳。
那我們的程序也能像QQ游戲那里禁止多次啟動嗎,答案是可以的,下面介紹下一個簡單的實(shí)現(xiàn)方法,那就是Mutex(互斥)。
Mutex(mutual exclusion,互斥)是.Net Framework中提供跨多個線程同步訪問的一個類。它非常類似了Monitor類,因?yàn)樗麄兌贾挥幸粋€線程能擁有鎖定。而操作系統(tǒng)能夠識別有名稱的互斥,我們可以給互斥一個唯一的名稱,在程序啟動之前加一個這樣的互斥。這樣每次程序啟動之前,都會檢查這個命名的互斥是否存在。如果存在,應(yīng)用程序就退出。
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew;
//系統(tǒng)能夠識別有名稱的互斥,因此可以使用它禁止應(yīng)用程序啟動兩次
//第二個參數(shù)可以設(shè)置為產(chǎn)品的名稱:Application.ProductName
//每次啟動應(yīng)用程序,都會驗(yàn)證名稱為SingletonWinAppMutex的互斥是否存在
Mutex mutex = new Mutex(false, "SingletonWinAppMutex", out createdNew);
//如果已運(yùn)行,則在前端顯示
//createdNew == false,說明程序已運(yùn)行
if (!createdNew)
{
Process instance = GetExistProcess();
if (instance != null)
{
SetForegroud(instance);
Application.Exit();
return;
}
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
/// <summary>
/// 查看程序是否已經(jīng)運(yùn)行
/// </summary>
/// <returns></returns>
private static Process GetExistProcess()
{
Process currentProcess = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if ((process.Id != currentProcess.Id) &&
(Assembly.GetExecutingAssembly().Location == currentProcess.MainModule.FileName))
{
return process;
}
}
return null;
}
/// <summary>
/// 使程序前端顯示
/// </summary>
/// <param name="instance"></param>
private static void SetForegroud(Process instance)
{
IntPtr mainFormHandle = instance.MainWindowHandle;
if (mainFormHandle != IntPtr.Zero)
{
ShowWindowAsync(mainFormHandle, 1);
SetForegroundWindow(mainFormHandle);
}
}
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
}
相關(guān)文章
C# Dynamic之:ExpandoObject,DynamicObject,DynamicMetaOb的應(yīng)用(上)
本篇文章對C#中ExpandoObject,DynamicObject,DynamicMetaOb的應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析
這篇文章主要介紹了C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析,以實(shí)例形式較為詳細(xì)的講述了.NET Framework里面提供的三種Timer具體用法,需要的朋友可以參考下2014-10-10漢字轉(zhuǎn)拼音縮寫示例代碼(Silverlight和.NET 將漢字轉(zhuǎn)換成為拼音)
本篇文章主要介紹了漢字轉(zhuǎn)拼音縮寫示例代碼(Silverlight和.NET 將漢字轉(zhuǎn)換成為拼音) 需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法,可實(shí)現(xiàn)系統(tǒng)服務(wù)的啟動和停止功能,非常具有實(shí)用價值,需要的朋友可以參考下2015-04-04