Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate shift/ctrl/alt key state?

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?

like image 967
Joey Morani Avatar asked Mar 28 '26 01:03

Joey Morani


1 Answers

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.

like image 111
Joey Morani Avatar answered Mar 29 '26 14:03

Joey Morani