C# WinForm 判斷程序是否已經(jīng)在運(yùn)行,且只允許運(yùn)行一個(gè)實(shí)例,附源碼
我們開(kāi)發(fā)WinFrom程序,很多時(shí)候都希望程序只有一個(gè)實(shí)例在運(yùn)行,避免運(yùn)行多個(gè)同樣的程序,一是沒(méi)有意義,二是容易出錯(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 沒(méi)有實(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)程名稱(chēng)相同的進(jìn)程列表 foreach (Process process in processes) { //如果實(shí)例已經(jīng)存在則忽略當(dāng)前進(jìn)程 if (process.Id != current.Id) { //保證要打開(kāi)的進(jìn)程同已經(jīng)存在的進(jìn)程來(lái)自同一文件路徑 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)文章
互斥量mutex的簡(jiǎn)單使用(實(shí)例講解)
本篇文章主要是對(duì)互斥量mutex的簡(jiǎn)單使用進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2014-01-01C#中Decimal類(lèi)型截取保留N位小數(shù)并且不進(jìn)行四舍五入操作
這篇文章主要介紹了C#中Decimal類(lèi)型截取保留N位小數(shù)并且不進(jìn)行四舍五入操作,本文給出需求說(shuō)明和實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-06-06C#中常見(jiàn)的系統(tǒng)內(nèi)置委托用法詳解
這篇文章主要介紹了C#中常見(jiàn)的系統(tǒng)內(nèi)置委托用法,主要包括了Action類(lèi)的委托、Func類(lèi)的委托、Predicate<T>委托、Comparison<T>委托等,需要的朋友可以參考下2014-09-09