
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Using the Windows Keyboard Hook
|
533
Discussion
The hooks provided by the Windows operating system allow for very powerful code
to be written with a minimum of work. The hook used in this recipe is the
WH_
KEYBOARD
hook, which watches messages that are generated by the keyboard.
// Handle Previous Track keyboard button here.
textBox1.Text += "Media Previous Track key caught" +
Environment.NewLine;
break;
case VK_MEDIA_STOP:
// Handle Stop keyboard button here.
textBox1.Text += "Media Stop key caught" +
Environment.NewLine;
break;
case VK_MEDIA_PLAY_PAUSE:
// Handle Play keyboard button here.
textBox1.Text += "Media Play/Pause key caught" +
Environment.NewLine;
break;
}
}
return (CallNextHookEx(hookHandle, code, wparam, lparam));
}
// Click event handlers for button1 and button2.
private void button1_Click(object sender, System.EventArgs e)
{
// Set the keyboard hook.
if (hookHandle == 0)
{
cb = new HookProc(Proc);
hookHandle = SetWindowsHookEx(WH_KEYBOARD, cb, 0,
AppDomain.GetCurrentThreadId( ));
}
else
{
textBox1.Text += "Hook already set" + Environment.NewLine;
}
textBox1.Text += "Start: " + hookHandle + Environment.NewLine;
}
private void button2_Click(object sender, System.EventArgs e)
{
// Unhook the keyboard hook.
textBox1.Text += "End: " + UnhookWindowsHookEx(hookHandle) ...