[方法记录]向Windows的特定窗口注入键盘事件

前言

在尝试开发一款可以远程控制电脑进行文字输入软件时候,需要找到合适方法在Windows端注入键盘事件。查询微软的相关文档之后,发现通过两个简单的函数就能实现基本的键盘事件注入功能。

事件注入

使用SendInput方法即可。参照官方给出的实例:

cpp 复制代码
//**********************************************************************
//
// Sends Win + D to toggle to the desktop
//
//**********************************************************************
void ShowDesktop()
{
    OutputString(L"Sending 'Win-D'\r\n");
    INPUT inputs[4] = {};
    ZeroMemory(inputs, sizeof(inputs));

    inputs[0].type = INPUT_KEYBOARD;
    inputs[0].ki.wVk = VK_LWIN;
   
    inputs[1].type = INPUT_KEYBOARD;
    inputs[1].ki.wVk = 'D';

    inputs[2].type = INPUT_KEYBOARD;
    inputs[2].ki.wVk = 'D';
    inputs[2].ki.dwFlags = KEYEVENTF_KEYUP;

    inputs[3].type = INPUT_KEYBOARD;
    inputs[3].ki.wVk = VK_LWIN;
    inputs[3].ki.dwFlags = KEYEVENTF_KEYUP;

    UINT uSent = SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT));
    if (uSent != ARRAYSIZE(inputs))
    {
        OutputString(L"SendInput failed: 0x%x\n", HRESULT_FROM_WIN32(GetLastError()));
    } 
}

写成如下函数进行测试:

cpp 复制代码
UINT sendInput(WORD virtualKeyCode) {
    cout<<"sendInput"<<virtualKeyCode<<endl;
    INPUT inputs[2] = {};
    ZeroMemory(inputs, sizeof(inputs));

    inputs[0].type = INPUT_KEYBOARD;
    inputs[0].ki.wVk = virtualKeyCode;

    inputs[1].type = INPUT_KEYBOARD;
    inputs[1].ki.wVk = virtualKeyCode;
    inputs[1].ki.dwFlags = KEYEVENTF_KEYUP;

    UINT uSent = SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT));
    if (uSent != ARRAYSIZE(inputs))
    {
        printf("SendInput failed: 0x%x\n", HRESULT_FROM_WIN32(GetLastError()));
    }

    return uSent;
}

int main()
{
    sendInput('W');
    sendInput('E');
    sendInput('B');
}

根据函数返回值,事件在这个时候已经注入成功了。

使用SetForegroundWindow 聚焦窗口

然而,事件被成功注入不代表被注入到我们想要的地方。sendInput方法只会将事件注入到已经聚焦的窗口,如果窗口没有聚焦的话是收不到注入的消息的。通过SetForegroundWindow方法,可以将特定的窗口聚焦。为了找到我们想聚焦的窗口,可以使用FindWindow方法。FindWindow需要两个参数,依次是类名、窗口名。 用法如下:

cpp 复制代码
HWND targetWindow = FindWindow("YodaoMainWndClass",NULL);
if (targetWindow != NULL)
{
    std::cout << "Window found!" << std::endl;
    SetForegroundWindow(targetWindow);
    
    
}

如何获取窗口的类名与方法名?

一般的窗口使用Visual Studio的工具Spy++即可。以网易有道词典为例:

如图可以看到,类名为YodaoMainWindClass,窗口名为网易有道词典。

相关推荐
路由侠内网穿透2 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
研华嵌入式3 天前
如何在高通跃龙QCS6490 Arm架构上使用Windows 11 IoT企业版?
arm开发·windows·嵌入式硬件
带娃的IT创业者3 天前
Windows 平台上基于 MCP 构建“文心一言+彩云天气”服务实战
人工智能·windows·文心一言·mcp
csdn_aspnet3 天前
Windows Node.js 安装及环境配置详细教程
windows·node.js
摇滚侠3 天前
java语言中,list<String>转成字符串,逗号分割;List<Integer>转字符串,逗号分割
java·windows·list
Source.Liu3 天前
【Pywinauto库】12.2 pywinauto.element_info 后端内部实施模块
windows·python·自动化
Source.Liu3 天前
【Pywinauto库】12.1 pywinauto.backend 后端内部实施模块
开发语言·windows·python·自动化
私人珍藏库3 天前
[Windows] FileOptimizer v17.1.0_一款文件批量压缩工具
windows·批量压缩
掘根3 天前
【CMake】List
windows·microsoft·list
TToolss3 天前
删除文件夹里的网盘图标
windows