Talikag
July 23rd, 2010, 01:03 PM
I'm trying to get the HWND of the focused control in the system. This control is not necessarily in my thread. I've tried this:
IntPtr IntPtrLocalFocus = GetFocus();
IntPtr IntPtrFore = GetForegroundWindow();
if (IntPtrFore == IntPtr.Zero)
return IntPtr.Zero;
Int32 dwCurrID = GetCurrentThreadId();
Int32 dwForeID = GetWindowThreadProcessId(IntPtrFore, IntPtr.Zero);
if (dwForeID == dwCurrID)
return IntPtrLocalFocus;
if (AttachThreadInput(dwCurrID, dwForeID, 1) == IntPtr.Zero)
return IntPtr.Zero;
IntPtr IntPtrGlobalFocus = GetFocus();
AttachThreadInput(dwCurrID, dwForeID, 0);
//Restore local focus
SetFocus(IntPtrLocalFocus);
return IntPtrGlobalFocus;
However, it doesn't work perfectly. For example, sometimes when an edit control is focused, the code above will return the form which contains the edit control, and not the edit control itself.
Am I missing something?
IntPtr IntPtrLocalFocus = GetFocus();
IntPtr IntPtrFore = GetForegroundWindow();
if (IntPtrFore == IntPtr.Zero)
return IntPtr.Zero;
Int32 dwCurrID = GetCurrentThreadId();
Int32 dwForeID = GetWindowThreadProcessId(IntPtrFore, IntPtr.Zero);
if (dwForeID == dwCurrID)
return IntPtrLocalFocus;
if (AttachThreadInput(dwCurrID, dwForeID, 1) == IntPtr.Zero)
return IntPtr.Zero;
IntPtr IntPtrGlobalFocus = GetFocus();
AttachThreadInput(dwCurrID, dwForeID, 0);
//Restore local focus
SetFocus(IntPtrLocalFocus);
return IntPtrGlobalFocus;
However, it doesn't work perfectly. For example, sometimes when an edit control is focused, the code above will return the form which contains the edit control, and not the edit control itself.
Am I missing something?