Sunday, May 18, 2008

Client coordinates and Screen coordinates

The .NET Framework can provide the mouse coordinates using the client coordinates system or the screen coordinates system. In some mouse-based scenarios we need exactly to know which coordinates system is used in order to use the correct offset.

Screen coordinates vs. Client coordinates

In a screen coordinates environment, the X coordinate will measure the distance between the mouse cursor and the left margin of the monitor's screen and the Y coordinate will measure the distance between the mouse cursor and the top margin of the monitor's screen.

In a client coordinates environment, the X coordinate will measure the distance between the mouse cursor and the left margin of the current user control and the Y coordinate will measure the distance between the mouse cursor and the top margin of the current user control.

The Control.DragDrop event

This event occurs when a drag-and-drop operation is completed and provides the coordinates where the dropping took place. We can access these coordinates thru the DragEventArgs parameter.

Unlike the other mouse-based events: MouseMove, MouseClick or MouseDown events which are using the client coordinates system, the DragDrop event provides the screen coordinates for the used pointing device.

In some scenarios we need to know the exact location the dropping occurred at. Let’s consider a charting application where the user can drag-and-drop the data he wants to visualize for both chart’s axes. Considering this, we need to know if the dropping occurred in the X axis region or in the Y axis region. In order to do this, we need to know the distances between the mouse location and the left and bottom margins of the current chart control. Because the Control.DragDrop event is using the screen coordinate system, a coordinate conversion is required.

How to convert

The .NET Framework provides two conversion methods for transforming the screen coordinates into client coordinates and back:
  • Control.PointToClient. Computes the location of the specified screen point into client coordinates.

    Point clientLocation = this.panel1.PointToClient(location);



  • Control.PointToScreen. Computes the location of the specified client point into screen coordinates.

    Point screenLocation = this.panel1.PointToScreen(location);

kick it on DotNetKicks.com

No comments: