Click here to Skip to main content
16,013,918 members
Articles / Programming Languages / Visual Basic
Article

TabKeyIntercept - Intercept and process the Tab key in a Windows.Forms form

Rate me:
Please Sign up or sign in to vote.
4.30/5 (9 votes)
4 Sep 2008CPOL2 min read 51.2K   695   18   8
This article describes a method to intercept the Tab key in a .NET application's form and thereby allow the use of the Tab key in a customized or application-specific meaning.

The Issue

Sometimes, in our applications, it would be helpful to assign a specialized meaning to the use of the Tab key. That is, rather than the normal action of changing the focus to the next control on the tab-order, one might wish the Tab key to cause some other action or event.

For instance, in one of my applications, I wanted to use the Tab key to cause the program to display the next group of images (or the previous group, if Shift-Tab is pressed). Now, of course, I could use the PageUp and PageDown keys for these functions, but -- assuming a right-handed user moving the mouse with his right hand -- that would require the user to "waste" time moving between the mouse and the keyboard. One purpose of this particular application is to allow a quick visual inspection of perhaps several hundred images (per order), and we want to spend the minimum of time on each order.

The Unfortunate Complication

"No problem," I thought. At first. "I'll just use the protected override void OnKeyDown(KeyEventArgs args) method to determine that the user has used the Tab key."

Unfortunately, under normal circumstances, the Tab key does not make it into the OnKeyDown() and related methods. I say "normal circumstances" because I've noticed that one way of coding the methodology described here will cause the Tab key to reach the OnKeyDown() method.

The Fortunate Resolution

Fortunately, in the base Form class, there exists the protected override bool ProcessTabKey(bool forward) method. Using this method, we can intercept and "consume" the Tab key.

And, as it turns out, if the ProcessTabKey() method's return value is false, the Tab key does make it into the OnKeyDown() method. But, of course, if your code "consumes" the Tab key in the ProcessTabKey() method, you probably won't need to process it in the OnKeyDown() method.

Also, the Control-Tab combination makes it into the OnKeyDown() method.

So, knowing these things, we are prepared to define a customized use for the Tab key -- and we can code the form to allow the user to use the Control-Tab combination to toggle between the normal use/meaning of the Tab key and our custom use.

C# Example Code

Keep in mind that you'll generally want to set the form's .KeyPreview property to true (depending on the content of the form, this may not be necessary).

C#
private void InitializeComponent()
{
    // ...
    this.KeyPreview = true;
    // ...
}

#region Overridden Methods: [OnKeyDown()] and 
        [ProcessTabKey()] -- Intercept/process [Keys.Tab]
// protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs args)
// protected override bool ProcessTabKey(bool forward)
// 
protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs args)
{
    if( (args.Modifiers == System.Windows.Forms.Keys.Control) 
    && (args.KeyCode == System.Windows.Forms.Keys.Tab) )
    {
        interceptTabKey = !interceptTabKey;
    }

    base.OnKeyDown(args);
}

private bool interceptTabKey = true;
protected override bool ProcessTabKey(bool forward)
{
    // We can intercept/process the [Keys.Tab] via this method.
    if (interceptTabKey)
    {
        if (forward)            // [Keys.Shift] was not used
        {
            // do something
        }
        else                    // [Keys.Shift] was used
        {
            // do something
        }

        // [return true;]  -- To indicate that a control is selected.
        // [return false;] -- Also, it happens that [return false;] causes the TabKey 
        //                    to be processed by the [OnKeyDown()] and related methods.
        return true;
        //return false;
    }

    return base.ProcessTabKey(forward); // One would normally do this, but we may
                                        // have wanted to intercept [Keys.Tab] above
}
#endregion

Visual Basic Example Code

Keep in mind that you'll generally want to set the form's .KeyPreview property to True (depending on the content of the form, this may not be necessary).

VB
Private Sub InitializeComponent()
    ' ...
    Me.KeyPreview = True
    ' ...
End Sub

#Region "Overridden Methods: [OnKeyDown()] and 
        [ProcessTabKey()] -- Intercept/process [Keys.Tab]"
' protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs args)
' protected override bool ProcessTabKey(bool forward)
' 
Protected Overrides Sub OnKeyDown(ByVal args As System.Windows.Forms.KeyEventArgs)
    If args.Modifiers = System.Windows.Forms.Keys.Control _
    And args.KeyCode = System.Windows.Forms.Keys.Tab Then
        If interceptTabKey Then
            interceptTabKey = False
        Else
            interceptTabKey = True
        End If
    End If

    MyBase.OnKeyDown(args)
End Sub

Dim interceptTabKey As Boolean = True
Protected Overrides Function ProcessTabKey(ByVal forward As Boolean) As Boolean
    ' We can intercept/process the [Keys.Tab] via this method.
    If interceptTabKey Then
        If forward Then                 ' [Keys.Shift] was not used
            ' do something
        Else                            ' [Keys.Shift] was used
            ' do something
        End If

        ' [Return True]  -- To indicate that a control is selected.
        ' [Return False] -- Also, it happens that [Return False] causes the TabKey 
        '                   to be processed by the [OnKeyDown()] and related methods.
        Return True         ' 'True' indicates that a control is selected
        'Return False
    End If

    ' One would normally do this, but we may
    ' have wanted to intercept [Keys.Tab] above
    Return MyBase.ProcessTabKey(forward)
End Function
#End Region

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerGood code Pin
-tusk-7-Jul-14 11:53
-tusk-7-Jul-14 11:53 
GeneralRe: Good code Pin
Ilíon9-Jul-14 3:24
Ilíon9-Jul-14 3:24 
I'm glad you found it useful. Thank you for your comment.
GeneralThank you! Pin
RealityRipple18-Mar-12 13:51
RealityRipple18-Mar-12 13:51 
GeneralRe: Thank you! Pin
Ilíon18-Mar-12 15:48
Ilíon18-Mar-12 15:48 
GeneralUse with extreme caution Pin
Darchangel8-Sep-08 9:36
Darchangel8-Sep-08 9:36 
GeneralDo *anything* with extreme caution [modified] Pin
Ilíon9-Sep-08 5:31
Ilíon9-Sep-08 5:31 
Questionhow about default button and cancel button Pin
Huisheng Chen4-Sep-08 20:25
Huisheng Chen4-Sep-08 20:25 
AnswerRe: how about default button and cancel button Pin
RealityRipple18-Mar-12 13:49
RealityRipple18-Mar-12 13:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.