The SendMessage API
Read Only Text Controls Sample
Now that I could set the text control to a read only state the only remaining thing was to stop the control from getting focus in the tab sequence. Easy - just set the tabstop property to false you may suggest. But when I click on the control it still gets the focus, which is not what I wanted.
To overcome this the sendkeys function came in very handy to tab past any offending fields. Why use sendkeys, rather than just using setfocus to the next control in the sequence? That is true. The problem there is if the client wanted to change the order in which the entered data instead of just changing the tab sequence I would have also had to modify code for every control on the form. Another advantage of using this approach is that if you have a mixture of editable controls, like the standard text boxes and some Microhelp input controls the routines will work regardless.
Declare Function SendMessage Lib "User" (ByVal Hwnd As Integer, _
ByVal wMsg As Integer, ByVal wParam As Integer, lParam As Any) As Long
Global Const EM_SETREADONLY = &H41F
Global Const GREY = &HC0C0C0
Sub ReadOnly (ctl As Control) ' Pass subroutine a text control to set it to readonly eg. ReadOnly Text1
Dim ret As Long
ctl.BackColor = GREY
ctl.TabStop = False ' Just in case
ret = SendMessage(ctl.Hwnd, EM_SETREADONLY, True, 0)
End Sub
Sub ReadWrite (ctl As Control) ' Pass subroutine a text control set it to read write eg. ReadWrite Text1
Dim ret As Long
ctl.BackColor = WINDOW_BACKGROUND ' &H80000005&
ctl.TabStop = True
ret = SendMessage(ctl.Hwnd, EM_SETREADONLY, False, 0)
End Sub
' Choose one of the following routines and place the call into the
' GotFocus event of your text control :
Sub Tab2next (ctl As Control) ' skip the ctl passed
If ctl.BackColor = GREY Then
SendKeys "{TAB}"
End If
End Sub
Sub SelectAll (ctl As Control) ' Routine also highlights text when readwrite text box gets focus
End Sub
Finally, you can also use this approach to set up security in your app that sets certain fields to be read only depending upon whatever parameter you choose.
![]()