C# WinForm 程式單例項執行,再次執行時啟用前一個例項
阿新 • • 發佈:2019-02-15
一個簡單的小程式,演示了winform程式如何執行單例項。當有例項執行時,再次單擊,會啟用第一個例項。
附主要原始碼:
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Threading; namespace SingleInstance { static class Program { public static EventWaitHandle ProgramStarted; /// <summary> /// 應用程式的主入口點。 /// </summary> [STAThread] static void Main() { // 嘗試建立一個命名事件 bool createNew; ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "MyStartEvent", out createNew); // 如果該命名事件已經存在(存在有前一個執行例項),則發事件通知並退出 if (!createNew) { ProgramStarted.Set(); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace SingleInstance { public partial class Form1 : Form { NotifyIcon notifyIcon1 = new NotifyIcon(); public Form1() { InitializeComponent(); this.notifyIcon1.Text = "Double click to show window"; this.notifyIcon1.Icon = System.Drawing.SystemIcons.Application; this.notifyIcon1.DoubleClick += OnNotifyIconDoubleClicked; this.SizeChanged += OnSizeChanged; ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted, null, -1, false); this.WindowState = FormWindowState.Normal; } // 當最小化時,放到系統托盤。 void OnSizeChanged(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.notifyIcon1.Visible = true; this.Visible = false; } } // 當雙擊托盤圖示時,恢復視窗顯示 void OnNotifyIconDoubleClicked(object sender, EventArgs e) { this.Visible = true; this.notifyIcon1.Visible = false; this.WindowState = FormWindowState.Normal; } // 當收到第二個程序的通知時,顯示窗體 void OnProgramStarted(object state, bool timeout) { this.notifyIcon1.ShowBalloonTip(2000, "Hello", "I am here...", ToolTipIcon.Info); this.Show(); this.WindowState = FormWindowState.Normal; //注意:一定要在窗體顯示後,再對屬性進行設定 } } }
附原始碼下載地址:點選開啟連結