我不得不解决类似的问题,我不得不做一些pInvoking把它完成。见下面的代码。
delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
public static class WindowEnumerator
{
[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("USER32.DLL")]
private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("USER32.DLL")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("USER32.DLL")]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("USER32.DLL")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("USER32.DLL")]
private static extern IntPtr GetShellWindow();
public static IDictionary<IntPtr, string> GetOpenWindowsFromPID(int processID)
{
IntPtr hShellWindow = GetShellWindow();
Dictionary<IntPtr, string> dictWindows = new Dictionary<IntPtr, string>();
EnumWindows(delegate(IntPtr hWnd, int lParam)
{
if (hWnd == hShellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
int length = GetWindowTextLength(hWnd);
if (length == 0) return true;
uint windowPid;
GetWindowThreadProcessId(hWnd, out windowPid);
if (windowPid != processID) return true;
StringBuilder stringBuilder = new StringBuilder(length);
GetWindowText(hWnd, stringBuilder, length + 1);
dictWindows.Add(hWnd, stringBuilder.ToString());
return true;
}, 0);
return dictWindows;
}
}
...
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
...
Process yourProcess = ???;
Dictionary<IntPtr, string> windows = (Dictionary<IntPtr, string>)WindowEnumerator.GetOpenWindowsFromPID(yourProcess.Id);
IntPtr mainWindowHandle = IntPtr.Zero;
foreach (KeyValuePair<IntPtr, string> pair in windows)
{
if (pair.Value.ToUpperInvariant() == "Main Window Title")
{
mainWindowHandle = pair.Key;
break;
}
}
if (mainWindowHandle != IntPtr.Zero)
{
if (IsIconic(mainWindowHandle))
{
ShowWindow(mainWindowHandle, 9);
}
SetForegroundWindow(mainWindowHandle);
}
你是什么意思“叫他们时,他们已经在运行”是什么意思?你只是想让他们把注意力集中在用户的电脑上吗?你是否试图为正在运行的应用程序调用一些API? –
是否确定要切换到其他应用程序(与在应用程序中嵌入浏览器控件相反)?有些背景在这里会有帮助。 如果你真的想切换,我想你想要的是(COM)Interop API(Google是你的朋友:) - 这应该允许你切换到应用程序(如果已经运行)或启动(如果没有)。 – David
我只是想切换到另一个正在运行的应用程序。不管是什么应用程序 - 我只是想通过按钮事件来做到这一点。根据我的理解,您可以从任务管理器中显示的进程名称中调用它。它是一个C#winform我工作。 – Steve