关于SetForegroundWindow调用失败的处理

今天在尝试置前一个窗口的时候,发现调用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 the AllowSetForegroundWindow function.这句话说的是一个可以置前的窗口可以通过调用AllowSetForegroundWindow来对另一个进程进行允许置前的操作。The process specified by dwProcessId 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 calls AllowSetForegroundWindow, 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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值