WPF使用Mutex创建单实例程序失效

时间:2023-12-04 22:30:32

vs2019

1.引入名称空间

using System.Threading;

using System.Runtime.InteropServices;

2.导入dll并声明方法

[DllImport("User32", CharSet = CharSet.Unicode)]

static extern IntPtr FindWindowW(string lpClassName, string lpWindowName);

[DllImport("User32", CharSet = CharSet.Unicode)]

static extern Boolean SetForegroundWindow(IntPtr hWnd);

3 修改后App.xaml.cs如下

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows; namespace WpfApp1
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application { protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Mutex mutex = new Mutex(true, "单实例", out bool isNewInstance);//“单实例”是MainWindow.xaml中的Title
if (isNewInstance != true)
{ IntPtr intPtr = FindWindowW(null, "单实例");
if (intPtr != IntPtr.Zero)
{
SetForegroundWindow(intPtr);
}
Shutdown();
}
} [DllImport("User32", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindowW(string lpClassName, string lpWindowName); [DllImport("User32", CharSet = CharSet.Unicode)]
static extern Boolean SetForegroundWindow(IntPtr hWnd);
} }

运行生成后的exe程序发现没有实现单实例的效果。

4重新修改App.xaml.cs文件

前面是将mutex声明为局部变量

Mutex mutex = new Mutex(true, "单实例", out bool isNewInstance);//“单实例”是MainWindow.xaml中的Title

这次将mutex声明为字段

...
Mutex mutex;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
mutex = new Mutex(true, "单实例", out bool isNewInstance);
if (isNewInstance != true)
{ IntPtr intPtr = FindWindowW(null, "单实例");
if (intPtr != IntPtr.Zero)
{
SetForegroundWindow(intPtr);
}
Shutdown();
}
}
...

重新生成后实现效果