Capturing keystrokes with GetAsyncKeyState

November 5, 2003 on 3:09 pm | In General |

An easy way to capture keystrokes in an application even if it is not the active one is by using the API function, GetAsyncKeyState, of the User32 DLL.

The trick is to set up a timer that regularly checks for the state of certain keys with GetAsyncKeyState

Here is an example:

using System;
using System.Windows.Forms;

public class Test {

	protected Timer timer = null;

	public Test {
		timer = new Timer();
		timer.Interval = 100; // check the keystate every 100ms
		timer.Click += new EventHandler(OnTimerTick);
		timer.Start();
	}

	private void OnTimerTick(Object sender, EventArgs args) {
		bool hotKeyPressed = true;
		// check the status of the left Windows key and the
		// right Control key
		Keys[] keys = {Keys.LWin, Keys.RControlKey};
		for (int i = 0; i < keys.Length; i++) {
			hotKeyPressed &= (GetAsyncKeyState( (int) keys[i]) & 0x8000) == 0x8000;
		}
		if (hotKeyPressed) {
			// do something
		}
	}

	// we expose the API function in the following lines
	[DllImport("User32.Dll")]
	private static extern int GetAsyncKeyState(int keyCode);

}

This technique is used in “TiBar”:http://www.jeysoft.com to detect whether the application launcher is being called.

Related Posts:

4 Comments »

RSS feed for comments on this post.

  1. What, if I hit the keys faster than timers interval? Even if the interval is 1, it seems to be possible to hit faster. So the function misses some keys :-(

    Does anybody know, how to solve this problem?

    Greets :-)

    Comment by Markus M�ller — 12 January 2004 #

  2. Sometimes a higher interval is preferable so as not to overload the system with unnecessary checks. 100 ms seems to work for me with insignificant misses.

    Comment by Eddy Young — 12 January 2004 #

  3. Ok, the timer is fast enough and could be about 100ms. But my event, that starts at some special keys, runs round about one second (!)
    So every key, I hit in the meantime, is not realized. It would be nice to have an input-queue. Is this supported by windows? Or do I have to build the queue by myself?

    Markus

    Comment by Markus M�ller — 14 January 2004 #

  4. Building a queue should not be a hard job. Just use the FIFO principle to add and remove keystrokes from your queue.

    Comment by Eddy Young — 14 January 2004 #

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>





Powered by blog.mu with Pool theme design by Borja Fernandez.