C# WinForm 判斷程序是否已經(jīng)在運(yùn)行,且只允許運(yùn)行一個(gè)實(shí)例,附源碼
我們開發(fā)WinFrom程序,很多時(shí)候都希望程序只有一個(gè)實(shí)例在運(yùn)行,避免運(yùn)行多個(gè)同樣的程序,一是沒有意義,二是容易出錯(cuò)。
為了更便于使用,筆者整理了一段自己用的代碼,可以判斷程序是否在運(yùn)行,只運(yùn)行一個(gè)實(shí)例,而且能實(shí)現(xiàn)當(dāng)程序在運(yùn)行時(shí),再去雙擊程序圖標(biāo),直接呼出已經(jīng)運(yùn)行的程序。
下面看代碼,只需在程序的入口文件中加如下代碼即可:
static class Program
{
/// <summary>
/// 應(yīng)用程序的主入口點(diǎn)。
/// </summary>
[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
}
相關(guān)文章
C#采用Winform實(shí)現(xiàn)類似Android的Listener
這篇文章主要介紹了C#采用Winform實(shí)現(xiàn)類似Android的Listener,很實(shí)用的技巧,需要的朋友可以參考下2014-08-08
C# Color.FromArgb()及系統(tǒng)顏色對(duì)照表一覽
基于C# 寫一個(gè) Redis 數(shù)據(jù)同步小工具
C#實(shí)現(xiàn)路由器斷開連接,更改公網(wǎng)ip的實(shí)例代碼
C#使用Fody實(shí)現(xiàn)監(jiān)控方法執(zhí)行時(shí)間
C#實(shí)現(xiàn)ComboBox變色的示例代碼
C# OpenCvSharp實(shí)現(xiàn)去除字母后面的雜線
C# Base 64 編碼/解碼實(shí)現(xiàn)代碼

