Search code examples
c#.netsendkeys

C# Wait for SendKeys to finish sending before executing next line of code?


I think the title explains what I am asking.

I need the SendKeys to finish sending the keys before the DoMouseClick method or my entire program is useless.

// Simulate the keyboard typing the value of 'i'
SendKeys.SendWait(i.ToString());

// Simulate mouse click so the Accept button in-game is clicked
DoMouseClick();

I tried using Thread.Sleep but I was hoping you guys had some better suggestions on how to fix my problem.


Solution

  • Use Input Simulator. It's much better than SendKeys, and handles the edge cases internally.

    Install-Package InputSimulator

    var simulator = new InputSimulator();
    
    //simulate what you need
    simulator.Keyboard.KeyPress(VirtualKeyCode.VK_I);
    simulator.Keyboard.TextEntry(i.ToString());
    
    simulator.Mouse.LeftButtonDoubleClick();