C#程序多用户只启动一个进程的方法[转载]

本文介绍了一种使用 C# 实现的应用程序单实例启动的方法。通过检查当前运行的进程,如果存在相同实例则激活该窗口,否则创建新实例并运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://greenlandy.blogbus.com/logs/14388828.html

Code Snippet
  1. [STAThread]
  2.      private static void Main()
  3.      {
  4.          Application.EnableVisualStyles();
  5.          Application.SetCompatibleTextRenderingDefault(false);
  6.          var wb = new Form1();
  7.          Process current = Process.GetCurrentProcess();
  8.          bool newinstance = true;
  9.          Process[] processes = Process.GetProcessesByName(current.ProcessName);
  10.  
  11.          //?历正在有相同名字??的例程  
  12.          foreach (Process process in processes)
  13.          {
  14.              //忽略现有的例程  
  15.              if (process.Id != current.Id)
  16.              {
  17.                  //确保例程从EXE文件??  
  18.                  if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
  19.                  {
  20.                      //?回另一个例程实例  
  21.                      current = process;
  22.                      newinstance = false;
  23.                      break;
  24.                  }
  25.              }
  26.          }
  27.          if (newinstance)
  28.          {
  29.              Application.Run(wb);
  30.          }
  31.          else
  32.          {
  33.              ShowWindowAsync(current.MainWindowHandle, 1);
  34.  
  35.              //?置真实例程为foreground   window  
  36.              SetForegroundWindow(current.MainWindowHandle);
  37.          }
  38.      }

引入这两个API函数

Code Snippet
  1. [DllImport("User32.dll")]
  2. private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
  3.  
  4. [DllImport("User32.dll")]
  5. private static extern bool SetForegroundWindow(IntPtr hWnd);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值