Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#

Using Raw Input from C# to handle multiple keyboards

,
Rate me:
Please Sign up or sign in to vote.
4.94/5 (138 votes)
9 Mar 2015LGPL318 min read 2.4M   69.1K   250  
Windows XP supports multiple keyboards, but by default, the .Net Framework will treat them all as one. This article explains how to use the Windows API Raw Input methods to support multiple keyboards from a C# application.
using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using Application=System.Windows.Application;

namespace WindowsApplication1
{
    public partial class Window1
    {
       RawStuff.InputDevice id;
       int NumberOfKeyboards;
       Message message = new Message();

        public Window1()
        {
           Activate();
        }

        private void _KeyPressed(object sender, RawStuff.InputDevice.KeyControlEventArgs e)
        {
            string[] tokens = e.Keyboard.Name.Split(';');
            string token = tokens[1];

            lbHandle.Content = e.Keyboard.deviceHandle.ToString();
            lbType.Content   = e.Keyboard.deviceType;
            lbName.Content   = e.Keyboard.deviceName;
            lbKey.Content    = e.Keyboard.key.ToString();
            lbVKey.Content   = e.Keyboard.vKey;
            lbDescription.Content  = token; 
            lbNumKeyboards.Content = NumberOfKeyboards.ToString();
        }

        public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (id != null)
            {
                // I could have done one of two things here.
                // 1. Use a Message as it was used before.
                // 2. Changes the ProcessMessage method to handle all of these parameters(more work).
                //    I opted for the easy way.

                //Note: Depending on your application you may or may not want to set the handled param.

                message.HWnd   = hwnd;
                message.Msg    = msg;
                message.LParam = lParam;
                message.WParam = wParam;
                
                id.ProcessMessage(message);
            }
            return IntPtr.Zero;
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            // I am new to WPF and I don't know where else to call this function.
            // It has to be called after the window is created or the handle won't
            // exist yet and the function will throw an exception.
            StartWndProcHandler();
            
            base.OnSourceInitialized(e);
        }
            
        void StartWndProcHandler()
        {
            IntPtr hwnd = IntPtr.Zero;
            Window myWin = Application.Current.MainWindow;

            try
            {
                hwnd = new WindowInteropHelper(myWin).Handle;
            }
            catch (Exception ex)
            {
               Console.WriteLine(ex);
            }

            //Get the Hwnd source   
            HwndSource source = HwndSource.FromHwnd(hwnd);
            //Win32 queue sink
            source.AddHook(new HwndSourceHook(WndProc));

            id = new RawStuff.InputDevice(source.Handle);
            NumberOfKeyboards = id.EnumerateDevices();
            id.KeyPressed += new RawStuff.InputDevice.DeviceEventHandler(_KeyPressed);
        }

        void CloseMe(object sender, RoutedEventArgs e)
        {
            Close();
        }
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Software Developer
United Kingdom United Kingdom
Emma's first steps in programming took place at primary school over thirty years ago, thanks to a TI-99/4A and the LOGO language. Following a Master's degree in English Studies (obtained, strangely enough, with a paper on the birth of the microcomputer), Emma started her career in IT.

Over the last ten years, she has worked as a localiser, technical writer, editor, web designer, systems administrator, team leader and support engineer, before finally making the move into software development a few years ago. She is now thrilled on a daily basis that she is getting paid for writing code after doing it for free half her life!

Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions