如何确保我的应用程序的单个实例,并在尝试打开第二个实例时将焦点设置为该应用程序?如何强制执行我的应用程序的单个实例?
我想:
public partial class Form1 : Form {
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern
IntPtr FindWindow(String lpClassName, String lpWindowName);
[DllImport("USER32.DLL")]
public static extern
Boolean SetForegroundWindow(IntPtr hWnd);
private void Form1_Load(object sender, EventArgs e)
{
bool isRunning = Process.GetProcesses()
.Where(p => p.MainWindowTitle.Contains(Text))
.Count() > 1;
if (isRunning)
{
FocusWindow(Text);
Application.Exit();
}
}
public static void FocusWindow(string title)
{
SetForegroundWindow(FindWindow(null, title));
}
}
这不是重点应用。我怎样才能解决这个问题?
你肯定FindWindow函数返回一个有效的HWND? – Tigran 2012-01-13 20:00:05
在启动表单之前检查Program.cs是否更有意义?用'count> 0'检查进程名称的实例。 – 2012-01-13 20:03:40
请参阅[C#中的单实例应用程序](http://blogs.msdn.com/b/tyler_whitney/archive/2005/11/28/497604.aspx) – LarsTech 2012-01-13 20:04:48