How to use winforms application to emulate keyboard input

178 Views Asked by At

I have a simple winforms application doing keyboard emulation with:

private void timer1_Tick(object sender, EventArgs e)
{
    string keys = txtUID.Text + "{ENTER}";
    SendKeys.SendWait(keys);
}

This application sends keystrokes to the active window every second. I can see easily this app working opening notepad or any other program accepting inputs. Please note I cannot change this application because in the real word I have an application not written by me that probabily use SendKeys.SendWait, and I need to get those keystrokes in my application.

My goal was to get these keyboard inputs in another winforms application, when the main window is active, and I don't find any solutions yet.

First Attempt

I tried to get input in a standard way: I setted Form.KeyPreview = true and I have implemented Form_KeyDown event. Event never raised when Form is active when other application uses SendKeys.SendWait. Event is raised when I type some key on the keyboard.

Second Attempt

I tried to override ProcessCmdKey; same behaviour of the previous attempt: the function was not called when other application uses SendKeys.SendWait, while function is called when I type on the keyboard.

Third Attempt

I implement event TextBox_PreviewKeyDow in a textbox, I put the focus on this textbox but event is never raised when other application uses SendKeys.SendWait. As other attempts, event is raised if I type on the hardware keyboard.

Fourt Attempt

I wrote a global keyboard hook as described here Global keyboard capture in C# application. The strange behaviour is that the keyboard hook callback is called only when the main form is not active! When the form is active, the callback is not called.

So I don't find any way to get keyboard event sended by SendKeys in my winforms application.

EDIT

Someone suspects this a malicious application. In the real word the application using SendKeys is an application reading Badge UID and sending them as ASCII characters via keyboard emulation. Nothing malicious.

0

There are 0 best solutions below