110,502
社区成员
发帖
与我相关
我的任务
分享
if (System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length > 1)
{
//这里怎么写才能能激活这个窗口呢???????????
}
else
{
Application.Run(new Form1());
}
C#单实例运行实现
在某些情况我们要求应用程序只能运行一次,后运行的实例要把之前运行的程序激活并自己退出。
在网上搜索了一些实现并根据自己的理解重新整理得出下面的实现代码:
1. API函数的声明
// Uses to active the exist window
[DllImport("User32.dll")]
public static extern void SetForegroundWindow(IntPtr hwnd);
[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. 查找并激活已经存在的程序(仅应用于进程名相同的程序)
///
/// Finds the running instance.
///
/// true if exist a running instace, otherwise false
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
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); // App is running, exit
}
// 程序真正运行的代码
}