为什么SendInput()不起作用? [英] Why isn't SendInput() working?

查看:631
本文介绍了为什么SendInput()不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用SendInput()函数自动按下某些键.

I want to use the SendInput() function to automate pressing some keys.

我的代码:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <Windows.h>

using std::cin;
using std::cout;
using std::string;

void presskeys(string s){
    INPUT ip;
    ip.ki.wScan = 0;
    ip.ki.time = 0;
    ip.ki.dwExtraInfo = 0;
    HKL kbl = GetKeyboardLayout(0);
    for (unsigned int i = 0; i < s.length(); ++i) {
        ip.type = INPUT_KEYBOARD;
        char c = s[i];
        int vk = VkKeyScanEx((WCHAR)c, kbl);
        ip.ki.wVk = vk;
        SendInput(1, &ip, sizeof(ip));
        ip.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(1, &ip, sizeof(ip));
    }
}
int main()
{
    cout << "Enter a string!\n";
    string str;
    cin >> str;
    Sleep(5000);
    presskeys(str);
    cout << "Done!\n";
    return 0;
}

我启动程序并输入一个字符串,仅此而已.哪里出问题了?

I boot up the program and enter a string, only for nothing to happen. Where did it go wrong?

推荐答案

您正在使用ANSI字符串,因此请使用VkKeyScanExA,或切换到std::wstring.但是,请勿将ANSI与UNICODE混合使用,也不要使用强制转换来隐藏编译器警告.

You are working with ANSI string so use VkKeyScanExA, or switch to std::wstring. But don't mix ANSI with UNICODE, and don't use casting to hide the compiler warnings.

您必须将ip.ki.dwFlags重置为零以指示按键按下.然后将其设置为KEYEVENTF_KEYUP.

You have to reset ip.ki.dwFlags to zero to indicate key down. Then set it to KEYEVENTF_KEYUP.

还必须检查键锁和换档的键状态.以这种方式使用SendInput是没有意义的,第一个参数在那里允许一次发送多个输入.您最好使用keybd_event

You also have to check the key state for caplock and shift, etc. Using SendInput in that way is pointless, the first parameter is there to allow sending multiple inputs at once. You might as well use keybd_event

void presskeys(string s) 
{
    INPUT ip;
    ip.type = INPUT_KEYBOARD;
    ip.ki.wScan = 0;
    ip.ki.time = 0;
    ip.ki.dwExtraInfo = 0;
    HKL kbl = GetKeyboardLayout(0);
    for (unsigned int i = 0; i < s.length(); ++i) 
    {
        char c = s[i];
        ip.ki.wVk = VkKeyScanExA(c, kbl); //<== don't mix ANSI with UNICODE
        ip.ki.dwFlags = 0; //<= Add this to indicate key-down
        SendInput(1, &ip, sizeof(ip));
        ip.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(1, &ip, sizeof(ip));
    }
}

这篇关于为什么SendInput()不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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