How to get the location of ContextMenuStrip?

此生再无相见时 提交于 2021-02-10 17:47:03

问题


I have attached a ContextMenuStrip to a Chart control.

How can I get the chart control coordinates where the top left of the ContextMenuStrip is located when it appears?

This is the point I want to translate to chart coordinates:


回答1:


Using the answer to query the current mouse cursor position in the Opening event of the ContextMenuStrip can deliver the wrong position when opening the strip is delayed a bit.

If you need the really clicked position, remove the ContextMenuStrip from the property of the control and manually open the context menu in the MouseDown event of the control. There you have access to the actual click position.

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        var relativeClickedPosition = e.Location;
        var screenClickedPosition = (sender as Control).PointToScreen(relativeClickedPosition);
        contextMenuStrip1.Show(screenClickedPosition);
    }
}

relativeClickedPosition is the cursor position relative to the control.




回答2:


I added a ContextMenuStrip_Opening event to the ContextMenuStrip. There I could save the menu popup location.

I did something like this:

menuPopupLocation = chart.PointToClient(System.Windows.Forms.Cursor.Position);

then I could use:

double dataX = chart.ChartAreas[0].AxisX.PixelPositionToValue(menuPopupLocation.X);
double dataY = chart.ChartAreas[0].AxisX.PixelPositionToValue(menuPopupLocation.Y);


来源:https://stackoverflow.com/questions/42178264/how-to-get-the-location-of-contextmenustrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!