窗口的最前端显示

来源:互联网 发布:卖家中心登陆淘宝网 编辑:程序博客网 时间:2024/04/30 13:09

需求:窗口最前端显示,窗口保持激活状态
但是用过很多方法都不可以
类似API:SetWindowPos(),ActivateTopParent()等等总是出现问题,后来codeobject找到了解决的方法,在这里分享一下

2种方式
1,类似Alt+Tab键切换窗口(因为是模拟按键,貌似会遗留下按键状态的异常,不过可以解决)

void SetForegroundWindowInternal(HWND hWnd)
{
if(!::IsWindow(hWnd)) return;

BYTE keyState[256] = {0};
//to unlock SetForegroundWindow we need to imitate Alt pressing
if(::GetKeyboardState((LPBYTE)&keyState))
{
if(!(keyState[VK_MENU] & 0x80))
{
::keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
}
}

::SetForegroundWindow(hWnd);

if(::GetKeyboardState((LPBYTE)&keyState))
{
if(!(keyState[VK_MENU] & 0x80))
{
::keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
}
}
2

void SetForegroundWindowInternal(HWND hWnd)
{
if(!::IsWindow(hWnd)) return;

//relation time of SetForegroundWindow lock
DWORD lockTimeOut = 0;
HWND hCurrWnd = ::GetForegroundWindow();
DWORD dwThisTID = ::GetCurrentThreadId(),
dwCurrTID = ::GetWindowThreadProcessId(hCurrWnd,0);

//we need to bypass some limitations from Microsoft :)
if(dwThisTID != dwCurrTID)
{
::AttachThreadInput(dwThisTID, dwCurrTID, TRUE);

::SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT,0,&lockTimeOut,0);
::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT,0,0,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);

::AllowSetForegroundWindow(ASFW_ANY);
}

::SetForegroundWindow(hWnd);

if(dwThisTID != dwCurrTID)
{
::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT,0,(PVOID)lockTimeOut,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
::AttachThreadInput(dwThisTID, dwCurrTID, FALSE);
}
}

 

原文:http://www.codeproject.com/Tips/76427/How-to-bring-window-to-top-with-SetForegroundWindo.aspx

 

原创粉丝点击