Get key state from a console application

In Scott Hanselman’s recent Hanselminutes podcast with Chris Sells, he bemoaned the fact that in .NET you can’t just query the keyboard state to say “is this key pressed right now?” Chris answered that you can do it, but that he’d have to look it up to get the exact reference. I got curious and looked it up myself. It turns out you can get the currently pressed mouse buttons (as a static property on the System.Windows.Forms.Form class), but you can’t retrieve the current keyboard state. Fortunately for us P/Invoke comes to the rescue. (Unless you’re trying to run in Mono.) Below is a simple console application that checks the state of a particular key (or keys) in a loop. There is a Win32 API call to get the entire keyboard state, but for the purposes of tracking one or two keys, it’s overkill.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Lerch.KeyPressTest
{
    public class KeyPressTest
    {
        [DllImport("user32.dll")]
        public static extern ushort GetKeyState(short nVirtKey);

        public const ushort keyDownBit = 0x80;

        public static void Main(string[] args)
        {
            long counter = 0;
            while (true)
            {
                if (Form.MouseButtons == MouseButtons.Right)
                {
                    Console.WriteLine("Right mouse button detected");
                    break;
                }
                else if (IsKeyPressed(Keys.Escape))
                {
                    Console.WriteLine("Escape key detected");
                    break;
                }

                if (IsKeyPressed(Keys.Up))
                {
                    Console.WriteLine("UP {0}", counter++);
                }
                else if (IsKeyPressed(Keys.Down))
                {
                    Console.WriteLine("DOWN {0}", counter--);
                }
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }

        public static bool IsKeyPressed(Keys key)
        {
            return ((GetKeyState((short)key) & keyDownBit) == keyDownBit);
        }
    }
}

This entry was posted on Tuesday, October 10th, 2006 at 2:34 am and is filed under programming. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.