vb.netvb6-migration

Changing KeyCode under KeyDown handler of TextBox


I have to rewrite some my old code from VB6 to VB.NET and here is some things I don't know what to do. For example I have to replace some keycodes under keyDown event handler of textbox and I can't do this without help.

Most simple to say, I have workable VB6 code:

If KeyCode = vbKeyUp Then
   KeyCode = vbKeyEscape
End If

When I try to rewrite this literally:

If e.KeyCode = Keys.Up Then
   e.KeyCode = Keys.Escape
End if

But this won't go:

Error 2 Property 'KeyCode' is 'ReadOnly'.

Since I have much of such conversions to do is here any way to achieve this simple?


Solution

  • The best way to simulate this in VB.Net is to do the following. When you see the Up key is pressed cancel the event. Then send an artificial key event for the Escape key.

    Protected Overrides Sub OnKeyDown(ByVal e As KeyEventArgs)
        If e.KeyCode = Keys.Up Then
            e.Handled = True
            SendKeys.Send("ESC")
        Else
            MyBase.OnKeyDown(e)
        End If
    End Sub