Unable to detect right mouseclick in ComboBox

I have a ComboBox, which is a simple dropdown style. I wanted to open a new window when the user right-clicks on an item in the list, but I had problems with his right-click detection.

My code is:

private void cmbCardList_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right && cmbCardList.SelectedIndex != -1) { frmViewCard vc = new frmViewCard(); vc.updateCardDisplay(cmbCardList.SelectedItem); vc.Show(); } } 

If I change e.Button == MouseButtons.Left it all works just fine. Anyway, can I make it work, as I suppose?

+4
source share
3 answers

I am afraid that this will not be possible if you do not make a serious hack. This article will explain.

Quoted for you:

Individual controls

The following controls do not conform to standard mouse click event behaviors:

Button, CheckBox, ComboBox, and RadioButton Controls

  • Left click: click, MouseClick

  • Right click: no events with pressed buttons

  • Left double click: Click, MouseClick; Click, MouseClick

  • Double click the right mouse button: no click events raised

+6
source

As an epitaph to this question, you can do this work using normal .NET functions; you just need to go a little deeper into the event call stack. Instead of handling the MouseClick event, handle the MouseDown event. Lately, I had to do something similar, and I just redefined the OnMouseDown method instead of binding the handler. But the handler should work too. Here is the code:

  protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Right && !HandlingRightClick) { HandlingRightClick = true; if (!cmsRightClickMenu.Visible) cmsRightClickMenu.Show(this, e.Location); else cmsRightClickMenu.Hide(); } base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { HandlingRightClick = false; base.OnMouseUp(e); } private bool HandlingRightClick { get; set; } 

The HandlingRightClick property is to prevent many OnMouseDown logic triggers; the user interface will send several MouseDown messages, which may interfere with hiding the context menu. To prevent this, I execute the logic only once on the first MouseDown trigger (the logic is simple enough that I don't care if two calls happen, but you can), and then ignore any other MouseDown triggers until MouseUp happens. This is not ideal, but it will do what you need.

+5
source

You can use the ContextMenuStrip Opening event to handle a right-click event.

 var chk = new CheckBox(); chk.ContextMenuStrip = cmsNone; 

 private void cmsNone_Opening(object sender, CancelEventArgs e) { e.Cancel = true; var cms = (ContextMenuStrip)sender; var chk = cms.SourceControl; //do your stuff } 
0
source

All Articles