§ May 20, 2005

Obtaining Key State info in .NET ( A C# GetKeyState implementation)

Sometimes it's usefull to know the current state of a given key. The platform SDK provides this functionality however .NET (at least v1.1) doesn't provide access to it.

GetKeyState allows a developer to get information such as whether or not the given key is currently being pressed down, or if the key has a toggled state, whether or not it is currently being toggled.

The following utility is a .NET complement to the GetKeyState platform SDK function. I've created a struct which has 3 properties: Key, IsPressed, and IsToggled. These properties are set when GetKeyState is invoked. The return value of this GetKeyState is this struct, to give easy access to the data provided. As MSDN documentation states, the return value of this function is a number who's high bit denotes whether or not the key is being pressed, and the low bit denotes whether or not the key is currently toggled. The "Key" property is simply being passed through. Another thing to take notice of, is that the platform sdk uses the virtual key VK_<XX> definition for keys. These have been mapped into .NET's System.Windows.Forms.Keys enumeration, so that the value of the given Keys.<key> has the same value as the VK_<key> winuser.h definition.

Anyway, here's the sample:

/******************************************************/
/*          NULLFX FREE SOFTWARE LICENSE              */
/******************************************************/
/*  GetKeyState Utility                               */
/*  by: Steve Whitley                                 */
/*  © 2005 NullFX Software                            */
/*                                                    */
/* NULLFX SOFTWARE DISCLAIMS ALL WARRANTIES,          */
/* RESPONSIBILITIES, AND LIABILITIES ASSOCIATED WITH  */
/* USE OF THIS CODE IN ANY WAY, SHAPE, OR FORM        */
/* REGARDLESS HOW IMPLICIT, EXPLICIT, OR OBSCURE IT   */
/* IS. IF THERE IS ANYTHING QUESTIONABLE WITH REGARDS */
/* TO THIS SOFTWARE BREAKING AND YOU GAIN A LOSS OF   */
/* ANY NATURE, WE ARE NOT THE RESPONSIBLE PARTY. USE  */
/* OF THIS SOFTWARE CREATES ACCEPTANCE OF THESE TERMS */
/*                                                    */
/* USE OF THIS CODE MUST RETAIN ALL COPYRIGHT NOTICES */
/* AND LICENSES (MEANING THIS TEXT).                  */
/*                                                    */
/******************************************************/

namespace NullFX.Win32 {
    using System;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    public class KeyboardInfo {
        private KeyboardInfo() {}
        [DllImport("user32")]
        private static extern short GetKeyState(int vKey);
        public static KeyStateInfo GetKeyState(Keys key) {
            short keyState = GetKeyState((int)key);
            byte[] bits = BitConverter.GetBytes(keyState);
            bool toggled = bits[0] > 0, pressed = bits[1] > 0;
            return new KeyStateInfo(key, pressed, toggled);
        }
    }


    public struct KeyStateInfo {
        Keys _key;
        bool _isPressed,
            _isToggled;
        public KeyStateInfo(Keys key, 
                        bool ispressed, 
                        bool istoggled) {
            _key = key;
            _isPressed = ispressed;
            _isToggled = istoggled;
        }
        public static KeyStateInfo Default {
            get { 
                return new KeyStateInfo(Keys.None, 
                                            false, 
                                            false);
            }
        }
        public Keys Key {
            get{return _key;}
        }
        public bool IsPressed {
            get{return _isPressed;}
        }
        public bool IsToggled {
            get{return _isToggled;}
        }
    }
}
usage:
KeyStateInfo capsLock = KeyboardInfo.GetKeyState(Keys.CapsLock);
if(capsLock.IsToggled) MessageBox.Show("Caps Lock is On");

Posted 20 years, 5 months ago on May 20, 2005

 Comments can be posted in the forums.

© 2003 - 2024 NullFX
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License