【问题标题】:Right click on ListBox open ToolStripMenu but doesn't select any item右键单击 ListBox 打开 ToolStripMenu 但未选择任何项目
【发布时间】:2016-10-16 15:01:43
【问题描述】:

我有一个包含完整路径的ListBox 和一个ToolStripMenu 来选择打开文件或在文件夹中显示文件。

问题是:我需要在右键单击之前左键单击ListBoxItem 以选择我需要在文件夹中显示的文件。
如果我不这样做,我会得到NullReferenceException,因为没有选择任何项目。

我怎样才能选择右键单击的项目?

这是我的代码:

Private Sub ShowInFolderToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowInFolderToolStripMenuItem.Click
    Try
        If DirectCast(DirectCast(sender, ToolStripMenuItem).GetCurrentParent,  _
            ContextMenuStrip).SourceControl.GetType Is GetType(ListBox) Then

            Shell("explorer /select, " & DirectCast(DirectCast(DirectCast(sender,  _
                  ToolStripMenuItem).GetCurrentParent, ContextMenuStrip).SourceControl,  _
                  ListBox).SelectedItem.ToString, AppWinStyle.NormalFocus)
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

只是另一个问题...为什么下面的代码不起作用但没有给出错误并显示文件夹?

Process.Start("explorer.exe", "/select" & DirectCast(DirectCast(DirectCast(sender,  _
    ToolStripMenuItem).GetCurrentParent, ContextMenuStrip).SourceControl,  _
    ListBox).SelectedItem.ToString)

【问题讨论】:

  • 你可以在开始时检查是否有选中的项目
  • @Plutonix 是的,我知道这一点。但是可以选择第一项并右键单击第三项,因此可能会显示错误的文件。
  • @Plutonix 我解决了,但我仍然愿意接受更好的解决方案;)

标签: vb.net select listbox right-click


【解决方案1】:

解决了添加 MouseDown 事件:

Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
    Try
        DirectCast(sender, ListBox).SelectedIndex = DirectCast(sender, ListBox).IndexFromPoint(e.X, e.Y)
    Catch ex As Exception
    End Try
End Sub

【讨论】:

    猜你喜欢
    • 2014-01-10
    • 1970-01-01
    • 2022-01-09
    • 2013-11-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    相关资源
    最近更新 更多