保证SetForegroundWindow执行成功

网上搜索到的办法有两个,

第一个没自测

保证SetForegroundWindow成功
在SetForegroundWindow之前比较早的时候(比如main函数里)调用一下以下代码:

DWORD dwTimeout = -1;  
SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, (LPVOID)&dwTimeout, 0);  
if (dwTimeout >= 100) {  
    SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (LPVOID)0, SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);  
}

第二个自测没问题

HWND hForeWnd = NULL; 
HWND hWnd= FindWindow(NULL, ""); 
DWORD dwForeID; 
DWORD dwCurID; 
 
hForeWnd =  GetForegroundWindow(); 
dwCurID =  GetCurrentThreadId(); 
dwForeID =  GetWindowThreadProcessId( hForeWnd, NULL ); 
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);
参考链接:
http://www.cnblogs.com/ziwuge/archive/2012/01/06/2315342.html