用Mutex实现程序单实例运行无效的问题

cncrazyzz 2010-05-04 11:33:50
[STAThread]
static void Main()
{
bool createdNew = false;
Mutex _mutex = new Mutex(true, "AddBook", out createdNew);//互斥

if (!createdNew)
{
MessageBox.Show("请不要重复运行程序");
return;
}

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainFM());
}

是参考的网上写的,可是我多次运行的时候createdNew始终是true,请高手指点!
...全文
153 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
skep99 2010-05-04
  • 打赏
  • 举报
回复
我的是这么写的:

[STAThread]
static void Main()
{

Mutex mutex = new Mutex(false, "myForm");
bool Running = !mutex.WaitOne(50, false);
if (Running)
{
mutex.Close();
MessageBox.Show("应用程序已经启动!");
return;
}

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form3());
}
捷哥1999 2010-05-04
  • 打赏
  • 举报
回复

1. API函数的声明
[DllImport("User32.dll")])
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

// 0-Hidden, 1-Centered, 2-Minimized, 3-Maximized
private const int WS_SHOWNORMAL = 3;

2. 查找并激活已经存在的程序(仅应用于进程名相同的程序)
private static bool ExistRunningInstance()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] procList = Process.GetProcessesByName(currentProcess.ProcessName);

foreach (Process proc in procList)
{
// Found a running instance
if (proc.Id != currentProcess.Id)
{
// Active the running instance 3
ShowWindowAsync(proc.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(proc.MainWindowHandle);

return true;
}
}

return false;
}

3. 在Main函数入口判断
[STAThread]
static void Main()
{
// Control only one instance with the same process name can run
if (ExistRunningInstance())
{
Environment.Exit(1);
}
}

捷哥1999 2010-05-04
  • 打赏
  • 举报
回复
看看这个例子:
http://www.paiming.org/bbs/read.php?tid=15611
rainingheart 2010-05-04
  • 打赏
  • 举报
回复
多次运行如多次按F5,还是一次一个
你运行两次exe试下

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧