解决C# WINFORM程序只允许运行一个实例的几种方法详解
要实现程序的互斥,通常有下面几种方式,下面用 C# 语言来实现:
方法一:
使用线程互斥变量. 通过定义互斥变量来判断是否已运行实例.
把program.cs文件里的Main()函数改为如下代码:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace NetTools
{
static class Program
{
[DllImport("user32.dll")]
private static extern bool
FlashWindow(IntPtr hWnd, bool bInvert);
[DllImport("user32.dll")]
private
static extern bool FlashWindowEx(int
pfwi);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
bool
runone;
System.Threading.Mutex run = new
System.Threading.Mutex(true, "single_test",
out runone);
if
(runone)
{
run.ReleaseMutex();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FrmRemote frm = new FrmRemote();
int
hdc = frm.Handle.ToInt32(); // write to ...
Application.Run(frm);
IntPtr
a = new IntPtr(hdc);
}
else
{
MessageBox.Show("已经运行了一个实例了。");
//IntPtr
hdc = new IntPtr(1312810); // read from...
//bool
flash = FlashWindow(hdc, true);
}
}
}
}
说明:程序中通过语句 System.Threading.Mutex run =
new System.Threading.Mutex(true, "single_test", out runone);来创建一个互斥体变量run,其中"single_test"为互斥体名,在此方法返回时,如果创建了局部互斥体或指定的命名系统互斥体,则布尔值runone为true;如果指定的命名系统互斥体已存在,则为 false。已命名的互斥体是系统范围的。
方法二:采用判断进程的方式,我们在运行程序前,查找进程中是否有同名的进程,同时运行位置也相同程,如是没有运行该程序,如果有就就不运行.在C#中应用System.Diagnostics名字空间中的Process类来实现,主要代码如下:
1,在program.cs文件中添加函数如下:
public static System.Diagnostics.Process
RunningInstance()
{
System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
foreach
(System.Diagnostics.Process process in processes) //查找相同名称的进程
{
if
(process.Id != current.Id) //忽略当前进程
{ //确认相同进程的程序运行位置是否一样.
if
(System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", @"/")
== current.MainModule.FileName)
{ //Return
the other process instance.
return process;
}
}
} //No
other instance was found, return null.
return
null;
}
2,把Main ()函数改为如下代码:
static void Main()
{
if
(RunningInstance() == null)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
MessageBox.Show("已经运行了一个实例了。");
}
}
方法三:全局原子法,创建程序前,先检查全局原子表中看是否存在特定原子A(创建时添加的),存在时停止创建,说明该程序已运行了一个实例;不存在则运行程序并想全局原子表中添加特定原子A;退出程序时要记得释放特定的原子A哦,不然要到关机才会释放。C#实现如下:
1.申明WinAPI函数接口
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
public static extern UInt32 GlobalAddAtom(String
lpString); //添加原子
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
public static extern UInt32 GlobalFindAtom(String
lpString); //查找原子
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
public static extern UInt32 GlobalDeleteAtom(UInt32
nAtom); //删除原子
2.修改Main()函数如下:
static void Main()
{
if
(GlobalFindAtom("jiaao_test") ==
77856768) //没找到原子"jiaao_test"
{
GlobalAddAtom("jiaao_test"); //添加原子"jiaao_test"
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
MessageBox.Show("已经运行了一个实例了。");
}
}
3.在FormClosed事件中添加如下代码:
GlobalDeleteAtom(GlobalFindAtom("jiaao_test"));//删除原子"jiaao_test"
方法四:通过进程判断是否启动:
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//获取当前进程的ID
int pId = Process.GetCurrentProcess().Id;
bool isRun = false;
foreach (Process p in Process.GetProcessesByName("CallMaster"))
{
//取得当前程序的进程,进行比较
if (Common.GetPath().ToLower() == p.MainModule.FileName.ToLower())
{
if (pId != p.Id)
{
isRun = true;
break;
}
}
}
if (isRun==true)
{
Application.Exit();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
利用放射获取当前应用程序的全路径:
public static string GetPath()
{
return System.Reflection.Assembly.GetExecutingAssembly().Location;
}
方法五:通过线程互斥判断是否启动:
static class Program
{
private static System.Threading.Mutex mutex;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
mutex = new System.Threading.Mutex(true, "OnlyRun");
if (mutex.WaitOne(0, false))
{
Application.Run(new MainForm());
}
else
{
MessageBox.Show("程序已经在运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
Application.Exit();
}
}
}
另附:c#中怎样判断一个程序是否正在运行?
if (System.Diagnostics.Process.GetProcessesByName("程序进程中的名称").ToList().Count > 0)
{
//存在
}
else
{
//不存在
}
最新文章
- C# Azure 存储-Blob
- CSV导入
- mobx源码解读3
- How to get the Current Controller Name, Action, or ID in ASP.NET MVC
- Apache MPM winnt
- 完整学习git二 git 暂存区
- [大牛翻译系列]Hadoop(7)MapReduce:抽样(Sampling)
- JS属性
- MySQL数据库传输BLOB类型数据丢失 解决办法
- table新增空白行到首行
- nRF51800 蓝牙学习 进程记录 1:感想
- javascript 特殊的面向对象以及继承详解(入门篇)
- 如何将程序集安装到全局程序集缓存GAC
- ubuntu18.04静态ip设置
- IIS7 开发与 管理 编程 之 Microsoft.Web.Administration
- 超级干货 :一文读懂数据可视化 ZT
- nagios系列(八)之nagios通过nsclient监控windows主机
- LeetCode OJ 145. Binary Tree Postorder Traversal
- jQuery 与 prototype 共存
- fastJson去掉指定字段