右键单击以选择ListBox中的项目

我正在尝试制作一个项目列表,您可以通过右键单击并启用上下文菜单来执行多项操作。 我已经完成了,没有任何问题。

但我想拥有它,以便当您右键单击某个项目而不是选择当前项目时,选择鼠标所在的项目。

我已经研究了这个和其他相关问题,并且我尝试使用indexFromPoint(我通过我的研究发现),但每当我右键单击某个项目时,它总是只清除所选项目而不显示上下文菜单,因为我设置它,以便它没有出现,如果没有选定的项目。

这是我目前使用的代码:

ListBox.SelectedIndex = ListBox.IndexFromPoint(Cursor.Position.X, Cursor.Position.Y); 

处理ListBox.MouseDown并选择其中的项目。 像这样:

 private void listBox1_MouseDown(object sender, MouseEventArgs e) { listBox1.SelectedIndex = listBox1.IndexFromPoint(eX, eY); } 

这一个正在……

 this.ListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.List_RightClick); private void List_RightClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { int index = this.listBox.IndexFromPoint(e.Location); if (index != ListBox.NoMatches) { listBox.Items[index]; } } } 

也可以通过在整个列表框上设置MouseRightButtonUp事件来获得相同的行为:

 private void AccountItemsT33_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e) { // If have selected an item via left click, then do a right click, need to disable that initial selection AccountItemsT33.SelectedIndex = -1; VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), (sender as ListBox)).OfType().First().IsSelected = true; }