qt 向窗口发送消息,键盘输入事件

#include <windows.h>
#include <QtDebug>
#include <locale>
#include <tchar.h>
#include <string>

    HWND hwnd = (HWND)0x000A069C;

    // https://docs.microsoft.com/zh-cn/windows/win32/winmsg/about-messages-and-message-queues
    // 这里使用W,发送的是unicode,而不是用的A
    QString str = "Ajanuw 中文";
    for(QChar c: str){
        // int v_latin = c.toLatin1(); // 不能转中文
        int v_latin = c.unicode(); // 对应的code码
        qDebug() << v_latin;
        SendMessageW(hwnd,WM_IME_CHAR,(WPARAM)v_latin,(LPARAM)v_latin);
    }

发送组合键

keybd_event

// ctrl+tap的组合键,然后抬起tab, ctrl
keybd_event(VK_CONTROL, 0, 0, 0);
keybd_event(VK_TAB, 0, 0, 0);

keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);

SendInput

        BringWindowToTop(hwnd);

        INPUT ip;
        ip.type = INPUT_KEYBOARD; // 输入事件的类型
        ip.ki.wScan = 0;
        ip.ki.time = 0;
        ip.ki.dwExtraInfo = 0;

        ip.ki.wVk = 0x41; // 按键 "A"
        ip.ki.dwFlags = 0;
        SendInput(1, &ip, sizeof(INPUT));

        // 抬起按键
        Sleep(30);
        ip.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(1, &ip, sizeof(INPUT));

SendInput 组合键,下面的程序先按下ctrl+tab的组合键,然后依次松开了tap和ctrl键后,在按下A键,再松开A键

        BringWindowToTop(hwnd);

        INPUT ip;
        ip.type = INPUT_KEYBOARD; // 输入事件的类型
        ip.ki.wScan = 0;
        ip.ki.time = 0;
        ip.ki.dwExtraInfo = 0;

        // 按下ctrl
        ip.ki.wVk = VK_CONTROL;
        SendInput(1, &ip, sizeof(INPUT));

        // 按下 tab
        ip.ki.wVk = VK_TAB;
        SendInput(1, &ip, sizeof(INPUT));

        // 抬起tab
        Sleep(30);
        ip.ki.wVk = VK_TAB;
        ip.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(INPUT_KEYBOARD, &ip, sizeof(INPUT));

        // 抬起ctrl
        Sleep(30);
        ip.ki.wVk = VK_CONTROL;
        ip.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(INPUT_KEYBOARD, &ip, sizeof(INPUT));

        Sleep(30);
        // 按下A
        ip.ki.wVk = 0x41;
        ip.ki.dwFlags = 0;
        SendInput(1, &ip, sizeof(INPUT));

        //  抬起A
        Sleep(30);
        ip.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(1, &ip, sizeof(INPUT));
posted @ 2020-05-07 10:41  Ajanuw  阅读(...)  评论(...编辑  收藏