使用WPF 當程式已開啟時第二次開啟程式直接彈出第一次開啟的程式

.拾贰發表於2024-06-11

在程式碼中增加

  [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

相關文章