3
votes

Does anyone know how I can simulate the shift/ctrl/alt key states?

Basically I'm creating a remote-desktop app with the clientside using a HTML5 canvas and the serverside running a C# app. The serverside app captures the screen, sends it and simulates any key presses which were sent by the client.

I have everything working except the key presses. The clientside sends:

 kd; KEYCODE HERE 

when a key is pressed and

ku; KEYCODE HERE 

when it's released (keyup). I'm using this code:

[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;

// - - - - -

// Keyboard events
if (receivedData[0] == "kd")
{
    // Shift key pressed
    if (receivedData[1] == "16")
    {
        keybd_event((byte)Convert.ToInt32(Keys.LShiftKey), 0, KEYEVENTF_EXTENDEDKEY, 0);
        return;
    }

    keybd_event((byte)Convert.ToInt32(receivedData[1]), 0, KEYEVENTF_EXTENDEDKEY, 0);
}
if (receivedData[0] == "ku")
{
    // Shift key released
    if (receivedData[1] == "16")
    {
        keybd_event((byte)Convert.ToInt32(Keys.LShiftKey), 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
        return;
    }

    keybd_event((byte)Convert.ToInt32(receivedData[1]), 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}

Normal keys work fine, but any key that has a state won't work correctly. The javascript keycode that's received for left-shift is 16. Any ideas how I would get it working?

1
Although the above code works for shift presses when writing text... Just not for programs like games, etc. :SJoey Morani
Hmm, holding the leftshift on server then pressing the leftshift key on the client (then releasing the shift key on the server) makes it work. But when you press the rightshift key on the server it stops working again. Anyone know what's going on? The states are getting messed up by the looks of it.Joey Morani

1 Answers

1
votes

I ended up using the Windows Input Simulator library. Works well for simulating key-downs and key-ups, including the shift, ctrl and alt keys.