WPF只运行一个实例

2022-03-13 09:35:33 浏览数 (1)

正文

代码语言:javascript复制
[DllImportAttribute("User32.dll")]
private static extern int FindWindow(string ClassName, string WindowName);

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

private void checkProcess()
{
  Console.WriteLine("程序启动");
  Process current = Process.GetCurrentProcess();
  //获取欲启动进程名
  string strProcessName = Process.GetCurrentProcess().ProcessName;
  var processList = Process.GetProcessesByName(strProcessName);
  if (processList.Length > 1)
  {
    foreach (var process in processList)
    {
      if (process.Id == current.Id) continue;
      int hWnd = FindWindow(null, process.MainWindowTitle.ToString());
      SetForegroundWindow(hWnd);
    }
    Environment.Exit(1);//退出程序
    return;
  }
}

调用

代码语言:javascript复制
protected override void OnStartup(StartupEventArgs e)
{
  checkProcess();
}
wpf

0 人点赞