天天看點

獲得VB listbox 選中項目(多項)的一個好方法

傳統方法是周遊一遍

如果listbox 項目過多

明顯速度不行

好方法是通過sendmessge發消息給listbox讓他把選中項目直接傳到參數數組中

You can use the SendMessage() API function instead.

As you probably know, this function lets you send a message to one or more windows. The declaration statement conforms to the following syntax:

Private Declare Function SendMessage Lib "user32" _

   Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg _

   As Long, ByVal wParam As Long, lParam As Any) As Long

Since we want to gather the listbox: selected items, we'll send the LB_GETSELITEMS constant in the wMsg argument, which you declare like so:

Private Const LB_GETSELITEMS = &H191

The LB_GETSELITEMS message fills an array with the index numbers of all the selected items.

Dim ItemIndexes() As Long, x As Integer, iNumItems As Integer

iNumItems = ThisBox.SelCount

If iNumItems Then

   ReDim ItemIndexes(iNumItems - 1)

   SendMessage ListBox1.hwnd, LB_GETSELITEMS, iNumItems, ItemIndexes(0)

End If

For x = 0 To iNumItems - 1

   MsgBox ListBox1.List(ItemIndexes(x)) '彈出對話框

Next x

After being passed to the SendMessage function, iNumItems holds the total number of selected items, and the ItemIndexes array holds the selected item index values. Notice, that you must pass a pointer to the ItemIndexes array, and not the array itself. Thus, we passed ItemIndexes(0) into the SendMessage function, not ItemIndexes().

繼續閱讀