Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4/32,VB5,VB6
Expertise: Intermediate
Oct 30, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Make a Checkbox control read-only

By default, VB's CheckBox controls automatically toggle their Value property when the user clicks on them. This is usually the desired behavior, but at times you may want to be able to change their value only programmatically. Unfortunately, you can't achieve this result by simply setting the CheckBox control's Enabled property to False, because this would have a visual impact on the user interface.

However, you can reach the desired result by simply place the CheckBox inside a borderless Frame control and set the Frame control's Enabled property to False. This will automatically disable the CheckBox control, but without changing its appearance.

If you don't want to add a Frame control just for making a CheckBox control read-only, you can use the following routine, that modifies the CheckBox control's style:

Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" _
    (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" _
    (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Const GWL_STYLE = -16

' Make a checkbox control read-only (or restore its
' regular behavior).
' Doesn't work well if the Style property is set to 1-Graphical

Sub MakeCheckBoxReadOnly(CheckBox As CheckBox, ByVal bReadOnly As Boolean)
    Dim lStyle As Long
    lStyle = GetWindowLong(CheckBox.hWnd, GWL_STYLE)
    If bReadOnly Then
        lStyle = lStyle Or BS_AUTOCHECKBOX
        lStyle = lStyle And (Not BS_AUTOCHECKBOX)
    End If
    SetWindowLong CheckBox.hWnd, GWL_STYLE, lStyle
End Sub

Marco Bellinaso
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date