Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 464
gberg927 Avatar asked Sep 20 '11 15:09

gberg927


2 Answers

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

like image 187
LarsTech Avatar answered Sep 18 '22 12:09

LarsTech


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.

like image 42
KV Prajapati Avatar answered Sep 18 '22 12:09

KV Prajapati