2014-02-14 113 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); 

感谢反正。