You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C++模拟键盘按键输入,实现pyautogui、pynput的自动打字功能?

实现方案

Windows下模拟键盘输入可以直接使用系统提供的keybd_eventAPI,实现难度较低,修改后的完整可运行代码如下:

#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

string message = "Lol";
// 转成毫秒避免浮点数计算误差
int send_delay = 200;

void click_to_location()
{
    // 5秒准备时间,可在此期间切换到聊天窗口界面
    Sleep(5000);
    SetCursorPos(525, 665);
    Sleep(10);
    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
    Sleep(10);
}

// 模拟单个按键的按下、释放流程
void press_key(WORD key_code, bool need_shift = false)
{
    if (need_shift) {
        // 按下shift键
        keybd_event(VK_SHIFT, 0, 0, 0);
    }
    // 按下目标键
    keybd_event(key_code, 0, 0, 0);
    Sleep(10);
    // 释放目标键
    keybd_event(key_code, 0, KEYEVENTF_KEYUP, 0);
    if (need_shift) {
        // 释放shift键
        keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);
    }
    Sleep(10);
}

// 逐字符输入指定字符串
void type_string(const string& str)
{
    for (char c : str) {
        WORD key_code = 0;
        bool need_shift = false;
        if (c >= 'a' && c <= 'z') {
            key_code = c - 'a' + 0x41;
        } else if (c >= 'A' && c <= 'Z') {
            key_code = c - 'A' + 0x41;
            need_shift = true;
        } else if (c >= '0' && c <= '9') {
            key_code = c - '0' + 0x30;
        } else if (c == ' ') {
            key_code = VK_SPACE;
        }
        // 可自行扩展其他符号的处理逻辑
        if (key_code != 0) {
            press_key(key_code, need_shift);
        }
    }
    // 输入完成后按回车发送消息
    press_key(VK_RETURN);
}

int main()
{
    click_to_location();
    while (true)
    {
        // 按下Q键直接退出程序
        if (GetAsyncKeyState(0x51) & 0x8000)
        {
            exit(0);
        }
        type_string(message);
        // 两次发送的间隔时间
        Sleep(send_delay);
    }
    return 0;
}

关键逻辑说明

  • keybd_event是Windows系统原生提供的键盘模拟API,第三个参数传0表示按键按下,传KEYEVENTF_KEYUP表示按键释放,成对调用即可完成一次完整的按键操作
  • 字母键的虚拟键码0x41对应A、0x42对应B,以此类推,需要支持更多符号可以自行补充字符判断逻辑
  • 原代码的GetAsyncKeyState判断增加了& 0x8000逻辑,仅判断按键当前是否处于按下状态,避免误触发退出

注意事项

  • 运行前需要确认SetCursorPos的坐标是你聊天窗口输入框的位置,坐标不对可以自行修改数值
  • 该逻辑仅支持Windows平台,依赖Win32 API
  • 仅用于好友之间娱乐使用,请勿恶意刷屏干扰他人

内容的提问来源于stack exchange,提问作者NoobBit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:45:00