|
|
|||
| H o m e | |||
| O v e r r i d i n g a C o n t r o l ’ s P r o c e s s C m d K e y F u n c t i o n | |||
|
|
By Michael McIntyre
In some situations overriding a control’s ProcessCmdKey function is the best way to intercept and control command key messages. You can override the ProcessCmdKey function in classes which inherit from the Control class. This includes the Windows Form and form control classes.
This ProcessCmdKey function is called during message preprocessing to handle command keys. Command keys are keys that always take precedence over regular input keys. Examples of command keys include accelerators, menu shortcuts, Home, Page Up, PageDown, and End.
Example: Below is a custom TextBox class that prevents the PageDown, PageUp, Home, and End keys (messages) from reaching the TextBox. As demonstrated in the example, when overriding the ProcessCmdKey method in a derived class, a control should return true to indicate that it has processed the key. For keys that are not processed by the control, the result of calling the base class's ProcessCmdKey method should be returned.
Imports System.Windows.Forms Public Class CustomTextBox Inherits System.Windows.Forms.TextBox ' Example: Override ProcessCmdKey function. Protected Overrides Function ProcessCmdKey( _ ByRef msg As System.Windows.Forms.Message, _ ByVal keyData As System.Windows.Forms.Keys) As Boolean ' Declare a variable of type Keys enumeration ' named keyPressed. ' Cast the msg's WParam as a KeyEnum value ' and assign it to the keyPressed variable. Dim keyPressed As Keys = CType(msg.WParam.ToInt32(), Keys) ' Process keyPressed. Select Case keyPressed Case Keys.PageDown ' Cancel PageDown key message. Return True Case Keys.PageUp ' Cancel PageUp key message. Return True Case Keys.Home ' Cancel Home key message. Return True Case Keys.End ' Cancel End key message. Return True Case Else ' Return the key message so it can be ' processed by this control. Return MyBase.ProcessCmdKey(msg, keyData) End Select End Function End Class
NOTE: If a Form or form control has a ContextMenu the key message is processed differently. Visit the help link below to learn more.
Learn more about the ProcessCmdKey function by clicking here.
|
||
|
Copyright © 2001-2003 aZ Software Developers. All rights reserved. |
|||