Make a Checkbox control read-only

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

See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

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