WPF:实现主应用程序单一实例运行方式总结
本文介绍常见的实现主应用程序单一实例运行的几种方式。
方式一:
public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { Process thisProc = Process.GetCurrentProcess(); if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1) { Application.Current.Shutdown(); return; } base.OnStartup(e); } }
方式二:
public partial class App : Application { public static EventWaitHandle ProgramStarted; private bool CreatedNew; protected override void OnStartup(StartupEventArgs e) { ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "MyApplication", out CreatedNew); if (CreatedNew) { MainWindow mainWindow = new MainWindow(); this.MainWindow = mainWindow; mainWindow.Show(); } else { ProgramStarted.Set(); Environment.Exit(0); } } }
方式三:
public partial class App : Application { private bool canCreateNew; private int EXISTINGWINGDOW_HANDLER; private Mutex m_ServerMutex; protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.m_ServerMutex = new Mutex(true, "MyApplication", out this.canCreateNew); if (!this.canCreateNew) { try { this.EXISTINGWINGDOW_HANDLER = SendMessageHelper.FindWindow(null, "WpfApplication1"); SendMessageHelper.SendMessage(this.EXISTINGWINGDOW_HANDLER, 0x112, 0xf120, 0); Application.Current.Shutdown(-1); } catch { } } } } public static class SendMessageHelper { [DllImport("User32.dll")] public static extern int FindWindow(string lpClassName, string lpWindowName); [DllImport("User32.dll")] public static extern int SendMessage(int hWnd, int Msg, int wParam); [DllImport("User32.dll")] public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam); [DllImport("User32.dll")] public static extern int SendMessage(int hWnd, int Msg, int wParam, IntPtr lParam); }
方式四:
注意:添加 Microsoft.VisualBasic.dll类库引用,并在项目属性窗口中设置启动对象为类MainEntry。
public partial class App : Application { } public class MainEntry { [STAThread] static void Main(string[] args) { SingleInstanceManager manager = new SingleInstanceManager(); manager.Run(args); } } public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase { App app; public SingleInstanceManager() { this.IsSingleInstance = true; } //应用程序初次运行时 protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e) { try { app = new App(); app.InitializeComponent(); app.Run(); } catch (Exception ex) { } return false; } //启动下一个应用程序实例时触发 protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs) { base.OnStartupNextInstance(eventArgs); } }
对于单一实例运行,不得不提到主进程通知,就是说第二次启动应用程序时,如何发送消息?发送消息的方式有命令行方式和关联文件打开。如在cmd中输入 MyApplocation.exe somaParameters或者打开程序支持的文件(.myextension)。将在后续博客中进行归纳总结......