IP002
IP002

Reputation: 547

How to simulate a keypress

I know about AutoHotKey but I want to make my own program for e.g. make it press F5 every 10 seconds. I searched the internet and Stack Overflow but did not find a solution

Is there a way to do it in C or not? I am using and targeting Windows 8.1

Upvotes: 3

Views: 1839

Answers (2)

Cal
Cal

Reputation: 48

If you need the key modular, check out my implementation (without event loop)

#include <windows.h>

const int key_a = 0x41;
const int key_b = 0x42;
const int key_c = 0x43;
const int key_d = 0x44;

write(int key) {

    INPUT inputs[2] = { 0 };

    inputs[0].type = INPUT_KEYBOARD;
    inputs[0].ki.wVk = key;

    inputs[1].type = INPUT_KEYBOARD;
    inputs[1].ki.dwFlags = KEYEVENTF_KEYUP;

    SendInput(2, inputs, sizeof(INPUT));
}

main() {
    // Some time to select another window here (e.g. Notepad)
    Sleep(3000);

    write(key_a);
    write(key_b);
    write(key_c);
    write(key_d);
}

Upvotes: 0

cdo256
cdo256

Reputation: 1003

You'd want to use the SendInput function. The following code sends a key-down, key-up pair of input events to Windows every 10 seconds.

#include <windows.h>

static const int delay_ms = 10000;

void sendF5(
    UINT uTimerID,
    UINT uMsg,
    DWORD_PTR dwUser,
    DWORD_PTR dw1,
    DWORD_PTR dw2) {

    INPUT input[2] = {0};
    input[0].type = input[1].type =
        INPUT_KEYBOARD;
    input[0].ki.wVk =
        input[1].ki.wVk = VK_F5;
    input[1].ki.dwFlags =
        KEYEVENTF_KEYUP;
    input[0].ki.dwExtraInfo =
        input[1].ki.dwExtraInfo =
        GetMessageExtraInfo();

    SendInput(2, input, sizeof(INPUT));
}

int WinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    PWSTR pCmdLine,
    int nCmdShow) {

    timeSetEvent(delay_ms, 1000,
        sendF5, 0, TIME_PERIODIC);
    return 0;
}

Upvotes: 3

Related Questions