Keystroke Text Case Change

in Visual Basic®

by Rick Meyer

Home

Change the case of text in a textbox from lower to upper (a to A) or upper to lower (Z to z) with a single keystroke. F8 is used here as the function key, but you could easily change it to any function key.

There is an auto advance so repeated keystrokes or just holding down the F8 key will continue changing case until the end of the text.

This code toggles whatever is at the cursor to the opposite case. Based on this demo you could add function keys that would force either all upper case or all lower case.

    Instructions for Building this Project:

1. Start a new standard exe.
2. On Form1 put a TextBox named Text1.

You may also use a RichTextBox by:

Either changing the RichTextBox.Name property to Text1
or changing Text1 in the following code to RichTextBox1.

Now you are ready for the code. Select all of the following code (by clicking on the word 'Option' three times) and copy it to the clipboard [Ctrl][Insert]. Then paste it into the code window of Form1 with [Shift][Insert]. Variable Key
% As Integer
& As Long
! As Single
# As Double
$ As String
Option Explicit

Private Sub Text1_KeyDown(KeyCode%, Shift%)
    Static b%, L&, start&
    
    L = Len(Text1.Text)
    If L = 0 Then Exit Sub
    
    Select Case KeyCode
        Case vbKeyF8
            KeyCode = 0
            With Text1
                If .SelStart >= L Then Exit Sub
                start = .SelStart + 1
                b = Asc(Mid$(.Text, start, 1))
                Select Case b
                    Case 97 To 122: b = b And 223
                        'Lower to Upper
                        .SelLength = 1
                        .SelText = Chr$(b)
                    Case 65 To 90: b = b Or 32
                        'Upper to lower
                        .SelLength = 1
                        .SelText = Chr$(b)
                    Case 13
                        'Add 1 Char for CrLf (13 10)
                        start = start + 1
                End Select
                .SelStart = start
            End With
    End Select
End Sub