I want to make text boxes respond to the insert key, so the user can switch between insert and overwrite mode in my text boxes. Currently they always seem to be stuck in insert mode.
Printable View
I want to make text boxes respond to the insert key, so the user can switch between insert and overwrite mode in my text boxes. Currently they always seem to be stuck in insert mode.
Try something like this. Set the form's KeyPreview to true, Add a textbox, Text1, and paste this code in the Declarations section:
This could use a little improvement, eg, the arrow keys lose functionality when insert mode is on..Code:Private insert As Boolean
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyInsert Then insert = Not insert
End Sub
Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
If Not insert And Text1.SelLength = 0 Then
Text1.SelLength = 1
End If
End Sub
Thanks, that will be helpful.
'This should work properly
Private Declare Function GetKeyState Lib "User32" (ByVal nVirtKey As Integer) As Integer
Public Function InsertMode() As Boolean
Dim insert%
insert = GetKeyState(vbKeyInsert)
If insert And 1 Then
InsertMode = True
Else
InsertMode = False
End If
End Function
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim char As String
If InsertMode() = False Then
If Text1.SelLength <= 1 Then
char$ = Mid$((Text1.Text), Text1.SelStart + 1, 1)
If char$ = vbCr Then
Text1.SelLength = 2
Else
Text1.SelLength = 1
End If
End If
End If
End Sub