1.WPF程序在 啟動窗口的構造函數執行InitializeComponent之前判斷是否已經存在實例
- 不涉及服務器情況,可直接進行判斷(不在mainwindow的構造函數中判斷)
// public MainWindow() // {
// private bool _createNew; // string exeName = Properties.Resources.ThreadName; // Mutex mutex = new Mutex(true, exeName, out _createNew); //only one instance is allowed // if (!_createNew) // { // MessageBox.Show(Properties.Resources.ThereAlreadyApp); // App.Current.Shutdown(); // return; // } // InitializeComponent(); // }
- 涉及服務器(好多復制粘貼的網址,不知道那個是原創,找了能找到時間最早的鏈接,侵刪) 在 exeName字符串加 “Global\\”
如果已經有實例運行,關閉當前試圖運行的程序。
更新 -- 2016-12-23,在main函數中做判斷不嚴謹,
托盤程序情況下,程序在桌面上顯示以后,唯一ID就判斷不了。改為在類App中重寫OnStartup函數進行判斷,強制程序退出用Environment.Exit(0);
public partial class App : Application {
public EventWaitHandle ProgramStarted { get; set; }
protected override void OnStartup(StartupEventArgs e) { bool createNew; ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "MyTctiApp", out createNew); if (!createNew) { MessageBox.Show("already exit"); App.Current.Shutdown(); Environment.Exit(0); } base.OnStartup(e); } }