Search This Blog

Saturday, January 28, 2012

VB.net, Getting arrow key input on controls

If you haven't already, you should read my previous blog post on Custom Text Boxes in VB.net, otherwise this post might not make much sense.

So, I got most of the functionality of a good text box working today, except using arrow keys to move the caret around the text.  I tried many different approaches, but no matter what I did, arrow keys and tab were moving focus around in my form instead of being handled by KeyDown.  I went back into the EnhancedTextBox class and started to poke around the protected overrides functions to find one that might help me out, and boy did I ever find it: ProcessCmdKey.

I added this code to the EnhancedTextBox class:

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
    If keyData = Keys.Up Or keyData = Keys.Down Or keyData = Keys.Left Or keyData = Keys.Right Then
        OnKeyDown(New KeyEventArgs(keyData))
        ProcessCmdKey = True
    ElseIf keyData = Keys.Tab Then
        OnKeyPress(New KeyPressEventArgs(Chr(9)))
        ProcessCmdKey = True
    Else
        Return MyBase.ProcessCmdKey(msg, keyData)
    End If
End Function

Now I'm able to capture KeyCode.Up, KeyCode.Down, KeyCode.Left, and KeyCode.Right in the KeyDown event handler and I can receive Tab as a keypress (ASCII code 9) in the KeyPress handler.  So that's spiffy.
Here's what the text editor control looks like right now.


It doesn't do syntax highlighting yet, but Rome wasn't built in one day, either.

No comments:

Post a Comment