Simulating input: key pressed, hold and release

核能气质少年 提交于 2019-12-10 17:13:40

问题


I am trying to simulate a user pressing a key, holding it for some specific time interval, and then releasing it. I have tried to implement this using SendKeys.Send(), but I cannot figure out how to control the duration of how long the key is pressed.

I don't want to just keep sending the same key over and over; I want a single key-down and a single key-up event.

For example, I have code like this:

//when i press this button, will sent keyboard key "A", i want to hold it until i release

private void start_btn_Click(object sender, EventArgs e)
{
    testSent();
}

//how should i hold it for a timer???
private void testSent()
{
    SendKeys.Send("A");
}

回答1:


If you want the receiving program to see just the key-down event followed by a key-up event some period of time later, you will need a different API than SendKeys. That one only sends entire key-strokes, i.e. with key-down and key-up. You may be able to do what you want by p/invoking the native Windows SendInput() function.

I haven't used it, but you may find that the Windows Input Simulator is a useful managed code wrapper for the API you need.

Assuming you figure out how to end the appropriate key events, doing it on a timed basis is trivial:

private static readonly TimeSpan _keyDownInterval = ...; // initialize as desired

private async void start_btn_Click(object sender, EventArgs e)
{
    SendKeyDown();
    await Task.Delay(_keyDownInterval);
    SendKeyUp();
}

// These two are implemented using whatever mechanism you prefer,
// e.g. p/invoke `SendInput()`, using the Windows Input Simulator library, or whatever.
private void SendKeyDown() { ... }
private void SendKeyUp() { ... }


Here are some related questions on Stack Overflow:
Send keys to WPF Browser control
C# p/Invoke How to simulate a keyPRESS event using SendInput for DirectX games

Neither specifically address your question, but they both include some discussion on the usage of SendInput().



来源:https://stackoverflow.com/questions/33793410/simulating-input-key-pressed-hold-and-release

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!