本指南演示了如何使用互斥词以确保您的WPF应用程序的一个实例同时运行。
>了解单建立应用中的静音
>> 这是如何使用命名的Mutex在WPF应用程序中实现单个现实行为的方法:
在您的应用程序的主类中,添加static Mutex变量:
<code class="language-csharp">static Mutex mutex = new Mutex(true, "{GUID_HERE}"); </code>
用全球唯一标识符(GUID)为您的应用程序。 该GUID确保不同的应用程序不会意外共享同一静音。 您可以使用大多数IDE中可用的工具生成一个GUID。{GUID_HERE}
>
>在您的应用程序的方法中检查Main
>中的现有实例,检查是否可以获取静音:>
Main
<code class="language-csharp">if (!mutex.WaitOne(TimeSpan.Zero, true)) { // Another instance is already running. MessageBox.Show("Only one instance of this application can run at a time."); return; // Exit the new instance. } else { // This is the first instance. Application.Run(new MainWindow()); mutex.ReleaseMutex(); // Release the mutex when the application closes. }</code>
在启动新实例时,将现有的应用程序带到前景,您需要处理自定义Windows消息:
<code class="language-csharp">protected override void WndProc(ref Message m) { if (m.Msg == NativeMethods.WM_SHOWME) { ShowMe(); // A method to activate your main window. } base.WndProc(ref m); }</code>(自定义消息ID),并实现
>将主窗口置于最前沿的方法。NativeMethods
>
WM_SHOWME
ShowMe()
> (在获取互斥品的情况下),将自定义消息发送给任何现有实例:else
<code class="language-csharp">NativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);</code>>
没有外部库:
以上是如何仅确保使用Mutexes运行WPF应用程序的一个实例?的详细内容。更多信息请关注PHP中文网其他相关文章!