VB.NET中的ListBox右键选中Item的方法

最近需要处理一个关于如何在ListBox中右键选中Item时弹出菜单的问题,上网搜索了一下,居然发现有不少人问这个问题,却没找到正确的答案(也许是我的搜索方法不对头),很多讲的只是ListView,相距答案甚远。无奈之下,只好放下偷懒的心,自己动手。

其实,关键只是在于如何得到右键点击ListBox时的坐标,然后根据坐标判断是否选中了某一项,得到Index而已。找了一下MSDN,终于找到了IndexFromPoint这个函数,解决方法呼之欲出了。于是,生成了ListBox的MouseDown消息处理函数(具体方法不用细说了吧?),然后使用这个函数得到选中Item的Index,进行后续弹出菜单的处理,具体见下面示例:

Private Sub ListBoxUser_MouseDown(ByVal sender As System.Object,ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBoxUser.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
Dim sPoint As Point = New Point(e.X,e.Y)
Dim sIndex As Integer = ListBoxUser.IndexFromPoint(sPoint.X,sPoint.Y)
If sIndex <> -1 Then
ListBoxUser.SelectedIndex = sIndex
ListBoxUser.ContextMenuStrip = ContextMenuListBox
Else
ListBoxUser.ContextMenuStrip = Nothing
End If

Else
ListBoxUser.ContextMenuStrip = Nothing
End If
End Sub

上面示例中,ListBoxUser是我的一个ListBox实例,ContextMenuListBox是我的一个菜单示例。是不是很简单?

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...