Alexey Kulikov
Alexey Kulikov

Reputation: 1147

Get handle of focused control from another applications window

I have an application has window this some controls (buttons, edits etc). I need to simulate user event (Like Tab click and input text). I'm using keybd_event to move focus between tab ordered controls (editboxes) and input text to them. But I need to know handle of current focused control (for example for get text from it or change its styles). How can I solve it?

ps I'm writing Delphi now but it does not matter (Win-API everywhere the same).

Upvotes: 4

Views: 5795

Answers (3)

Danil
Danil

Reputation: 895

I converted pascal code of Sertac Akyuz 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.
    }
}

Upvotes: 0

Sertac Akyuz
Sertac Akyuz

Reputation: 54812

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

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;

Upvotes: 5

gmorrow
gmorrow

Reputation: 101

GetDlgItem from the Win-API returns a value that is the window handle of the specified control.

Upvotes: 0

Related Questions