How to Programmatically Display or Hide a VB Combo Box List

ID Number: Q85991

1.00

WINDOWS

Summary:

The list of a Visual Basic drop-down combo box (Style=0 or 2) is

usually opened and closed by using a mouse. However, you can also

open and close the list of a combo box programmatically by using the

Windows SendMessage function as described below.

This information applies to Microsoft Visual Basic programming system

version 1.0 for Windows.

More Information:

The CB_SHOWDROPDOWN constant can be used with the SendMessage

function to programmatically open or close the list of a Visual

Basic drop-down combo box of Style=0 or Style=2 (Style=1 always has

the list displayed). The following steps demonstrate how to open the

list of a drop-down combo box:

1. Run Visual Basic, or from the File menu, choose New Project

(ALT, F, N) if Visual Basic is already running. Form1 is created

by default.

2. Place a combo box (Combo1) and a command button (Command1) on

Form1.

3. Add the following declarations and constants to the general

Declarations section of Form1:

Declare Function GetFocus Lib "User" () as Integer

Declare Function GetParent Lib "User" (ByVal hWnd as Integer)

as Integer

Declare Function SendMessage Lib "User" (ByVal hWnd as Integer,

ByVal wMsg as Integer,

ByVal wParam as Integer,

ByVal lParam as Any) as

Long

' Each Declare above must be on one line.

Global Const WM_USER = &H400

Global Const CB_SHOWDROPDOWN = WM_USER + 15

4. Add the following code to the Form1 Load event procedure to put

some items in the combo box:

Sub Form_Load ()

Combo1.AddItem "apple"

Combo1.AddItem "orange"

Combo1.AddItem "banana"

End Sub

5. Add the following code to the Command1_Click event procedure:

Sub Command1_Click ()

Combo1.SetFocus

cbhWnd% = GetFocus ()

cblisthWnd% = GetParent (cbhWnd%)

cbFunc% = -1 'cbFunc% = -1 displays the list

'cbFunc% = 0 hide the list

retval& = SendMessage (cblisthWnd%, CB_SHOWDROPDOWN,

cbFunc%, 0&)

End Sub

6. Press F5 to run the program. Click on Command1 to display the list

of the combo box.

If Style=2 for the combo box, there is no need to use the GetParent

function. Use the return value of the GetFocus (cbhWnd% in the above

example) call as the first parameter of the SendMessage function.

(Note: The list of a combo box with Style=0 or 2 will close whenever

the combo box loses focus.)

Additional reference words: 1.00