Get cursor position with respect to the control - C#

夙愿已清 提交于 2019-11-27 22:42:48

You can directly use the Location property of the MouseEventArgs argument passed to your event-handler.

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    Text = e.Location.X + ":" + e.Location.Y;      
} 

Use Control.PointToClient to convert a point from screen-relative coords to control-relative coords. If you need to go the other way, use PointToScreen.

The following will give you mouse coordinates relative to your control. For example, this results in (0,0) if mouse is over top left corner of the control:

var coordinates = yourControl.PointToClient(Cursor.Position);
Chris

One can use following methods for getting the relative from absolute and absolute from relative coordinates:

Point Control.PointToClient(Point point);

Point Control.PointToScreen(Point point);

Simply subtract from the cursor position the Left and Top coordinates of the control:

this.Text = Convert.ToString(
    Cursor.Position.X - this.Left + ":" +
    Cursor.Position.Y - this.Top);

I use MouseLocation and PointToClient to check. And then use it in a timer!

bool IsMouseHover(Control c, Control container)
        {
            Point p = Control.MousePosition;
            Point p1 = c.PointToClient(p);
            Point p2 = container.PointToClient(p);
            if (c.DisplayRectangle.Contains(p1) && container.DisplayRectangle.Contains(p2))
            {
                return true;
            }
            return false;
        }

Cursor.Position return Point on Screen, but Control.PointToClient(Cursor.Position) returns point on control (e.g. control -> panel). In your case, you have e.Locate which return point on control.

Pichitron
private void lienzo_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
    Point coordenadas = new Point();
    coordenadas = Mouse.GetPosition(lienzo);

    string msg = "Coordenadas mouse :" + coordenadas.X + "," + coordenadas.Y;
    MessageBoxResult resultado;
    string titulo = "Informacion";
    MessageBoxButton botones = MessageBoxButton.OK;
    MessageBoxImage icono = MessageBoxImage.Information;

    resultado = MessageBox.Show(msg, titulo, botones, icono);
}

Where "lienzo" is my canvas panel

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