C#中让本身程序不能同时执行多个
来源:互联网 发布:ipad 淘宝 卖家版 app 编辑:程序博客网 时间:2024/05/22 06:32
方法一:使用Mutex来进行
1. 首先要添加如下的namespace:
using System.Threading;
2. 修改系统Main函数,大致如下:
bool bCreatedNew;
//Create a new mutex using specific mutex name
Mutex m =new Mutex( false, "myUniqueName", out bCreatedNew );
if( bCreatedNew )
Application.Run(new yourFormName());
如上面编码就可以了,要注意的一点是,在给Mutex起名字的时候,不要太简单,以防止和其他程序的Mutex重复,从而达不到所预想的效果。
方法二:使用Process来进行
1. 首先要添加如下的namespace:
using System.Diagnostics;
using System.Reflection;
2. 添加如下函数:
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
3. 修改系统Main函数,大致如下:
if( RunningInstance() == null )
Application.Run(new yourFormName());
如上面编码就可以了,要注意的一点是,在判断进程模块文件名是否相等这部分的代码,是可选的。如果当前的程序在文件系统中只存在一个的话,以上的方法是可以的;否则不要删除这部分的代码。
对比两种方法,就效率和简便性来说,前一种方法是最好的,也是我比较喜欢的;后一种方法,速度比较慢,其次通过ProcessName去系统中查寻,有可能查出来的Process并不是我想要得,虽说在后面加了文件目录判断,但是其含有潜在的问题(前面已经说出来)。不过,第一种方法也有缺陷,就是扩展性操作不方便,例如:让程序只运行一次,如果程序已经运行,把它弹出并显示到最前面。对于此,后一种方法就很有优势了。
程序示例:
private void btnOK_Click(object sender, EventArgs e)
{
if (GetProcess("SMS") >1)
{
MessageBox.Show("一台电脑只能登录一个用户!","提示");
return;
}
}
private int GetProcess(string strProcessName)
{
int nCount = 0;
System.Diagnostics.Process[] myPs;
myPs = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process p in myPs)
{
if (p.ProcessName.ToUpper() == strProcessName)
{
nCount++;
}
}
return nCount;
}
- C#中让本身程序不能同时执行多个
- C#中让本身程序不能同时执行多个
- delphi 设置程序不能同时打开多个
- Linux 同时在多个服务器中执行命令
- C# WindowsForm程序同时启动多个窗口类
- C# WindowsForm程序同时启动多个窗口类
- C#中实现同时上传多个附件
- 让iBatisNet同时使用多个数据库
- 让你的ipad同时运行两个或多个程序
- 【BASH】同时执行多个命令
- 实现多个手势同时执行
- 实现多个手势同时执行
- Android 多个animation同时执行
- ubuntu中sublime3在一个项目中不能同时打开多个文件
- CSS3的 transform属性,怎么才能让他同时执行多个不同动画(属性)效果
- springsecurity中如何做到多个用户不能使用同一个账号同时登陆系统
- VC中实现一个程序不能被同时打开多次
- 如何在多个新窗口中,同时执行不同的命令行
- jstl的用法--c:forEach||c:out
- 动态添加和删除文件选择框及脚本的兼容性问题。
- 微软:盗版伤害的不仅是软件公司
- 提供可定制软件
- Weblogic连接Oracle时NL Exception was generated错误
- C#中让本身程序不能同时执行多个
- symbian s60 vc设置
- C++基础试题
- NeuronDotNet——用户手册
- 最简短生动的次贷危机讲解
- JMS消息类型模型
- 传说中的剑客
- 有关excel表导入sql server 2005 的亲身经历
- 开发环境搭建(VC6版)