WinForms ListBox Right Click

I am trying to add a context menu to the list when I right-click on an item.

I'm not even sure if the right click function works correctly.

Here is the code:

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

Does not print anything on the console. Did I miss something?

Thanks.

+6
source share
2 answers

Make sure you hook 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 configure the conductor for the event by selecting the ListBox and double-clicking on the MouseDown event in the Properties window (click on the zipper).

+10
source

Console.WriteLine() method does not display anything in the GUI. Use MessageBox.Show("Right Click");

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

EDIT: Verify that the handler is associated with the MouseDown event or not.

+2
source

Source: https://habr.com/ru/post/897695/


All Articles