您的位置:首页 > 编程语言 > VB

VB ListBox 借助winAPI实现鼠标自由拖放改变顺序

2016-12-07 21:27 477 查看
在窗体Form1上放置一个一个ListBox控件List1,然后在Form1的窗体代码里面复制以下即可

Option Explicit

Public item_height As Single
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
Private Const LB_GETITEMHEIGHT = &H1A1

Private Sub Form_Load()

List1.AddItem "China"
List1.AddItem "America"
List1.AddItem "Japan"
List1.AddItem "Soccer"
List1.AddItem "Tennis"
List1.AddItem "Basketball"

item_height = Screen.TwipsPerPixelX * _
SendMessage(List1.hwnd, LB_GETITEMHEIGHT, 0, vbNullString)

End Sub

'从list1拖到Form上就删掉
Public Sub Form_DragDrop(Source As Control, X As Single, Y As Single)

If Not (Source Is List1) Then Exit Sub
If List1.ListIndex >= 0 Then List1.RemoveItem List1.ListIndex

End Sub

'从list1拖到list1上
Private Sub List1_DragDrop(Source As Control, X As Single, Y As Single)

Dim newpos As Integer
If Not (Source Is List1) Then Exit Sub
newpos = Y / item_height

If newpos > List1.ListCount Then
List1.AddItem List1.List(List1.ListIndex)
Else
List1.AddItem List1.List(List1.ListIndex), newpos
End If

If List1.ListIndex >= 0 Then List1.RemoveItem List1.ListIndex

End Sub

'鼠标按下就开始拖
Private Sub List1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)

List1.Drag

End Sub
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息