C++ 从另一个应用程序窗口获取聚焦控件的句柄
我有一个应用程序有一些控件(按钮,编辑等)。我需要模拟用户事件(如单击选项卡和输入文本)。我正在使用C++ 从另一个应用程序窗口获取聚焦控件的句柄,c++,c,windows,delphi,C++,C,Windows,Delphi,我有一个应用程序有一些控件(按钮,编辑等)。我需要模拟用户事件(如单击选项卡和输入文本)。我正在使用keybd\u event在按选项卡排序的控件(编辑框)之间移动焦点,并向它们输入文本。但我需要知道当前焦点控件的句柄(例如从中获取文本或更改其样式)。我怎样才能解决它 ps 我现在正在编写Delphi,但这并不重要(Win API到处都是一样的)。从Win API返回一个值,该值是指定控件的窗口句柄。有关下面示例的解释,请参阅“文档”中的备注部分 function GetFocus: HWND;
keybd\u event
在按选项卡排序的控件(编辑框)之间移动焦点,并向它们输入文本。但我需要知道当前焦点控件的句柄(例如从中获取文本或更改其样式)。我怎样才能解决它
ps
我现在正在编写Delphi,但这并不重要(Win API到处都是一样的)。从Win API返回一个值,该值是指定控件的窗口句柄。有关下面示例的解释,请参阅“文档”中的备注部分
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;
函数GetFocus:HWND;
变量
Wnd:HWND;
工业贸易署署长:德沃德;;
开始
结果:=windows.GetFocus;
如果结果=0,则开始
Wnd:=GetForegroundWindow;
如果Wnd为0,则开始
TId:=GetWindowThreadProcessId(Wnd,PId);
如果AttachThreadInput(GetCurrentThreadId,TId,True),则开始
结果:=windows.GetFocus;
AttachThreadInput(GetCurrentThreadId,TId,False);
结束;
结束;
结束;
结束;
我将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.
}
}
#包括“Windows.h”
#包含//以访问GetModuleFileNameEx
#包括
#包括
#ifdef_UNICODE
#定义tcout wcout
#定义tcerr-wcerr
#否则
#定义输出cout
#定义tcerr cerr
#恩迪夫
HWND GetFocusGlobal()
{
HWND-Wnd;
HWND Result=NULL;
德沃德工业贸易署,PId;
结果=GetFocus();
如果(!结果)
{
Wnd=GetForegroundWindow();
如果(Wnd)
{
TId=GetWindowThreadProcessId(Wnd和PId);
if(AttachThreadInput(GetCurrentThreadId(),TId,TRUE))
{
结果=GetFocus();
AttachThreadInput(GetCurrentThreadId(),TId,FALSE);
}
}
}
返回结果;
}
int _tmain(int argc,_TCHAR*argv[]
{
std::wstring状态;
而(1)
{
HWND focus_handle=GetFocusGlobal();
if(焦点\句柄)
{
TCHAR文本[最大路径];
GetClassName(焦点句柄、文本、最大路径);
常量std::wstring cur_路径(文本);
if(当前路径!=状态)
{
std::t看看GetGuitThreadInfo(),为什么你决定伪造输入而不是使用自动化API?@DavidHeffernan:只是好奇-你想到了哪种自动化API?@MartynA UIAutomationDavid,我只需要使用WinApi,不需要三维派对解决方案。我在公司工作,所以这不是我的决定