Reputation: 7983
I have a custom Windows Forms Control to which I want to add a context menu. The custom control has an active selection that can be manipulated by keyboard or mouse. I set the custom control's ContextMenu
property to the context menu I wish to show. When the user right-clicks, the context menu appears right where it is expected.
However, when the user presses the Menu key (or equivalently, Shift-F10
) the context menu appears in the dead center of my control. I would like to be able to control the location of where the context menu appears depending on where the selection is in the control. How is this done? And does it also work for ContextMenuStrip
?
EDIT
I'm writing up the worked solution given the answer below. First, set the ContextMenu
property (or ContextMenusStrip
property, as appropriate). Then, override the OnKeyDown
method to intercept Shift-F10
, and do an explicit Show()
in that case.
this.ContextMenu = <my context menu>;
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyData == (Keys.Shift|Keys.F10))
{
ContextMenu.Show(this, new Point(<x and y coordinates as appropriate>));
e.Handled = true;
}
else
{
base.OnKeyDown(e);
}
}
This way, you don't have to muck with the logic that shows the context menu on right-click.
Upvotes: 0
Views: 1779
Reputation: 8792
The Show()
method of the ContextMenuStrip
allows you to provide a control on which it is shows as well as the location.
For instance in example below:
this.contextMenuStrip1.Show(button1, new Point(50, 50));
It will display the menu 50 pixels to the right and below the button1
. And when specifying only the location:
this.contextMenuStrip1.Show(new Point(50, 50));
The menu is displayed in the position relative to the main form.
Upvotes: 4