6

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.

Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
gberg927
  • 1,636
  • 9
  • 38
  • 51

2 Answers2

11

Make sure you wire the event up (and the ListBox is enabled):

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).

LarsTech
  • 80,625
  • 14
  • 153
  • 225
2

Console.WriteLine() method wont display anything on GUI. Use 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.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186