如何编程并行键盘输入

时间:2018-05-24 13:22:35

标签: c++ visual-studio parallel-processing keyboard

如前所述,我想知道并行键盘输入是如何工作的。

到目前为止,这是我的代码:

cout << "Enter time for Key A: ";
cin >> timeA;
cout << "Enter time for Key B: ";
cin >> timeB;
while (1)
{

    Sleep(timeA);
    INPUT ip;
    ip.type = INPUT_KEYBOARD;
    ip.ki.time = 0;
    ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a unicode character
    ip.ki.wScan = 'A'; // Which keypress to simulate
    ip.ki.wVk = 0;
    ip.ki.dwExtraInfo = 0;
    SendInput(1, &ip, sizeof(INPUT));


    Sleep(timeB);
    ip.type = INPUT_KEYBOARD;
    ip.ki.time = 0;
    ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a unicode character
    ip.ki.wScan = 'B'; // Which keypress to simulate
    ip.ki.wVk = 0;
    ip.ki.dwExtraInfo = 0;
    SendInput(1, &ip, sizeof(INPUT));

}

它有效,但我想达到,例如每隔500毫秒按一次字母A,每隔1秒按字母B.我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是一个计时器类。您可以创建一个对象并将其命名为:

timer timer_1(time_in_milliseconds, true_if_async, &function_name, argument_1, arg_2, ...);

通过这种方式,您可以在经过一段时间后运行您的函数,您也可以与异步一起运行多个函数,或者只使用同步和排队。你的选择。

线程是解决问题的最佳方案。

class timer
{
public:
    template <class Callable, class... Arguments>
    timer(int after, const bool async, Callable&& f, Arguments&&... args)
    {
        std::function<typename std::result_of<Callable(Arguments...)>::type()> task(bind(forward<Callable>(f), forward<Arguments>(args)...));

        if (async)
        {
            thread([after, task]()
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }
};

以下是一个小例子用法:

void say(const string& word)
{
    cout << "Hello, " << word << "!\n";
}

int main(int argc, char* argv[])
{
    while (true)
    {
        timer timer1(500, false, &say, "pyreN - A");
        timer timer2(1000, false, &say, "pyreN - B");
    }
}