Get the focus control handle from another application window

I have a window in the application, these are some controls (buttons, edits, etc.). I need to simulate a custom event (e.g. Tab click and input text). I use keybd_eventto move focus between tab controls (editboxes) and text input. But I need to know the handle of the current focused control (for example, to get text from it or change its styles). How can I solve it?

ps I am writing Delphi now, but it does not matter (Win-API is the same everywhere).

+3
source share
3 answers

See the notes section in GetFocus'for an explanation of the example below.

function GetFocus: HWND;
var
  Wnd: HWND;
  TId, PId: DWORD;
begin
  Result := windows.GetFocus;
  if Result = 0 then begin
    Wnd := GetForegroundWindow;
    if Wnd <> 0 then begin
      TId := GetWindowThreadProcessId(Wnd, PId);
      if AttachThreadInput(GetCurrentThreadId, TId, True) then begin
        Result := windows.GetFocus;
        AttachThreadInput(GetCurrentThreadId, TId, False);
      end;
    end;
  end;
end;
+3

GetDlgItem Win-API , .

0

I converted the Pascal Sertac Akyuz code to C ++

#include "Windows.h"
#include <psapi.h> // For access to GetModuleFileNameEx
#include <iostream>
#include <string>


#ifdef _UNICODE
#define tcout wcout
#define tcerr wcerr
#else
#define tcout cout
#define tcerr cerr
#endif

HWND GetFocusGlobal()
{
    HWND Wnd;
    HWND Result = NULL;
    DWORD TId, PId;

    Result = GetFocus();
    if (!Result)
    {
        Wnd = GetForegroundWindow();
        if(Wnd)
        {
            TId = GetWindowThreadProcessId(Wnd, &PId);
            if (AttachThreadInput(GetCurrentThreadId(), TId, TRUE))
            {
                Result = GetFocus();
                AttachThreadInput(GetCurrentThreadId(), TId, FALSE);
            }            
        }
    }
    return Result;
}


int _tmain(int argc, _TCHAR* argv[])
{
    std::wstring state;

    while(1)
    {
        HWND focus_handle = GetFocusGlobal();

        if(focus_handle)
        {

            TCHAR text[MAX_PATH];
            GetClassName(focus_handle, text, MAX_PATH);

            const std::wstring cur_path(text);

            if(cur_path != state)
            {
                std::tcout << "new:" << focus_handle << " " << text << std::endl;
                state = cur_path;
            }

            }

        Sleep(50); // Sleep for 50 ms.
    }
}
0
source

All Articles