作者liaommx (Orz)
看板C_Sharp
标题[问题] winform防止程式重复执行,唤醒已执行程式?
时间Mon Mar 8 21:10:47 2010
我现在有一个winform程式,
我用以下的程式码,避免重复执行同样的程式,
(若已经有同一个程式在执行了,直接关闭现在执行的这个)
但是,假设我要将原本缩小到工具列的程式,
唤醒到最上面来,
并让使用者focus上去,
我该怎麽改写这个程式呢?
==
//宣告於最外面,是公变数,避免程式重复执行的变数
private System.Threading.Mutex appMutex;
// 防止程式重复执行
private void Form1_Load(object sender, EventArgs e)
{
Application.ApplicationExit += new
EventHandler(Application_ApplicationExit);
bool createNew;
appMutex = new System.Threading.Mutex(true, "APName", out
createNew);
if (!createNew)
{
MessageBox.Show("You just execute the same program");
appMutex.Close();
appMutex = null;
Close();
return;
}
else
{
MessageBox.Show("this is the first time execute");
}
}
private void Application_ApplicationExit(object sender, EventArgs e)
{
if (appMutex != null)
{
appMutex.ReleaseMutex();
appMutex.Close();
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.169.231.3
1F:→ mortleo:ShowWindowAsync、SetForegroundWindow 03/08 21:30
2F:推 leicheong:其实... 用FileLock是最准确的方法了... 03/08 23:47
3F:→ leicheong:产生一个档案... 用exclusive access开启, 开不到就离开 03/08 23:48
4F:→ leicheong:那样... 03/08 23:49