关于SetForegroundWindow调用失败的处理

来源:互联网 发布:万科翡翠系 知乎 编辑:程序博客网 时间:2024/06/06 04:06

今天在尝试置前一个窗口的时候,发现调用SetForegroundWindow失败,查看了MSDN对该函数的解释:

The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true: 

1、The process is the foreground process. 
2、The process was started by the foreground process. 
3、The process received the last input event. 
4、There is no foreground process. 
5、The foreground process is being debugged. 
6、The foreground is not locked (see LockSetForegroundWindow). 
7、The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo). 

上述的情况就详细说明了SetForegroundWindow调用失败的情况。而我的程序之所以不能置顶的原因就是不满足上面的任何一种情况。

A process that can set the foreground window can enable another process to set the foreground window by calling theAllowSetForegroundWindow function.这句话说的是一个可以置前的窗口可以通过调用AllowSetForegroundWindow来对另一个进程进行允许置前的操作。The process specified bydwProcessId loses the ability to set the foreground window the next time the user generates input, unless the input is directed at that process, or the next time a process callsAllowSetForegroundWindow, unless that process is specified. 这句话说的是通过AllowSetForegroundWindow指定的进程会失去可以置前的能力,当用户在该进程进行输入或者使用Allow函数指定该进程时,该进程的置前能力依然可以保留。而下面的代码据说是微软的例子来实现使窗口置前。应该就是使进程满足上面的第三个条件来实现置前的。

if(hWnd){            HWND hForeWnd = ::GetForegroundWindow();            DWORD dwForeID = ::GetWindowThreadProcessId(hForeWnd,NULL);            DWORD dwCurID = ::GetCurrentThreadId();            ::AttachThreadInput(dwCurID,dwForeID,TRUE);            ::ShowWindow(hWnd,SW_SHOWNORMAL);            ::SetWindowPos(hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOSIZE|SWP_NOMOVE);            ::SetWindowPos(hWnd,HWND_NOTOPMOST,0,0,0,0, SWP_NOSIZE|SWP_NOMOVE);            ::SetForegroundWindow(hWnd);            ::AttachThreadInput(dwCurID,dwForeID,FALSE);
//hWnd就是需要置前的窗口句柄}


0 0
原创粉丝点击