使用WPF 当程序已打开时第二次打开程序直接弹出第一次打开的程序

在代码中增加

  [DllImport("user32.dll")]
  private static extern bool SetForegroundWindow(IntPtr hWnd);
  [DllImport("user32.dll")]
  private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
  [DllImport("user32.dll")]
  private static extern bool IsIconic(IntPtr hWnd);
  private const int SW_RESTORE = 9;
  /// <summary>
  /// 激活已打开窗口
  /// </summary>
  public static void RaiseOtherProcess()
  {
      Process proc = Process.GetCurrentProcess();
      foreach (Process otherProc in
      Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName))
      {
          if (proc.Id != otherProc.Id)
          {
              IntPtr hWnd = otherProc.MainWindowHandle;
              if (IsIconic(hWnd))
              {
                  ShowWindowAsync(hWnd, 9);
              }
              SetForegroundWindow(hWnd);
              break;
          }
      }
  }

然后就是调用:

  string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
  //检查进程是否已经启动,已经启动则退出程序,显示已启动的程序。
  if (System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)
  {
      RaiseOtherProcess();
      Application.Current.Shutdown();
      return;
  }

 

我是直接写在Application_Startup 中
来源:https://www.cnblogs.com/webenh/p/17639905.html

 

posted @ 2024-06-11 16:37  .拾贰  阅读(1)  评论(0编辑  收藏  举报