当前位置:编程学习 > C#/ASP.NET >>

C# 创建互斥程序_只允许运行一个程序实例

C# 创建互斥进程(程序) 互斥进程(程序), 简单点说,就是在系统中只能有该程序的一个实例运行. 现在很多软件都有这功能.

要实现程序的互斥,通常有下面几种方式,下面用 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文件中添加函数如下:

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,