星期日, 1月 18, 2009

如何維持.net程式單一執行個體應用程式

VB專案可以很開心的依以下路徑設定 就完成這限制
「專案=>屬性=>應用程式=>建立單一執行個體應用程式 」

不過其他的如C#等語言 就得自己寫程式
C#裡
/*
Code Snippet
Just add that piece of code (here in C#) in your main method (you need to
include the System.Diagnostic namespace) :
*/
Process currentProcess = Process.GetCurrentProcess();

Process [] allProcesses =
Process.GetProcessesByName(currentProcess.ProcessN ame);

if (allProcesses.Length > 1)
{
MessageBox.Show(currentProcess.ProcessName + " is already running !",
currentProcess.ProcessName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
//do your stuff here
}

VB
/*
Code Snippet
In the VB.NET application:
*/
Dim m As Mutex = _
New Mutex(False, "{11C92606-65D9-4df2-9AEA-B6A4DA91BCE2}")
If m.WaitOne(10, False) Then
Application.Run(New Form1())
m.ReleaseMutex()
Else
MessageBox.Show("Application already running!")
End If


Reference:
[VB 2005]如何避免程式(.exe)連開兩個以上

後記
除了維持單一執行應用程式外
應該不只是關閉新開的程式,而且要喚起即有的程式視窗
據說一般是利用hook達成... 等研究出來再補上

沒有留言: