2

I have been trying to get this to work but it's doing my head in, wondered if you experts can help me out.

On my form I would like to set focus to a TextBox when I press F1 on the keyboard, I have the code written but somehow it does not work when I press F1. What am I doing wrong? I have also set keypreview to true.

The code here:

 Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
        If e.KeyData = Keys.F1 Then
            txtemployeeno.Focus() 
        End If
End Sub
Chris Barlow
  • 3,274
  • 4
  • 31
  • 52
user3562155
  • 51
  • 1
  • 12

1 Answers1

2

The problem is that your KeyUp event isn't firing because the form doesn't technically have input focus (though it may be activated). If you wish to use the KeyPreview property, you need to use the KeyPress event instead of KeyUp.

Alternatively, you could always override the ProcessCmdKey function. Just add the following method to your form's code:

   Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
      If keyData = Keys.F1 Then
         txtemployeeno.Focus()
         Return True
      End If

   Return MyBase.ProcessCmdKey(msg, keyData)
   End Function
Chris Barlow
  • 3,274
  • 4
  • 31
  • 52
  • I've changed it, but i get keydata is not a member of system.windowsforms.keypresseventsargs? – user3562155 Jun 12 '14 at 14:50
  • You won't be able to check the key data very easily using KeyPress. My suggestion above to use `ProcessCmdKey` might be a better fit for what you're doing. Additional Reading: http://stackoverflow.com/q/17948204/590783 – Chris Barlow Jun 12 '14 at 14:52
  • 1
    I hate to play this card but it works on my machine. =( You placed the `ProcessCmdKey` code in the form that contains your text box right? Please place a breakpoint on `txtemployeeno.Focus()` and ensure that you are reaching that line of code. – Chris Barlow Jun 12 '14 at 15:00