整理一些将窗口显示在前台办法

   windows下简单的调用Setforegroundwindow有时候并不能将窗口置最前,不妨试试以下办法。

1、先置topmost,然后取消
 SetWindowPos(HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
 SetWindowPos(HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);

2、改变系统环境参数

这些定义winuser.h里都有的
#define SPI_GETFOREGROUNDLOCKTIMEOUT 0x2000
#define SPI_SETFOREGROUNDLOCKTIMEOUT 0x2001
#define SPIF_UPDATEINIFILE 0x0001
#define SPIF_SENDWININICHANGE 0x0002

先设置环境变量
DWORD lockTime = 0;
SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &lockTime, 0);
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0,
                     SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);

退出程序时还原环境变量

SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, lockTime,
SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
3、AllowSetForegroundWindow
 HMODULE hModule = NULL;
ASFW_PTR pProcAddress = NULL;

hModule = GetModuleHandle("User32");
 if (hModule != NULL)
pProcAddress = (ASFW_PTR)GetProcAddress(hModule, "AllowSetForegroundWindow");

if (pProcAddress != NULL)
{
nResult = (*pProcAddress)(-1);
  if (nResult == FALSE )
MessageBox(NULL, "Could not set foreground permission", NULL, MB_OK | MB_ICONERROR);
}
 4、使用AttachThreadInput

AttachThreadInput这个函数可以使两个线程的输入队列共享。 如果我们把当前的焦点的输入队列跟我们要显示的窗口的输入队列共享,我们就可以让我们的窗口SetForegroundWindow 成功,然后成功 获得焦点,显示在前台。

//捕捉并设置当前焦点窗口为我们的窗口
AttachThreadInput(
GetWindowThreadProcessId(
::GetForegroundWindow(),NULL),
GetCurrentThreadId(),TRUE);


SetForegroundWindow();
SetFocus();

//释放thread
AttachThreadInput(
GetWindowThreadProcessId(
::GetForegroundWindow(),NULL),
GetCurrentThreadId(),FALSE);

 

//代码2

HWND hWnd = ::FindWindow(_T("#32770"),_T(“test”));

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);
return 0;
}

 

posted @ 2014-05-08 17:48  vlan99  阅读(701)  评论(0编辑  收藏  举报