WPF Snippet - Reliably Getting The Mouse Position

Skill

WPF Snippet - Reliably Getting The Mouse Position

Posted in:

If you've worked for a while in WPF doing any kind of complicated user interface, you may have noticed that while WPF has some great methods for getting the mouse position relative to an element, there is one serious problem - the returned position is sometimes wrong. Yeah, I know it is hard to believe, but it is true. When I first ran across the problem, I tore out my hair for the better part of a day trying to find what was wrong with my code - only to eventually figure out that this is a known issue with WPF.

This problem is actually even documented on the MSDN page about the standard WPF function to get mouse position. The following quote is taken verbatim from the MSDN page on Mouse.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 drag until the drop is completed, with much of the behavior controlled by 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.GetPosition will be correct.

The issue also applies to the GetPosition function on MouseEventArgs, which available through all the standard mouse events. Even one of their suggested workarounds for the issue during drag-and-drop (using the GetPosition function on DragEventArgs) 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 method GetCursorPos. 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 case CorrectGetPosition), 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 named Win32Point 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 method GetCursorPos. 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 (namely Named 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 handy PointFromScreen method is useful. This method converts a screen position into WPF coordinates relative to the visual. And that is it! The value returned by PointFromScreen 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 like PointFromScreen (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. If you have any questions on this stuff, or horror stories about it, please, leave them below.

RobertJ
03/29/2009 - 17:23

I'd use System.Windows.Forms.Control.MousePosition instead of the p/invoke.

reply

Ima Dirty Troll
11/12/2010 - 21:45

+1

As long as you've got it, use it. Sooner or later most of my WPF projects end up referring to System.Windows.Forms anyway.

reply

Alonzo
06/04/2009 - 06:44

Thank you so much! I wish I'd found this post sooner!!!!!

reply

Travis
01/13/2010 - 21:30

Nice! Thanks for that. Took all of a minute to go from working out there was an issue with drag drop to finding your solution!

reply

Peter
01/20/2010 - 07:50

The world of programming changes really fast and I'd like to see a date at the top of the article. Thanks.

reply

The Reddest
01/20/2010 - 09:39

I would too. We upgraded Drupal a while ago and somehow lost the template that controls that. We'll get it fixed soon.

reply

Yury
06/16/2010 - 23:18

Thanks a lot, worked like a charm right away. Glad I did research eventual issues before trying out anything.

reply

Mel
08/06/2010 - 14:11

Thanks a lot for sharing! This was exactly what I was looking for and solved my problem with getting the mouse position during Drag-Drop.

reply

Notre
09/21/2010 - 17:46

I'm having trouble trying to set (change) the cursor position during a drop operation. I tried to to use the System.Windows.Forms.Position setter and SetCursorPos both in the source's PreviewQueryContinueDrag handler and the target's PreviewDrop handler but neither affected the position of where the items were dropped. In the case of PreviewQueryContinueDrag, the mouse visually moved to the programmatic location after the items were dropped, even though the PreviewQueryContinueDrag handler was called before the item was dropped (and before PreviewDrop).

reply

Anonymous
08/18/2011 - 09:32

This works like a charm.
Thanks a lot.

reply

Anonymous
12/27/2011 - 04:33

this is an improved way:

public static class MouseUtils
    {
        //do not use while DoDragDrop is happening
        public static Point GetMouseAbsoluteScreenPosition(this UIElement visual)
        {
            return visual.PointToScreen(Mouse.GetPosition(visual));
        }//use like that: this.GetMouseAbsoluteScreenPosition();


        //use in conjunction with PreviewGiveFeedback to simulate MouseMove event
        public static Point GetMouseAbsoluteScreenPositionNative()
        {
            Win32Point point;
            if (!GetCursorPos(out point))
            {
                var e = Marshal.GetLastWin32Error();
                throw new Win32Exception(e);
            }

            return point;
        }

        //get mouse position , on drag & drop, Mouse.GetPosition Doesn't work when doing DragDrop.DoDragDrop()
        //http://www.switchonthecode.com/tutorials/wpf-snippet-reliably-getting-the-mouse-position

        //http://msdn.microsoft.com/en-us/library/windows/desktop/ms648390(v=vs.85).aspx
        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", EntryPoint = "GetCursorPos", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        private static extern bool GetCursorPos([Out] out Win32Point lpPoint);

        //http://msdn.microsoft.com/en-us/library/windows/desktop/dd162805(v=vs.85).aspx
        [StructLayout(LayoutKind.Sequential)]
        private struct Win32Point
        {
            public int x;//not readonly because of out parameter
            public int y;//not readonly because of out parameter

            public Win32Point(int x, int y)
            {
                this.x = x;
                this.y = y;
            }

            public override string ToString()
            {
                return (x + "," + y);
            }

            public static implicit operator Point(Win32Point p)
            {
                return new Point(p.x, p.y);
            }

            public static implicit operator Win32Point(Point p)
            {
                return new Win32Point((int)p.X, (int)p.Y);
            }
        }
    }

reply

Valeria
04/13/2012 - 02:44

Thank you!!!!!!!!!!!!!!!!!!! you solved me a big problem!!!!

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.