In C#, using WPF to create a single instance application requires a technology called mutually exclusive body. Mutual exclusion aims to ensure that only one application instance can be run at a time.
Understand the mutual reprimand
Mutual body acting as a seeker who acts as application resources. When the application creates a mutual reprimand, it actually "locks" these resources to prevent any other instances of the application from accessing them. This mechanism ensures that only one application instance can be performed at one time.
Create a single instance WPF application
To create a single instance WPF application, please follow the steps below: <.> 1. Development of mutual exclusive body:
In the application code, declare a static Mutex object.
The parameter specifies that the mutually exclusive body is initially owned by the application. The string parameter is the unique identifier of the mutually exclusive body. This identifier ensures that no other applications can use the same mutual body.
<.> 2. Check the mutually exclusive body ownership: true
static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
<.> 3. Notify the existing example:
WaitOne()
If the application is not the first instance, use the true
function to send a custom message to notify the start -up attempt of the running instance of the second instance. false
if (mutex.WaitOne(TimeSpan.Zero, true)) { // 应用程序的第一个实例 } else { // 第二个实例,通知第一个实例并退出 }
In running instances, the custom message is processed by rewriting the
method of the main window.
PostMessage()
NativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);
When the running instance receives a custom message, you can use the method to place it on the front desk.
WndProc
By performing these steps, you can create a single instance WPF application to ensure that only one application instance is in active at a time.
The above is the detailed content of How to Create a Single-Instance WPF Application Using Mutexes?. For more information, please follow other related articles on the PHP Chinese website!