Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating input: key pressed, hold and release

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");
}
like image 818
NewBieS Avatar asked Oct 30 '22 15:10

NewBieS


1 Answers

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().

like image 128
Peter Duniho Avatar answered Nov 10 '22 13:11

Peter Duniho