3

I want to know the what the width of the context menu will be, just before being displayed, possibly in the myContextMenu.popup event handler or better yet, before myContextMenu.show().

The reason I want to know the width, is so that I can affect the location of where it will be painted. Specifically, in the circumstance where the data of a column is right justified, when the operator right clicks, I don't want the context menu to cover the data, which is typically, also to the right. If I have the width, I can move the context menu to the left by the amount of the width and the top-right corner of the context menu will be at the point of the cursor.

I really do not want to use the myContextMenu.DrawItem event to paint the context menu items unless that is absolutely the only way to accomplish this.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398

1 Answers1

3

ContextMenuStrip has Left, Top, Width and Height properties which you can use to find its location and size.

Also to change the location, you can use SetBounds method.

The suitable event to correct the location is Opened event.

Example

private void contextMenuStrip1_Opened(object sender, EventArgs e)
{
    contextMenuStrip1.SetBounds(contextMenuStrip1.Left - contextMenuStrip1.Width,
        contextMenuStrip1.Top, 0, 0, BoundsSpecified.Location);
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Thanks for this! It is no wonder I could not get anywhere with what I was doing...I have been handling the mouse click events on my form and simply building a `ContextMenu` with `MenuItems`, which did not give me any access to what you have shown. Now I have to learn how to build a `ContextMenuStrip'. Fun! Thanks again! – JimOfTheNorth Feb 01 '18 at 13:42
  • You can create the ContextMenuStrip simply by dropping it on your form from toolbox. Then to show it, you can use code or simply assign it to `ContextMenuStrip` of the control (then by right clicking on that control, it will be shown automatically). – Reza Aghaei Feb 01 '18 at 13:45
  • Neat, I'll try that. I'm trying to do most of my work in code, but I have a little sample project using the visual designer so that I can test out stuff like this and see how it works under the sheets. Thanks for the tip!! – JimOfTheNorth Feb 01 '18 at 13:53