我不久前使用本网站上另一个问题和答案中的一些 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
或false
返回SingleApplication.Run()
以了解您的程序是否正在启动。它会阻塞直到Application.Run()
正常退出并返回 true,或者如果程序已经在运行,它会立即返回 false。