简体   繁体   English

WinForms ListBox右键单击

[英]WinForms ListBox Right-Click

I am trying to add a context menu to a listbox when you right click an item. 我正在尝试在右键单击项目时将上下文菜单添加到列表框中。

I am not even sure if the right click function with working properly. 我甚至不确定右键单击功能是否正常工作。

Here is the code: 这是代码:

private void lstSource_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        Console.WriteLine("Right Click");
    }
}

Nothing prints to the console. 没有任何东西打印到控制台。 Am I missing something? 我错过了什么吗?

Thanks. 谢谢。

Make sure you wire the event up (and the ListBox is enabled): 确保将事件连接起来(并且启用了ListBox):

private void Form1_Load(object sender, EventArgs e)
{
  listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);
}

void listBox1_MouseDown(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Right)
  {
    MessageBox.Show("Right Click");
  }
}

You can also have the designer wire up the event for you by selecting the ListBox and double-clicking on the MouseDown event in the Properties window (click on the lightning bolt). 您还可以让设计人员通过选择ListBox并在“属性”窗口中双击MouseDown事件(单击闪电)为您连接事件。

Console.WriteLine() method wont display anything on GUI. Console.WriteLine()方法不会在GUI上显示任何内容。 Use MessageBox.Show("Right Click"); 使用MessageBox.Show("Right Click");

private void lstSource_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        MessageBox.Show("Right Click");
    }
}

EDIT: Be sure that the handler is attached with MouseDown event or not. 编辑:确保处理程序附加了MouseDown事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM