如何在 C++ 中模拟按住键盘按钮 [英] How to simulate holding down a keyboard button in C++

查看:88
本文介绍了如何在 C++ 中模拟按住键盘按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个模拟按住键盘按钮的程序.

I am trying to make a program that would simulate holding down a keyboard button.

这个程序应该在需要按住W、A、S、D等按钮的游戏中运行.我在 Grand Theft Auto V 和 Garry's Mod 中测试了该程序,但在其中任何一个中都不起作用.

This program is supposed to work in games, where holding down buttons such as W,A,S,D is required. I tested the program both in Grand Theft Auto V and Garry's Mod, but it didn't work in either of them.

我尝试使用 SendInputkeybd_event 函数来模拟输入,但没有运气.

I tried using SendInput and keybd_event functions for emulating the input with no luck.

#include <windows.h>
#define VK_W 0x57

using namespace std;

int main(){
    while(1){
        keybd_event(VK_W, 0, 0, 0);
        Sleep(3000);  //should hold W for 3 seconds
        keybd_event(VK_W, 0, KEYEVENTF_KEYUP, 0);
        Sleep(1000);
    }
    return 0;
}

我用Razer的键盘软件创建了宏,效果很好,所以一定有办法模拟按键输入.

I've created macros using Razer's keyboard software, which work perfectly, so there must be a way to simulate the key hold input.

我还尝试创建一个 AutoHotkey 脚本,它在 Garry's Mod 中有效,但在 Grand Theft Auto V 中无效:

I also tried creating an AutoHotkey script, which does work in Garry's Mod, but not in Grand Theft Auto V:

w::
SendInput {w down}
Sleep 3000
SendInput {w up}

当按下 W 时,这个脚本会保持 W 3 秒.

This script holds W for 3 seconds when W is pressed.

我尝试在网上搜索,但没有找到任何可行的实现.

I tried searching the web, but didn't find any working implementation.

我搜索了更多,发现了这个:https://stackoverflow.com/a/3647975/1587051

事实证明我使用的是 Unicode 而不是键盘扫描代码与 KEYEVENTF_SCANCODE 标志相结合.DirectInput 游戏现在可以正确接收击键.

It turns out I was using Unicode instead of keyboard scan codes combined with KEYEVENTF_SCANCODE flag. DirectInput games are now receiving the keystrokes correctly.

推荐答案

仅供参考,因为已经在评论中回答了,您必须使用 SendInput 而不是 SendMessage,在填充 SendInput 函数所需的 INPUT 结构时,请确保将 FlagsKEYEVENTF_SCANCODE 结合起来发送硬件信号而不是虚拟信号.这些将由 DirectInput 处理.来源:在 DirectInput 应用程序中使用 SendInput API 模拟键盘

For reference sake, as it has already been answered in the comments, you have to use SendInput rather than SendMessage, when filling the INPUT structure required for the SendInput function make sure you combine your Flags with KEYEVENTF_SCANCODE to send hardware signals instead of virtual ones. These will be handled by DirectInput. Source : Simulating Keyboard with SendInput API in DirectInput applications

这篇关于如何在 C++ 中模拟按住键盘按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆