Click here to Skip to main content
Licence CPOL
First Posted 4 Sep 2008
Views 19,400
Downloads 193
Bookmarked 17 times

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

By | 4 Sep 2008 | Article
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).

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).

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)

About the Author

Ilíon



United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralThank you! PinmemberRealityRipple13:51 18 Mar '12  
GeneralRe: Thank you! PinmemberIlíon15:48 18 Mar '12  
GeneralUse with extreme caution PinmemberDarchangel9:36 8 Sep '08  
GeneralDo *anything* with extreme caution [modified] PinmemberIlíon5:31 9 Sep '08  
Darchangel wrote:
I've used countless programs where the creator thought they were being clever by making tab, enter, right-click, or any number of other things do something other than what these commands typically do. This is almost always entirely frustrating.
 
If you can really add to your program by doing things like this, then by all means do so. But think very carefully about the side effects before you do.

Yes, I too hate "too clever by half" programs.
 

But what I've presented here is not "too clever by half," and certainly not as I am using it. If other developers wish to be too clever, that's their issue.
 
Many keys -- including the Tab key -- have different meanings in different contexts. For instance, when certain types of controls have the focus, the Tab key does not shift focus to the next control in the form's tab-order. I'm using that fact to make life easier for the users of my application.
 

 
Also, if one has paid much attention to typical users of PCs as they are using one, it's obvious that most are oblivious to the typical/normal use of the Tab key and the Enter key. I've even had to put a button which does nothing at all on a form so that the typical user has something to click on (because I needed them to shift the focus off a textbox or combobox so that the program would know they had given it the information they themselves had wanted to give it).
 
modified on Tuesday, September 9, 2008 11:41 AM

Questionhow about default button and cancel button PinmemberUnruled Boy20:25 4 Sep '08  
AnswerRe: how about default button and cancel button PinmemberRealityRipple13:49 18 Mar '12  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120604.1 | Last Updated 4 Sep 2008
Article Copyright 2008 by Ilíon
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid