devxlogo

Undo changes in a TextBox control

Undo changes in a TextBox control

The TextBox control supports the capability to undo changes, but there is no property or method that exposes this feature. You can achieve the same goal with a a set of messages.

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal _    hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _    lParam As Any) As LongConst EM_CANUNDO = &HC6Const EM_UNDO = &HC7Const EM_EMPTYUNDOBUFFER = &HCD

The EM_CANUNDO message returns a non-zero value if the contents of the TextBox control can undone. The EM_UNDO message actually undoes all changes:. The following code demonstrates how you can use these messages in a typical Edit menu:

Private Sub mnuEdit_Click()    If TypeOf ActiveControl Is TextBox Then        ' check whether changes to the current         ' TextBox control can be undone        mnuEditUndo.Enabled = SendMessage(ActiveControl.hWnd, EM_CANUNDO, 0, _            ByVal 0&)    Else        ' in all other cases, disable this menu command        mnuEditUndo.Enabled = False    End IfEnd SubPrivate Sub mnuEditUndo_Click()    ' Undo the most recent edit operation on the active control     ' (no need to use TypeOf...Is to check the control's type)    SendMessage ActiveControl.hWnd, EM_UNDO, 0, ByVal 0&End Sub

Finally, the EM_EMPTYUNDOBUFFER clears the internal undo buffer, so that the user can’t undo changes.

SendMessage ActiveControl.hWnd, EM_EMPTYUNDOBUFFER, 0, ByVal 0&

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist