C#实现单实例运行的方法,也有多种,比如利用 Process 查找进程的方式,利用 API findwindow 查找窗体的方式,还有就是 利用 Mutex 原子操作,上面几种方法中, 综合考虑利用 Mutex 的方式是较好的选择。
[STAThread]
static void Main()
{
bool isAppRunning = false;
System.Threading.Mutex mutex = new System.Threading.Mutex(
true,
System.Diagnostics.Process.GetCurrentProcess().ProcessName,
out isAppRunning);
if (!isAppRunning)
{
MessageBox.Show("本程序已经在运行了,请不要重复运行!");
Environment.Exit(1);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
使用Process 查找进程的方式会报错:System.ComponentModel.Win32Exception 中第一次偶然出现的“System.dll”类型的异常
原因可能是因为:
有些进程,如:system 系统空闲进程,当前程序没有权限获取相关信息或有些程序没有process.MainModule.FileName这些属性
示例代码:
bool result = false;
try
{
Process me = Process.GetCurrentProcess();
Process[] us = Process.GetProcesses();
Process another = null;
foreach (var p in us)
{
try
{
if (p.Id != me.Id && p.MainModule.FileName == me.MainModule.FileName)
{
another = p;
break;
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
if (another != null)
{
MessageBox.Show("程序已运行", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
result = true;
}
}
catch (Exception e)
{
MessageBox.Show(e.StackTrace+“\n”+ e.Message);
result = true;
}
return result;.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
http://xxinside.blogbus.com/logs/47162540.html
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }