Archive for the ‘VB.Net’ Category

VB.Net – Keydown event not firing with WinForm application

December 4, 2013 Leave a comment

As part of my recent project I was handed with a job to create a windows form application. In this application I had to capture arrow key events. For my surprise the key event where not firing for arrow keys. I tried setting “KeyPreview” but that didn’t helped. Then I realized these are special keys and controls in the form will intercept these.

The solution was to override ProcessCmdKeys function as below

For demonstration, add a PictureBox control and change its background color. Pressing arrow key will move it around the form

Public Class Form1
    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keydata As Keys) As Boolean
        If keydata = Keys.Right Then
            PictureBox1.Left += 10
        End If

        If keydata = Keys.Left Then
            PictureBox1.Left -= 10
        End If

        If keydata = Keys.Up Then
            PictureBox1.Top -= 10
        End If

        If keydata = Keys.Down Then
            PictureBox1.Top += 10
        End If

        If keydata = Keys.Right Or keydata = Keys.Left Or keydata = Keys.Up Or keydata = Keys.Down Then
            OnKeyDown(New KeyEventArgs(keydata))
            ProcessCmdKey = True
            ProcessCmdKey = MyBase.ProcessCmdKey(msg, keydata)
        End If
    End Function
End Class
Categories: VB.Net

RichTextBox – Highlight line on Click event

Handle Mouse Down event as shown below

Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles RichTextBox1.MouseDown
Dim box = DirectCast(sender, RichTextBox)
Dim index = box.GetCharIndexFromPosition(e.Location)
Dim line = box.GetLineFromCharIndex(index)
Dim lineStart = box.GetFirstCharIndexFromLine(line)
Dim lineEnd = box.GetFirstCharIndexFromLine(line + 1)
If lineEnd = -1 Then
lineEnd = box.TextLength
End If
box.SelectionStart = lineStart
box.SelectionLength = lineEnd - lineStart
End Sub

Categories: Misc, VB.Net Tags: