7.10. Using the Windows Keyboard Hook
Problem
You need to watch and respond to specific user keyboard input, and, based on the input, you want to perform one or more actions. For example, pressing the Windows key and the E key at the same time launches Windows Explorer. You would like to add other Windows key combinations for your own applications. In addition, you could prevent the user from using specific keys (such as the Windows key) from within your application.
Solution
The following Windows Forms application
uses the WH_KEYBOARD
Windows hook:
using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsApplication2 { public class Form1 : System.Windows.Forms.Form { // Required designer variable. private System.ComponentModel.Container components = null; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox1; public Form1( ) { // Required for Windows Form Designer support InitializeComponent( ); } protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose( ); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent( ) { this.button1 = new System.Windows.Forms.Button( ); this.button2 = new System.Windows.Forms.Button( ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.