How to simulate keybard input to a remote desktop session?

Ian Boyd picture Ian Boyd · Dec 5, 2008 · Viewed 20.2k times · Source

i'm trying to send fake keyboard input to an application that's running in a Remote Desktop session. i'm using:

Byte key = Ord("A");

keybd_event(key, 0, 0, 0); // key goes down
keybd_event(key, 0, KEYEVENTF_KEYUP, 0); // key goes up

Now this code does send the character "a" to any local window, but it will not send to the remote desktop window.

What that means is i use Remote Desktop to connect to a server, and i then open Notepad on that server. If i manually punch keys on the keyboard: they appear in Notepad's editor window. But keybd_event's fake keyboard input not causing "a"'s to appear in Notepad.

How can i programtically send fake keyboard input to an application running inside a remote desktop connection, from an application running on the local machine?


Nitpickers Corner

In this particular case i want to do this becase i'm trying to defeat an idle-timeout. But i could just as well be trying to

  • perform UI automation tests
  • UI stress tests
  • UI fault finding tests
  • UI unit tests
  • UI data input tests
  • UI paint tests
  • or UI resiliance tests.

In other words, my reasons for wanting it aren't important

Note: The timeout may be from remote desktop inactivity, or perhaps not. i don't know, and it doesn't affect my question.

Answer

Ian Boyd picture Ian Boyd · Dec 5, 2008

Answer

Although Microsft says you don't need to, and you should not, send the OEM code, you need to send the OEM scan codes. In this example i need to send the OEM scan codes for

  • key A goes down
  • key A goes up

There is a picture of a chart on CodeProject that lists the make and break scan codes for various keys:

alt text

In my case the original calls to keybd_event need to be changed to:

Byte key = Ord("A");

keybd_event(key, 0x1E, 0, 0); // key goes down
keybd_event(key, 0x9E, KEYEVENTF_KEYUP, 0); // key goes up

i tested this, and it works. So all is well.