SetActiveWindow(handle); SwitchToThisWindow(handle,true);
以前我也有ShowWindow(句柄,SW_SHOWMAXIMIZED);在其他2之前执行,但删除它因为它导致了奇怪的行为.
我当前实现的问题是偶尔会无法正确设置焦点.窗口将变为可见,但它的顶部仍然显示为灰色,就好像它没有聚焦一样.
有没有办法可靠地做到这一点,100%的时间工作,或不一致的行为是我无法逃避的副作用?如果您有任何建议或实施始终有效,请告诉我.
解决方法
AttachThreadInput
Windows created in different threads typically process input independently of each other. That is,they have their own input states (focus,active,capture windows,key state,queue status,and so on),and they are not synchronized with the input processing of other threads. By using the AttachThreadInput function,a thread can attach its input processing to another thread. This also allows threads to share their input states,so they can call the SetFocus function to set the keyboard focus to a window of a different thread. This also allows threads to get key-state information. These capabilities are not generally possible.
我不确定从(大概)Windows窗体使用此API的后果.也就是说,我在C中使用它来获得这种效果.代码如下所示:
DWORD currentThreadId = GetCurrentThreadId(); DWORD otherThreadId = GetWindowThreadProcessId(targetHwnd,NULL); if( otherThreadId == 0 ) return 1; if( otherThreadId != currentThreadId ) { AttachThreadInput(currentThreadId,otherThreadId,TRUE); } SetActiveWindow(targetHwnd); if( otherThreadId != currentThreadId ) { AttachThreadInput(currentThreadId,FALSE); }
targetHwnd是您要设置焦点的窗口的HWND.我假设您已经可以使用P / Invoke签名,因为您已经在使用本机API.