使用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 @   .拾贰  阅读(36)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示