Developer

Create a 'sticky' button that toggles in VB6

If you want to use a VB6 Command Button that you can toggle, then learn how to create "sticky" buttons, which are useful for selecting On/Off options as an alternative to a checkbox.

VB6's Command Buttons are widely used for registering user input such as mouse clicks. The normal behavior of these buttons is to appear "raised" normally, then to appear "down" during the click, and return to the "raised" appearance when the mouse button is released.

For most users, this is what they want. However, you may prefer a Command Button that you can toggle. You could click it once and it would stay in the "down" state; click it again and it would return to the "raised" appearance. These types of "sticky" buttons are useful for selecting On/Off options as an alternative to a checkbox.

To create a "sticky" button, you need to send a message to the Command Button using the SendMessageBynum Windows API function. You must put the function declaration in your program, as well as a constant definition:

Public Const BM_SETSTATE = &HF3

Declare Function SendMessageBynum Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
    ByVal lParam As Long) As Long

Then it's a simple matter of toggling the button in its Click event procedure. The following code changes the button's caption as well:

Private Sub Command1_Click()

Static Downstate As Long

Downstate = Not Downstate

If Downstate Then
    Command1.Caption = "Option On"
Else
    Command1.Caption = "Option Off"
End If

Call SendMessageBynum(Command1.hwnd, BM_SETSTATE, Downstate, 0)

End Sub

If you make the Downstate variable global rather than local, code in other parts of the program will be able to check the button's state as needed.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

0 comments

Editor's Picks