You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止右键选中ListView项,仅保留左键选择功能?

解决方案:让ListView仅响应左键选中,右键仅触发上下文菜单

要实现左键负责选中项并加载图片,右键仅触发上下文菜单且不选中项,可通过以下步骤实现:

1. 拦截右键导致的选中操作

处理ListView的BeforeSelect事件,当检测到右键点击时,直接取消默认的选择行为:

Private Sub ImagesListViewBx_BeforeSelect(sender As Object, e As ListViewCancelEventArgs) Handles ImagesListViewBx.BeforeSelect
    ' 若当前是右键点击,取消选择操作
    If Control.MouseButtons = MouseButtons.Right Then
        e.Cancel = True
    End If
End Sub

2. 右键点击时手动触发上下文菜单

处理ListView的MouseDown事件,当右键点击到具体项时,定位到点击位置显示上下文菜单:

Private Sub ImagesListViewBx_MouseDown(sender As Object, e As MouseEventArgs) Handles ImagesListViewBx.MouseDown
    If e.Button = MouseButtons.Right Then
        ' 获取右键点击的ListView项
        Dim hitTestResult As ListViewHitTestInfo = ImagesListViewBx.HitTest(e.X, e.Y)
        If hitTestResult.Item IsNot Nothing Then
            ' 替换为你实际的ContextMenuStrip名称
            ContextMenuStrip1.Show(ImagesListViewBx, e.Location)
            
            ' 可选:如果需要在上下文菜单中操作当前右键点击的项,可将其存入变量
            ' 例如:currentRightClickedItem = hitTestResult.Item
        End If
    End If
End Sub

3. 保留原有左键选中加载逻辑

你现有的LoadSelectedImageFromList和ItemSelectionChanged事件代码无需修改——因为右键点击已被拦截,不会触发项选择变化,自然不会执行图片加载逻辑。

为什么之前的尝试没成功?

ListView默认会在任何点击(包括右键)时触发选中行为,仅通过鼠标按下/抬起事件判断按键,无法直接拦截控件内置的选中逻辑。而BeforeSelect事件是控件提供的选择操作拦截入口,能直接阻止右键导致的选中行为。

内容的提问来源于stack exchange,提问作者Mike Couples

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 10:55:15