|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis article discusses a class that I wrote that wraps a global low level keyboard hook. The sample hooks the BackgroundI was trying to find a way for an application that I am writing to restore itself when a combination of keys was pressed. This was born from searching around for the answer. Using the CodeFirst download the source, and add globalKeyboardHook.cs to your project. Then add... using Utilities;
... to the top of the file you are going to use it in. Next add an instance of globalKeyboardHook gkh = new globalKeyboardHook() ;
When a 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 ;
}
Here I have chosen to watch for the You can add hooks for as many keys as you would like, just add them like above. Don't get frustrated if you add a hook for a key and it doesn't work, many of them, like If you would like to hook or unhook the keyboard hook at any point, just call your //unhook
gkh.unhook()
//set the hook again
gkh.hook()
Points of InterestThe bulk of the work in this code is done in the [DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx
(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
The parameters were worked out to be: IntPtr hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);
The first parameter History
|
||||||||||||||||||||||