最近做项目遇到了一个问题,用DllInject到所有进程中,然后创建一个线程调用函数GetFocus,当返回为NULL.非常的奇怪.Google了一下,才知GetFocus函数只能在窗体处理函数的线程中使用,其他的线程都返回为NULL.
下面这篇是原文
By Alexander Shargin, August 20, 2004.
GetFocus is a very useful API function used to find window which has keyboard focus. However, this function has a limitation - focused window must be created by the calling thread or GetFocus will return NULL. On desktop Windows it was possible to walkaround this problem using AttachThreadInput function. However, on CE-based devices this function is not available. So, how can I use GetFocus to find focused window created by another process?
To make GetFocus work, you need to call it from a thread which created focused window. Usually (though not quite always) this is the same thread which created top-level foreground window (obtained with GetForegroundWindow). The trick is to subclass this window and the send it a special message which will be processed by your window proc. Since your window proc will be called by a thread in another process, you can just call GetFocus and return HWND as LRESULT to your own process. Note that on desktop this trick will not work since each process has its own address space and subclassing between process boundaries is not possible. But on CE it does work.
I've written a small function, GetFocusEx, which uses the trick described above. You can use it in your projects the same way you use GetFocus. GetFocusWindowProc is a window proc assigned to foreground window. If it gets special message (registered with RegisterWindowMessage function) it calls GetFocus and returns obtained HWND as LRESULT. Otherwise it just forwards messages to original window proc using CallWindowProc function.
static WNDPROC g_pOldWndProc = NULL;
static UINT g_uGetFocusMessage = RegisterWindowMessage(_T("SpecialGetFocusMessage"));
static LRESULT WINAPI GetFocusWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if(uMsg == g_uGetFocusMessage)
{
return (LRESULT)GetFocus();
}
else
{
return CallWindowProc(g_pOldWndProc, hWnd, uMsg, wParam, lParam);
}
}
HWND GetFocusEx()
{
HWND hWnd = GetForegroundWindow();
if(!IsWindow(hWnd))
return NULL;
g_pOldWndProc = (WNDPROC)GetWindowLong(hWnd, GWL_WNDPROC);
SetWindowLong(hWnd, GWL_WNDPROC, (LONG)GetFocusWindowProc);
HWND hResult = (HWND)SendMessage(hWnd, g_uGetFocusMessage, 0, 0);
SetWindowLong(hWnd, GWL_WNDPROC, (LONG)g_pOldWndProc);
g_pOldWndProc = NULL;
return hResult;
}
原始连接 http://www.smartphonedn.com/qa/getfocusip.html