有時咱們不但願咱們的WPF應用程序能夠同時運行有多個實例,當咱們試圖運行第二個實例的時候,已經運行的實例也應該彈出來。html
咱們能夠用Mutex來實現ide
打開App.xaml.cs,在App類中添加以下內容post
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能夠防止同一個進程運行兩次url
Update:擴展參考:Process and Assemblyspa