WPF Snippet - Reliably Getting The Mouse Position

来源:互联网 发布:软件陷阱 编辑:程序博客网 时间:2024/05/18 13:12

The following quote is taken verbatim from the MSDN page onMouse.GetPosition:

During drag-and-drop operations, the position of the mouse cannot be reliably determined through GetPosition.This is because control of the mouse(possibly including capture)is held by the originating element of the draguntil the drop is completed,with much of the behavior controlledby underlying Win32 calls

 

The problem is more widespread than just drag-and-drop, though. It actually has to do with mouse capture (as the quote states) - and so anytime that an element is doing something funky with mouse capture, there is no guarantee that the position returned by Mouse.GetPositionwill be correct.

The issue also applies to theGetPositionfunction onMouseEventArgs, which available through all the standard mouse events. Even one of their suggested workarounds for the issue during drag-and-drop (using theGetPositionfunction onDragEventArgs) has the exact same problem. They really need to remove that workaround from their list - figuring that it didn't work either was another few hours of hair tearing pain.

Ok, but enough complaining about what doesn't work - time to figure out what does. The second workaround suggested on MSDN actually does work, which is P/Invoking the native methodGetCursorPos. This is actually pretty easy to do, assuming that you know how to pull in native methods. So let's take a look at the code:

 

using System;using System.Runtime.InteropServices;using System.Windows;using System.Windows.Media;namespace CorrectCursorPos{  public static class MouseUtilities  {    public static Point CorrectGetPosition(Visual relativeTo)    {      Win32Point w32Mouse = new Win32Point();      GetCursorPos(ref w32Mouse);      return relativeTo.PointFromScreen(new Point(w32Mouse.X, w32Mouse.Y));    }    [StructLayout(LayoutKind.Sequential)]    internal struct Win32Point    {      public Int32 X;      public Int32 Y;    };    [DllImport("user32.dll")]    [return: MarshalAs(UnmanagedType.Bool)]    internal static extern bool GetCursorPos(ref Win32Point pt);  }}


So what we want here is a method that works the same way as the WPF version, except that it is correct all the time. This means a method (in this caseCorrectGetPosition), that takes in a Visual as the argument to get the mouse position relative to that Visual. What does this method do? Well, first, we have to create our own special point struct, which I namedWin32Point here. This is because outside of WPF, mouse positing is dealt with in terms of pixels, and so the coordinates are integers (not doubles, like the WPF point struct). Then we pass in a pointer to the struct to the native methodGetCursorPos. This will fill the stuct with the current cursor coordinates. The code used to pull in this native method shouldn't look to surprising - while it is not common, we have used it before here in some SOTC tutorials (namelyNamed Pipes).

Once we have the raw cursor position, we need to convert it to something that makes sense in the WPF world. This is where the handyPointFromScreenmethod is useful. This method converts a screen position into WPF coordinates relative to the visual. And that is it! The value returned byPointFromScreen is the correct cursor position.

One important thing to note about using the results of GetCursorPos in WPF. You should never use those values directly, because the values are in system pixel coordinates, which are meaningless to WPF (since WPF uses DIU, or Device Independent Units, instead of pixels). Using them directly will cause a subtle problem that you won't notice until you run your application on a system that has a DPI setting other than 96 (this is because 1 pixel = 1 DIU when working on a 96 DPI screen). Before using the result, you should always pass it through something likePointFromScreen (WPF does the translation between screen pixels and DIUs deep inside that method).

Now really, was that that hard? As you might have been able to tell from my tone at the start of the tutorial, this WPF issue really irked me. But oh well, hopefully they fix it in the next version of WPF.

原创粉丝点击