Use TabControl accelerators in C#

Use TabControl accelerators in C#

This example shows how you can use TabControl accelerators, such as pressing Alt+X to open the X tab. Unfortunately the TabControl doesn’t support accelerators. In fact, the tabs can’t even display underlined characters. This example shows how to provide these features.

First make an owner-drawn TabControl that draws the tabs with underlined accelerator keys. (Note that this example always displays the accelerator keys underlined. Some operating systems only underline these keys after the user presses the Alt key.) For more information on owner-drawn TabControls, see Make an owner-drawn TabControl in C#.

Next set the form’s KeyPreview property to true. In the form’s KeyDown event handler, look for TabControl accelerators and select the appropriate tabs. This example uses the following code to look for Alt+B, Alt+L, and Alt+D.

// Look for Alt+B, Alt+L, and Alt+D.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Alt)
    {
        switch (e.KeyCode)
        {
            case Keys.B:
                tabMenu.Focus();
                tabMenu.SelectedTab = tabPageBreakfast;
                e.Handled = true;
                e.SuppressKeyPress = true;
                break;
            case Keys.L:
                tabMenu.Focus();
                tabMenu.SelectedTab = tabPageLunch;
                e.Handled = true;
                e.SuppressKeyPress = true;
                break;
            case Keys.D:
                tabMenu.Focus();
                tabMenu.SelectedTab = tabPageDinner;
                e.Handled = true;
                e.SuppressKeyPress = true;
                break;
        }
    }
}

This code checks e.Alt to see if the Alt key is pressed. If it is, the code checks e.KeyCode to see if the B, L, or D key is also pressed. If one of those combinations is pressed, the code gives the TabControl focus, selects the appropriate tab page, and suppresses the key press so the form doesn’t beep.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, user interface and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *