Posted on 2008-06-11 23:06
buf 阅读(3807)
评论(0) 编辑 收藏 引用
/// <summary>
/// Win32 API Imports
/// </summary>
[DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")] private static extern bool IsZoomed(IntPtr hWnd);
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] private static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
[DllImport("user32.dll")] private static extern IntPtr AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, int fAttach);
/// <summary>
/// Win32 API Constants for ShowWindowAsync()
/// </summary>
private const int SW_HIDE = 0;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;
/// <summary>
/// Sets focus to this Window Object
/// </summary>
public void ActivateWindow(IntPtr hWnd)
{
if(hWnd == GetForegroundWindow())
return;
IntPtr ThreadID1 = GetWindowThreadProcessId(GetForegroundWindow(),IntPtr.Zero);
IntPtr ThreadID2 = GetWindowThreadProcessId(hWnd,IntPtr.Zero);
if (ThreadID1 != ThreadID2)
{
AttachThreadInput(ThreadID1,ThreadID2,1);
SetForegroundWindow(hWnd);
AttachThreadInput(ThreadID1,ThreadID2,0);
}
else
{
SetForegroundWindow(hWnd);
}
if (IsIconic(hWnd))
{
ShowWindowAsync(m_hWnd,SW_RESTORE);
}
else
{
ShowWindowAsync(hWnd,SW_SHOWNORMAL);
}
}
}
上面的代码是从CodeProject上
Window Hiding with C#一文中截取出来的,用于激活某个已运行的程序。
几个问题:
1、使用ShowWindowAsync而非ShowWindow是防止目标程序无响应时主调线程被阻塞
2、AttachThreadInput调用那一段代码不知道是啥目的
3、如果目标程序的主窗口已最大化且不在前端,该调用会让它正常显示,会有一点闪烁 2008年6月16日,22:18:17
注释掉ActivateWindow最后一段else部分的代码,就3所述的问题了:-)