本指南演示瞭如何使用互斥詞以確保您的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中文網其他相關文章!