Can anyone help please?
How can I give focus to a textbox (for example we have two) by defining a shortcut key as alt+m ?
Thanks in advance
Btw, I'm a beginner so please tell me in the simplest way. :)

Dani AI

Generated

Good suggestions from and — using a label as an access key is the standard VB6 way to make an Alt+letter put focus into a nearby field (labels forward focus to the next focusable control in the tab order). (stackoverflow.com)

If the label method didn’t work in the OP’s form (what reported), check a few non-obvious issues before changing approach:

  • The target control must be able to receive focus (TabStop True, visible and enabled).
  • The label must be configured to act as a mnemonic (the label’s mnemonic/UseMnemonic behavior must be enabled).
  • If controls live inside a Frame or other container, tab order is local to that container — the label needs to precede the textbox in that container’s tab order.
  • A form-level key handler or a menu with the same Alt mnemonic can intercept the key. (xxxmen.github.io)

When label mnemonics aren’t suitable (conflicts, unusual layout), explicitly handle Alt+key in the form KeyDown event. Set the form’s KeyPreview so the form sees keys first, then detect Alt+letter and call SetFocus. Example:

Private Sub Form_Load()
    Me.KeyPreview = True
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    If (Shift And vbAltMask) <> 0 And KeyCode = vbKeyM Then
        Text2.SetFocus
    End If
End Sub

The KeyPreview/KeyDown pattern and the vbKey / shift-mask constants are standard VB idioms. Use this when you need a programmatic fallback or nonstandard shortcuts. (learn.microsoft.com)

Recommended Answers

All 4 Replies

Use a Label in front of each text box and in the Caption for the Label, use an & in front of the letter to define the shortcut key - &m in your example. Make sure the Label's TabIndex is one less than the TabIndex for its associated TexBox. That should do it.

Well this doesn't work out. :(
Can anyone please help me out? I have an exam coming. :(

While, I would suggest using a menu with a key combination shortcut, the suggestion by SCBWV does work...

Start a new standard exe project and add in this order, text box (text1), label (label1), text box (text2). Now set the caption of the label to &Focus. You should see Focus in the labels caption. Now, just to make sure that the tab orders are correct, lets check.

Text1 TabIndex = 0
Label1 TabIndex = 1
Text2 TabIndex = 2

Run the program and press ALT+F. You should see the carat jump from text1 to text2.

Good Luck

Thank you so much dear. It worked out perfectly. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.