我正在向一个应用程序添加一些代码,如果它还没有运行,它将启动另一个应用程序,或者如果是,请将它带到前面.这需要少量的interop/WinAPI代码,我从其他网站获得了示例,但似乎无法在Win7中工作.
如果窗口处于某种可见状态,则API的SetForegroundWindow方法就像处理一样(这将是主要情况,根据公司策略,如果外部应用程序正在运行,则不应该最小化).但是,如果它被最小化(例外但很重要,因为我的应用程序在这种情况下似乎什么也不做),这个方法和ShowWindow/ShowWindowAsync实际上都不会从任务栏中恢复窗口; 所有方法都只是突出显示任务栏按钮.
这是代码; 大部分工作都很好,但是对ShowWindow()的调用(我也尝试过ShowWindowAsync),无论我发送的命令是什么,都不会做我想要的事情:
[DllImport("user32.dll")]
private static extern int SetForegroundWindow(IntPtr hWnd);
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_RESTORE = 9;
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
...
//The app is named uniquely enough that it can't be anything else,
//and is not normally launched except by this one.
//so this should normally return zero or one instance
var processes = Process.GetProcessesByName("ExternalApp.exe");
if (processes.Any()) //a copy is already …Run Code Online (Sandbox Code Playgroud)