Hotkey Assignments - Tab Control

MFarley01

Member
Joined
May 31, 2007
Messages
5
Programming Experience
3-5
Hello, I am relatively new to using VB.net and would be grateful if someone could help me.

I am working on a form which dynamically creates tab panels on a tab control. Essentially, there is a numeric_updown object which determines how many tab panels are to be created i.e. user enters 3, 3 tab panels appear.

I have managed to get this part working, but am having trouble with assigning hotkeys to the tab panels. I need to use the keypress or keydown event handler to allow the user to press 'Ctrl' plus a number on the keyboard which correlates to the tab panel they wish to view. So when the user presses Ctrl and the number 3 for example, the 3rd tab come into focus on the form.

I would be extremely grateful for any pointers or tips that anyone could give me.

Thanks :)
 
Here is one way to do it once a key has been selected for a TabPage, with what interface you make that connection is up to you. TabControl KeyDown event is used here to make the tab selection, but that requires a tab to have focus already, perhaps I would use the Forms KeyDown instead (depends on the layout I guess).
VB.NET:
    Dim tcHotkeys As New Dictionary(Of Keys, TabPage)

    Sub Setuptabs()
        Dim tp As New TabPage
        tp.Text = "tab A"
        tcHotkeys.Add(Keys.A, tp)
        TabControl1.TabPages.Add(tp)

        tp = New TabPage
        tp.Text = "tab B"
        tcHotkeys.Add(Keys.B, tp)
        TabControl1.TabPages.Add(tp)

        tp = New TabPage
        tp.Text = "tab C"
        tcHotkeys.Add(Keys.C, tp)
        TabControl1.TabPages.Add(tp)
    End Sub

    Private Sub TabControl1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) _
    Handles TabControl1.KeyDown
        If e.Control AndAlso tcHotkeys.ContainsKey(e.KeyCode) Then
            TabControl1.SelectedTab = tcHotkeys(e.KeyCode)
        End If
    End Sub
 
Just one more quick question, how can I assign key combos as hotkeys?

For example, I would like Ctrl+1 to open up tab 1, Ctrl+2 to open up tab 2 etc, instead of just pressing 1 or 2.

Thanks Again.
 
The example was using and requiring Ctrl modifier key (If e.Control AndAlso ...).

A value of type Keys can be combined and compared for modifiers (and only those!) with regular bitwise operations. For example:
Dim combined As Keys = Keys.Control Or Keys.A
'combined' value is here both value Keys.Control and value Keys.A

If you set a combination for the tab (like ctrl+a, shift+b, alt+c) you check if e.KeyData is equal to your hotkey combination. e.KeyData holds the full combination of keys currently pressed.
 
Back
Top