关键操作:
Mutex
GetProcessesByName
SetForegroundWindow
ShowWindow
IsIconic
public partial class App : Application
{
private Mutex mutexExistCheck;
[DllImport("User32")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32")]
private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
[DllImport("User32")]
private static extern bool IsIconic(IntPtr hWnd);
private const int SW_SHOW = 5;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;
protected override void OnStartup(StartupEventArgs e)
{
mutexExistCheck = new Mutex(true, "SingleInstance", out bool isNewInstance);
if (isNewInstance != true)
{
string appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
Process[] myProcess = Process.GetProcessesByName(appName);
Process procExe = myProcess.SingleOrDefault(o => o.MainWindowHandle != IntPtr.Zero);
if (null != procExe)
{
IntPtr hWnd = procExe.MainWindowHandle;
_ = IsIconic(hWnd) ? ShowWindow(hWnd, SW_RESTORE) : ShowWindow(hWnd, SW_SHOW);
_ = SetForegroundWindow(hWnd);
}
else
{
_ = MessageBox.Show("程序已运行!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
Environment.Exit(0);
return;
}
base.OnStartup(e);
}
}