Alternative to SendKeys when running over Remote Desktop?

24,887

Solution 1

SendKeys is not a good fit mainly due to:

  • It can only send keys to active/focused application, which is never guaranteed to work because the the active application can change between the time the keys are actually sent.
  • RDP and many other libraries (e.g., DirectX) block them mainly for security reasons.

Better alternatives:

Sample code using SendMessage:

HWND hwndNotepad = FindWindow(_T("Notepad"), NULL);
HWND hwndEdit = FindWindowEx(hwndNotepad, NULL, _T("Edit"), NULL);
SendMessage(hwndEdit, WM_SETTEXT, NULL, (LPARAM)_T("hello"));

Solution 2

In my case I was successfully using WinAPI's SendInput with hardware scan codes. It seems like SendKeys maps chars to scan codes incorrectly.

Solution 3

You can workaround RDP issue by having desktop always logged in before use (or configured for auto-login @ every boot).

And even with the auto-login, if you ever need remote desktop access to run automation, or manage system, etc., the preferred method is using VNC for remote access rather than RDP. Reason is VNC is cross platform and you won't run into this RDP issue. VNC works like a relay of your actual desktop (RDP console session 0 or the "head" of the machine), the disadvantage being one remote session at a time only (or you all share the same desktop + keyboard + mouse). VNC will work for virtual machines too. Use VNC instead of RDP or local (RDP) access from the (VMWare/Hyper-V/Xen) virtual machine manager software.

The only thing to watch out for with VNC still is that the desktop not be configured to auto-lock on idle or screensaver, that may also stop send keys and GUI automation from running, so be sure to disable that. Screensaver & monitor power save is ok, just no auto-lock & password protect.

NOTE: I'm not sure, but believe since VNC relays the desktop "as is", it is the same as executing locally from the app/system's point of view, so it should in theory also be able to fool the system/app that doesn't allow SendKeys via RDP. I've had no issues using this VNC method for AutoIt + SendKeys, whether I was actively connected via VNC, or disconnected (sendkeys/automation still continues to work after disconnect because on the actual desktop, it's still logged in, just that VNC not active).

Share:
24,887
Cameron
Author by

Cameron

Updated on February 03, 2021

Comments

  • Cameron
    Cameron about 3 years

    I have an application which injects keystrokes into applications via SendKeys.

    Unfortunately, the application will not work when I am running it via Remote Desktop because of the well known issue that SendKeys doesn't work with Remote Desktop.

    Has anyone solved this issue before, or have any good suggestions on how to resolve it?