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 LongPrivate Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" _    (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As LongConst GWL_STYLE = -16Const BS_AUTOCHECKBOX = 1' Make a checkbox control read-only (or restore its' regular behavior).' Doesn't work well if the Style property is set to 1-GraphicalSub 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    Else        lStyle = lStyle And (Not BS_AUTOCHECKBOX)    End If    SetWindowLong CheckBox.hWnd, GWL_STYLE, lStyleEnd Sub

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: