Click here to Skip to main content
15,891,657 members
Articles / Programming Languages / C#

A Simple C# Global Low Level Keyboard Hook

Rate me:
Please Sign up or sign in to vote.
4.90/5 (98 votes)
30 May 2007CPOL2 min read 979.9K   68.2K   171  
A simple description and sample of creating a global low level keyboard hook in C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Utilities;

namespace key_preview {
	public partial class Form1 : Form {
		globalKeyboardHook gkh = new globalKeyboardHook();

		public Form1() {
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e) {
			gkh.HookedKeys.Add(Keys.A);
			gkh.HookedKeys.Add(Keys.B);
			gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
			gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
		}

		void gkh_KeyUp(object sender, KeyEventArgs e) {
			lstLog.Items.Add("Up\t" + e.KeyCode.ToString());
			e.Handled = true;
		}

		void gkh_KeyDown(object sender, KeyEventArgs e) {
			lstLog.Items.Add("Down\t" + e.KeyCode.ToString());
			e.Handled = true;
		}
	}
}

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 Code Project Open License (CPOL)


Written By
Software Developer
United States United States
I currently work as a Software Engineer for a company in North Carolina, mainly working with C#.

Comments and Discussions