Mike Mazowski
Mike Mazowski

Reputation: 45

How to write a driver for external keyboard in C#

I have a code that receives a USART byte that represents the button clicked on keyboard I made and displays it in console window. I would like to know how to make the pressed button cause an actual button press so that it could be used in other applications and probably run in background. Running on windows.

using System;
using System.IO.Ports;

namespace ConsoleApplication1
{


class Program
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM4");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.Write(indata);
    }
}
}

Upvotes: 0

Views: 1268

Answers (1)

CherryDT
CherryDT

Reputation: 29052

You'll need the keybd_event function.

[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

public const int KEYEVENTF_KEYUP = 2; // Flag that we simulate a key being released

public static void simulateKeyPress(byte bVk) {
    // Simulate keydown
    keybd_event(bVk, 0, 0, 0);
    // Simulate keyup
    keybd_event(bVk, 0, KEYEVENTF_KEYUP, 0);
}

You can use this function to simulate and key being pressed or released.

The list of available key codes can be found here.

The simulateKeyPress helper function I wrote will simulate both keydown and keyup. For example, we can simulate the enter key being pressed like this:

simulateKeyPress(0x0D); // 0x0D is constant VK_RETURN from the list

...but you might need different combinations as well, for example if you want to send Ctrl+C you would need to send Ctrl-down, C-down, C-up, Ctrl-up.

Upvotes: 2

Related Questions