C# 限制软件单进程运行

该博客介绍了一个C#程序,通过检查当前运行的进程来确保同一时间只有一个实例在运行。如果检测到已有实例,则会显示消息框提示用户程序已在运行,否则将启动新的窗体。代码中使用了`Process`类来获取和比较进程信息。

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

  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Windows.Forms;
  4. using System.Diagnostics;
  5. using System.Reflection;
  6. namespace AvsRecoder
  7. {
  8.     static class Program
  9.     {
  10.         /// <summary>
  11.         /// 应用程序的主入口点。
  12.         /// </summary>
  13.         [STAThread]
  14.         static void Main()
  15.         {
  16.             Application.EnableVisualStyles();
  17.             Application.SetCompatibleTextRenderingDefault(false);
  18.             Process instance = RunningInstance();
  19.             if (instance == null)
  20.             {
  21.                 //如果没有其它例程,就新建一个窗体   
  22.                 Application.Run(new mainForm());
  23.             }
  24.             else
  25.             {
  26.                 MessageBox.Show("程序已在运行");
  27.             }
  28.         }
  29.         public static Process RunningInstance()
  30.         {
  31.             Process current = Process.GetCurrentProcess();
  32.             Process[] processes = Process.GetProcessesByName(current.ProcessName);
  33.             //遍历正在有相同名字运行的例程   
  34.             foreach (Process process in processes)
  35.             {
  36.                 //忽略现有的例程   
  37.                 if (process.Id != current.Id)
  38.                 {
  39.                     //确保例程从EXE文件运行   
  40.                     if (Assembly.GetExecutingAssembly().Location.Replace("/""//") ==
  41.                         current.MainModule.FileName)
  42.                     {
  43.                         //返回另一个例程实例   
  44.                         return process;
  45.                     }
  46.                 }
  47.             }
  48.             //没有其它的例程,返回Null   
  49.             return null;
  50.         }
  51.     }  // end class
  52. }   // end NameSpace
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值