首先新建一個(gè)VB工程,,順序點(diǎn)擊菜單 工程(P)→部件(O)... 打開 部件 對(duì)話框,勾選 Microsoft Windows Common Controls 6.0 (SP6) 并單擊確定,,關(guān)閉對(duì)話框,,如圖1所示。
圖1
選擇并在窗體上畫出 ListView 控件,,如圖2所示,。
圖2
然后在窗體上雙擊鼠標(biāo),輸入如下代碼:
Option Explicit
Dim b_MouseDown As Boolean, FirstItem As ListItem
Private Sub Form_Load()
Dim iCount As Integer, Item As ListItem
'設(shè)置ListView外觀并添加項(xiàng)目
With ListView1
.View = lvwReport
.MultiSelect = True
.FullRowSelect = True
For iCount = 1 To 8
.ColumnHeaders.Add Text:="Column " & iCount, Width:=1200
Next
For iCount = 1 To 30
Set Item = ListView1.ListItems.Add
Item.Text = iCount
Item.SubItems(1) = iCount * 20
Item.SubItems(2) = iCount * 30
Item.SubItems(3) = iCount * 40
Item.SubItems(4) = iCount * 50
Item.SubItems(5) = iCount * 60
Item.SubItems(6) = iCount * 70
Item.SubItems(7) = iCount * 80
Next
End With
End Sub
Private Sub ListView1_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
Dim iCount As Integer
If Button <> vbLeftButton Or ListView1.HitTest(x, y) Is Nothing Then Exit Sub
For iCount = 1 To ListView1.ListItems.Count
ListView1.ListItems(iCount).Selected = False
Next
Set FirstItem = ListView1.HitTest(x, y)
b_MouseDown = True
End Sub
Private Sub ListView1_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single)
Dim iCount As Integer, jCount As Integer, CurrentItem As ListItem
If Button <> vbLeftButton Or Not b_MouseDown Or ListView1.HitTest(x, y) Is Nothing Then Exit Sub
Set CurrentItem = ListView1.HitTest(x, y)
'從上向下拖選項(xiàng)目
If FirstItem.Index < CurrentItem.Index Then
For jCount = 1 To ListView1.ListItems.Count
For iCount = FirstItem.Index To CurrentItem.Index
ListView1.ListItems(iCount).Selected = True
If ListView1.ListItems(jCount).Index <> iCount Then ListView1.ListItems(jCount).Selected = False
Next
Next
End If
'從下向上拖選項(xiàng)目
If FirstItem.Index > CurrentItem.Index Then
For jCount = 1 To ListView1.ListItems.Count
For iCount = CurrentItem.Index To FirstItem.Index
ListView1.ListItems(iCount).Selected = True
If ListView1.ListItems(jCount).Index <> iCount Then ListView1.ListItems(jCount).Selected = False
Next
Next
End If
If FirstItem.Index = CurrentItem.Index Then
For jCount = 1 To ListView1.ListItems.Count
ListView1.ListItems(jCount).Selected = False
Next
CurrentItem.Selected = True
End If
End Sub
Private Sub ListView1_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
If Button = vbLeftButton Then b_MouseDown = False
End Sub
=========代碼結(jié)束=========
按 F5 運(yùn)行程序,,用鼠標(biāo)點(diǎn)中其中某個(gè)項(xiàng)目,,并上下拖拽鼠標(biāo)察看效果,如圖3所示,。
圖3