How to prevent a keyboard from writing to other applications

493 Views Asked by At

I am using a simple Hookup to record the keys from a BarcodeScanner which is a connect via Usb as a Keyboard. I am using this example that I found online:

using System.Windows.Forms;

namespace RawInput
{
public partial class Form1 : Form
{
    InputDevice id;
    int NumberOfKeyboards;

    public Form1()
    {
        InitializeComponent();

        // Create a new InputDevice object, get the number of
        // keyboards, and register the method which will handle the 
        // InputDevice KeyPressed event
        id = new InputDevice( Handle );
        NumberOfKeyboards = id.EnumerateDevices();
        id.KeyPressed += new InputDevice.DeviceEventHandler( m_KeyPressed );
    }

    // The WndProc is overridden to allow InputDevice to intercept
    // messages to the window and thus catch WM_INPUT messages
    protected override void WndProc( ref Message message )
    {
       if( id != null )
       {
           id.ProcessMessage( message );
       }
       base.WndProc( ref message );
    }

    private void m_KeyPressed( object sender, InputDevice.KeyControlEventArgs e )
    {
        //Replace() is just a cosmetic fix to stop ampersands turning into underlines
        lbHandle.Text = e.Keyboard.deviceHandle.ToString();
        lbType.Text = e.Keyboard.deviceType;
        lbName.Text = e.Keyboard.deviceName.Replace("&", "&&");
        lbDescription.Text = e.Keyboard.Name;         
        lbKey.Text = e.Keyboard.key.ToString();
        lbNumKeyboards.Text = NumberOfKeyboards.ToString();
        lbVKey.Text = e.Keyboard.vKey;
    }

    private void btnClose_Click(object sender, System.EventArgs e)
    {
        this.Close();
    }

}
}

The problem is, the barcode scanner writes to whichever application is in focus. Is it possible to redirect all data from this device to my application whilst it is running?

1

There are 1 best solutions below

0
On

If your device has installed as a keyboard (rather than a non-keyboard HMI device) this isn't particularly easy as keyboards and mice are restricted by the OS.

This answer states how you might be able to work around this restriction.

Good luck!