有時我們不希望我們的WPF應用程序可以同時運行有多個實例,當我們試圖運行第二個實例的時候,已經運行的實例也應該彈出來。
我們可以用Mutex來實現
打開App.xaml.cs,在App類中添加如下內容
public partial class App : Application { [DllImport("user32", CharSet = CharSet.Unicode)] static extern IntPtr FindWindow(string cls, string win); [DllImport("user32")] static extern IntPtr SetForegroundWindow(IntPtr hWnd); [DllImport("user32")] static extern bool IsIconic(IntPtr hWnd); [DllImport("user32")] static extern bool OpenIcon(IntPtr hWnd); protected override void OnStartup(StartupEventArgs e) { bool isNew; var mutex = new Mutex(true, "My Singleton Instance", out isNew); if (!isNew) { ActivateOtherWindow(); Shutdown(); } } private static void ActivateOtherWindow() { var other = FindWindow(null, "MainWindow"); if (other != IntPtr.Zero) { SetForegroundWindow(other); if (IsIconic(other)) OpenIcon(other); } } }
WPF實現和WinForm略有區別,請參考DebugLZQ前面的博文:使用內核對象Mutex可以防止同一個進程運行兩次
Update:擴展參考:Process and Assembly
