Getting focused control
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Getting focused control

  1. #1
    Join Date
    Jan 2007
    Posts
    491

    Getting focused control

    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:
    Code:
    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?
    Last edited by Talikag; July 23rd, 2010 at 01:06 PM.

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Wallisellen (ZH), Switzerland
    Posts
    17,258

    Re: Getting focused control

    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.
    Victor Nijegorodov

  3. #3
    Join Date
    Jan 2007
    Posts
    491

    Re: Getting focused control

    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.

  4. #4
    Join Date
    Nov 2000
    Location
    Voronezh, Russia
    Posts
    5,914

    Re: Getting focused control

    Best regards,
    Igor

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center