2014-02-14 45 views
1

我想設置一個Chrome窗口前臺並激活它,以獲得鍵盤的焦點。我的代碼適用於記事本或IE,但不適用於谷歌瀏覽器。設置活動的Chrome窗口(C++)

//Getting the HWND of Chrome 
HWND chromeWindow = FindWindow("Chrome_WidgetWin_1", NULL); 

DWORD dwCurrentThread = GetCurrentThreadId(); 
DWORD dwFGThread = GetWindowThreadProcessId(GetForegroundWindow(), NULL); 
AttachThreadInput(dwCurrentThread, dwFGThread, TRUE); 

//Actions 
AllowSetForegroundWindow(ASFW_ANY); 
bool fore =SetForegroundWindow(chromeWindow); 
if(fore==false){cout << "fore failed"<<endl;} 

bool capture = SetCapture(chromeWindow); 
if(capture==false){cout << "capture failed" <<endl;} 

bool focus = SetFocus(chromeWindow); 
if(focus==false){cout << "focus failed"<<endl;} 

bool active = SetActiveWindow(chromeWindow); 
if(active==false){cout << "active failed"<<endl;} 

//Finishing 
AttachThreadInput(dwCurrentThread, dwFGThread, FALSE); 

該代碼將Google Chrome窗口設置爲前景,但未將其激活或將鍵盤對焦在其上。我不知道什麼是錯的。顯示結果爲:

capture failed. 
focus failed. 
active failed. 

我該怎麼辦?

回答

2

好吧,我幾天前找到答案。

有兩個谷歌瀏覽器的窗口具有相同的類名「Chrome_WidgetWin_1」,我試圖激活第一個,當有用的窗口是第二個。所以,我搜索了第二個窗口,隨後在該窗口中使用了SetForegroundWindow()。

結果是:

//Getting the HWND of Chrome 
HWND chromeWindow = FindWindow("Chrome_WidgetWin_1", NULL); 
HWND chrome = GetWindow(chromeWindow, GW_HWNDNEXT); 

//Setting the window to the foreground (implies focus and activating) 
SetForegroundWindow(chrome); 

感謝反正。