在游戏中使用keybd_event的问题

原文链接:http://blog.163.com/lion_jaka/blog/static/103192597201311732732255/


今天发现在游戏中,keybd_event不能使用,结果发现游戏是使用directinput实现读取键盘的,关键还是扫描码的问题,我抄了一段老外的代码,经测试有效(在金庸中测试重复输入空格):


#include <iostream>
#include <windows.h>
// for key pushing
BYTE scan_code(DWORD pKey)
{
    const DWORD result = MapVirtualKey(pKey, MAPVK_VK_TO_VSC);
    return static_cast<BYTE>(result);
}
void press_key(DWORD pKey)
{
    keybd_event(static_cast<BYTE>(pKey), scan_code(pKey), 0, 0);
}
void release_key(DWORD pKey)
{
    keybd_event(static_cast<BYTE>(pKey), scan_code(pKey), KEYEVENTF_KEYUP, 0);
}
// for testing
#define PRESS(x) press_key(x); std::cout << "Press: " #x << std::endl
#define RELEASE(x) release_key(x); std::cout << "Release: " #x << std::endl
// test
int main(void)
{
    for (;;)
    {
        PRESS(VK_LEFT);
        Sleep(10); // hold it for 1/100'th of a second
        RELEASE(VK_LEFT);
        Sleep(1000); // wait for a second
        PRESS(VK_RIGHT);
        Sleep(10); // hold it for 1/100'th of a second
        RELEASE(VK_RIGHT);
        Sleep(1000); // wait for a second
    }
}


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页