Click to See Complete Forum and Search --> : Getting focused control


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?

VictorN
July 23rd, 2010, 03:13 PM
The Windows API GetFocus returns a window handle which type is HWND, not a IntPtr
So either your code is wrong or the Forum you chose for your problem is wrong.

Talikag
July 23rd, 2010, 03:23 PM
This code is not written in C++. IntPtr is just the replacement for HWND in the language the code was written.

I ran the code in C++ as well. If it makes any difference I can write here the C++ version of this code.

My question is about the API calls. I think the idea behind that code is right, but for some reason it doesn't work all the times.

Igor Vartanov
July 24th, 2010, 01:19 PM
GetGUIThreadInfo (http://msdn.microsoft.com/en-us/library/ms633506(VS.85).aspx)