我前一段時間使用一些R & D(Ripoff和Deploy)從本網站的其他問題和答案(找不到原文)寫了這段代碼,它檢查程序是否已經從相同的路徑(只要exe是從不同的路徑啓動,這允許多個實例)。我使另一個程序成爲活動窗口(它甚至在最小化時恢復窗口),甚至不告訴用戶有重複的實例打開。
public static class SingleApplication
{
[DllImport("user32.Dll")]
private static extern int EnumWindows(EnumWinCallBack callBackFunc, int lParam);
[DllImport("User32.Dll")]
private static extern void GetWindowText(int hWnd, StringBuilder str, int nMaxCount);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);
static Mutex mutex;
const int SW_RESTORE = 9;
static string sTitle;
static IntPtr windowHandle;
delegate bool EnumWinCallBack(int hwnd, int lParam);
private static bool EnumWindowCallBack(int hwnd, int lParam)
{
windowHandle = (IntPtr)hwnd;
StringBuilder sbuilder = new StringBuilder(256);
GetWindowText((int)windowHandle, sbuilder, sbuilder.Capacity);
string strTitle = sbuilder.ToString();
if (strTitle == sTitle && hwnd != lParam)
{
ShowWindow(windowHandle, SW_RESTORE);
SetForegroundWindow(windowHandle);
return false;
}
return true;
}
/// <summary>
/// Execute a form application. If another instance already running on the system activate previous one.
/// </summary>
/// <param name="frmMain">main form</param>
/// <returns>true if no previous instance is running</returns>
public static bool Run(System.Windows.Forms.Form frmMain)
{
if (IsAlreadyRunning())
{
sTitle = frmMain.Text;
EnumWindows(new EnumWinCallBack(EnumWindowCallBack), frmMain.Handle.ToInt32());
return false;
}
Application.Run(frmMain);
return true;
}
/// <summary>
/// Checks using a Mutex with the name of the running assembly's location
/// </summary>
/// <returns>True if the assembly is already launched from the same location, false otherwise.</returns>
private static bool IsAlreadyRunning()
{
string strLoc = Assembly.GetEntryAssembly().Location;
FileSystemInfo fileInfo = new FileInfo(strLoc);
string name = fileInfo.Name;
mutex = new Mutex(true, name);
if (mutex.WaitOne(0, false))
{
return false;
}
return true;
}
}
它被用作以下
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SingleApplication.Run(new Form1());
}
}
如果你願意,你可以檢查是否true
或從SingleApplication.Run()
返回找出如果你的程序正在啓動或不false
。它會阻止,直到Application.Run()
通常會退出並返回true,或者如果程序已經運行,它立即返回false。
你可以嘗試進程間的通信,使您的流程封閉自己 –
一點比更溫柔'Process.Kill()' – jglouie