Search code examples
c#.netwinformscontextmenustrip

Any way to get the width of a Context Menu before it is displayed?


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.


Solution

  • 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);
    }