views:

1410

answers:

2

Hi all,

I have a .NET 2.0 Windows Forms application. On this app there is a Form control with a Menu bar and a status bar. Also there's a ListView on this form.

If I add a context menu to this form, the context menu will open when the user right clicks any part of the form, including the menu bar and the status bar.

1) How can I prevent the context menu from opening when the click happened on the menu bar / status bar? I want it to open only when clicking the "gray area" of the form.

2) If the click happened above a control on this form (for example, on the ListView), how can I identify this? I'd like to know if the user right clicked above the gray area or above the ListView, so I can enable/disable some menu items based on this.

Thanks!

+1  A: 

I found the answer:

Point clientPos = this.PointToClient(Form.MousePosition);
Control control = this.GetChildAtPoint(clientPos);

This should give the underlying control that was clicked on the Form, or null if the click was on the gray area. So we just need to test for the type of the control on the Opening event of the context menu. If it's MenuStrip, ToolStrip or StatusStrip, do e.Cancel = true;.

+2  A: 

After you've placed your Statusbar at the bottom and MenuStrip at the top,

  1. Set ContextMenuStrip on your form to None
  2. Place a standard Panel in the middle (between MenuStrip and StatusStrip) with the Dock property set to Fill.
  3. Set the ContextMenuStrip property on your Panel (instead of on the form).

And place the ListView and all other controls that should go into the form in the Panel

Eg

~~~~~~~~~~~~~

menustrip

~~~~~~~~~~~~~

Panel. Dock=Fill. ContextMenuStrip=yourContextMenu.

~~~~~~~~~~~~~

StatusStrip

~~~~~~~~~~~~~

Andreas H.R. Nilsson