本文主要介紹WinFrom程序中只允許運(yùn)行一個(gè)實(shí)例的方法,并有完整的代碼示例,希望能給需要的朋友一些幫助。
我們開發(fā)WinFrom程序,很多時(shí)候都希望程序只有一個(gè)實(shí)例在運(yùn)行,避免運(yùn)行多個(gè)同樣的程序,一是沒有意義,二是容易出錯。
為了更便于使用,筆者整理了一段自己用的代碼,可以判斷程序是否在運(yùn)行,只運(yùn)行一個(gè)實(shí)例,而且能實(shí)現(xiàn)當(dāng)程序在運(yùn)行時(shí),再去雙擊程序圖標(biāo),直接呼出已經(jīng)運(yùn)行的程序。
下面看代碼,只需在程序的入口文件中加如下代碼即可:
static class Program
{
///
/// 應(yīng)用程序的主入口點(diǎn)。
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//1.這里判定是否已經(jīng)有實(shí)例在運(yùn)行
//只運(yùn)行一個(gè)實(shí)例
Process instance = RunningInstance();
if (instance == null)
{
//1.1 沒有實(shí)例在運(yùn)行
Application.Run(new frmMain());
}
else
{
//1.2 已經(jīng)有一個(gè)實(shí)例在運(yùn)行
HandleRunningInstance(instance);
}
//Application.Run(new frmMain());
}
//2.在進(jìn)程中查找是否已經(jīng)有實(shí)例在運(yùn)行
#region 確保程序只運(yùn)行一個(gè)實(shí)例
private static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//遍歷與當(dāng)前進(jìn)程名稱相同的進(jìn)程列表
foreach (Process process in processes)
{
//如果實(shí)例已經(jīng)存在則忽略當(dāng)前進(jìn)程
if (process.Id != current.Id)
{
//保證要打開的進(jìn)程同已經(jīng)存在的進(jìn)程來自同一文件路徑
if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
{
//返回已經(jīng)存在的進(jìn)程
return process;
}
}
}
return null;
}
//3.已經(jīng)有了就把它激活,并將其窗口放置最前端
private static void HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, 1); //調(diào)用api函數(shù),正常顯示窗口
SetForegroundWindow(instance.MainWindowHandle); //將窗口放置最前端
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(System.IntPtr hWnd);
#endregion
}
新聞熱點(diǎn)
疑難解答
圖片精選