有很多方法可以解决这个问题,即您可以在启动控制台应用程序上运行,该应用程序将运行并集中您的程序:
[STAThread]
static void Main(string[] args)
{
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "calc";
myProcess.Start();
IntPtr hWnd = myProcess.Handle;
SetFocus(new HandleRef(null, hWnd));
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr SetFocus(HandleRef hWnd);
您可以托管一个 Windows 服务应用程序并使用计时器检查您的应用程序是否处于活动状态并且已聚焦,或者您可以使用热键将其重新聚焦: http: //www.codeproject.com/KB/miscctrl/ashsimplehotkeys.aspx
已编辑
这是控制台应用程序,它将使您的应用程序保持活力和专注(经过测试)。我需要找到 Windows 服务的解决方法,因为 vista 发生了一些变化,并且从服务中盯着看时表单是不可见的:P
static Process myProcess;
[STAThread]
static void Main(string[] args)
{
for (int i = 0; i < 10000; i++)
{
//count how many procesess with this name are active if more than zero its still alive
Process[] proc = Process.GetProcessesByName("myprog");
if (proc.Length > 0)
{
//its alive check if it has focus
if (proc[0].MainWindowHandle != GetForegroundWindow())
{
SetFocus(proc[0].MainWindowHandle);
}
}
//no process start new one and focus on it
else
{
myProcess = new Process();
myProcess.StartInfo.FileName = "C:\\aa\\myprog.exe";
myProcess.Start();
SetFocus(myProcess.Handle);
}
Thread.Sleep(1000);
}
}
private static void SetFocus(IntPtr handle)
{
SwitchToThisWindow(handle, true);
}
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);