Recipe 14.19. Intercepting All Key Presses on a Form


Problem

You have a form that needs to watch for certain keys and process them before any control on the form recognizes those keys.

Solution

Sample code folder: Chapter 14\InterceptKeys

Use the form's KeyPreview property to control access to the form's KeyDown, KeyUp, and KeyPress events.

Discussion

Create a new Windows Forms application, and add a single TextBox control named TextBox1. Set the form's KeyPreview property to TRue. Now add the following code to the form's class:

 Private Sub Form1_KeyDown(ByVal sender As Object, _       ByVal e As System.Windows.Forms.KeyEventArgs) _       Handles Me.KeyDown    If (e.KeyCode = Keys.F5) Then MessageBox.Show("Form: F5")    e.Handled = True End Sub Private Sub TextBox1_KeyDown(ByVal sender As Object, _       ByVal e As System.Windows.Forms.KeyEventArgs) _       Handles TextBox1.KeyDown    If (e.KeyCode = Keys.F5) Then MessageBox.Show("Text: F5") End Sub 

Run the program, and press the F5 key when the input focus is in the text box. You should receive only the "Form: F5" message.

Modify the program by commenting out the e.Handled = True line in the form's KeyDown event handler, and then run the program again. This time, you will receive both messages when you press F5.

Modify the program once again, setting the form's KeyPreview property to False. When you run the program and press F5, only the "Text: F5" message will appear.

Normally, a form ignores all keyboard input whenever a control on that form has the input focus. But you can alter that behavior by setting the KeyPreview property to TRue. Once set, the program sends all keyboard input first to the form's key-focused event handlers, and after that it sends those same key events to the active control. Stopping processing at the form level is accomplished by setting the e.Handled property to true in any of the form-level keyboard event handlers.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net