从另一个应用程序窗口获取集中控制的句柄

时间:2014-02-05 12:30:06

标签: c++ c windows delphi

我有一个应用程序有窗口这一些控件(按钮,编辑等)。我需要模拟用户事件(如Tab键单击和输入文本)。我正在使用keybd_event在选项卡有序控件(编辑框)之间移动焦点并将输入文本移到它们之间。但是我需要知道当前聚焦控件的处理(例如,从中获取文本或更改其样式)。我该如何解决?

PS 我现在正在编写Delphi,但这并不重要(Win-API到处都是这样)。

3 个答案:

答案 0 :(得分:3)

有关以下示例的说明,请参阅GetFocus'文档中的备注部分。

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;

答案 1 :(得分:0)

来自Win-API的

GetDlgItem 返回一个值,该值是指定控件的窗口句柄。

答案 2 :(得分:0)

我将Sertac Akyuz的pascal代码转换为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.
    }
}
相关问题