WPF应用单实例

2023-07-24 15:37:31 浏览数 (1)

前言

默认情况下 WPF应用是能够多开的,但是大部分情况下我们只想打开一个实例,这就有两种情况

  • 保留之前的,关闭新打开的。
  • 关闭之前的。

保留之前的进程

代码语言:javascript复制
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    CheckProcess();
}

[DllImport("User32.dll")]
private static extern int FindWindow(string className, string windowName);

[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(int hWnd);

private static void CheckProcess()
{
    Console.WriteLine(@"程序启动");
    Process current = Process.GetCurrentProcess();
    //获取欲启动进程名
    string strProcessName = Process.GetCurrentProcess().ProcessName;
    var processList = Process.GetProcessesByName(strProcessName);
    if (processList.Length > 1)
    {
        MessageWindow.Show("当前程序已在运行,请勿重复运行。");
        foreach (var process in processList)
        {
            if (process.Id == current.Id) continue;
            int hWnd = FindWindow(null, process.MainWindowTitle);
            SetForegroundWindow(hWnd);
        }
        Environment.Exit(1); //退出程序
    }
}

结束之前的进程

代码语言:javascript复制
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    CheckProcess();
}

/// <summary>
/// 结束已运行的程序
/// </summary>
private static void CheckProcess()
{
    Process current = Process.GetCurrentProcess();
    Process[] processList = Process.GetProcesses();
    foreach (Process process in processList)
    {
        if (process.ProcessName == Process.GetCurrentProcess().ProcessName)
        {
            if (process.Id != current.Id) //忽略当前进程
            {
                try
                {
                    process.Kill(); //结束进程
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
    }
}

0 人点赞