Thursday, May 5, 2011

ProcessCmdKey in Windows Form

Many time we need to trap the key pressed in Windows Form and based on it perform some operation. For example, stop user from closing the application when user press Alt+F4. Or want to stop user from moving from one child form to another child in a mdi form using Ctrl+Tab or stop user from moving from one tabpage to another tabpage in TabControl control. In this case ProcessCmdKey method is the best option.

ProcessCmdKey is a method in .NET which process the command key. This method is called during message preprocessing to handle command keys. Command keys are keys that always take precedence over regular input keys. The method return true to indicate that it has processed the command key, or false to indicate that the key is not a command key. This method is only called when the control is hosted in a Windows Forms application or as an ActiveX control.

The following example with stop user from closing the form when user press Alt+F4 and also stop user from navigate to another tabpage or child form by using Ctrl+Tab.

    Public Class Form1
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
keyData = (Keys.Alt Or Keys.F4) Then
Return True
keyData = (Keys.Control Or Keys.Tab) Then
Return True
Return MyBase
.ProcessCmdKey(msg, keyData)
End If
End Function
End Class