using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; namespace DTS.Common.Utils { public class MouseUtilities { [StructLayout(LayoutKind.Sequential)] private struct Win32Point { public int X; public int Y; }; [DllImport("user32.dll")] private static extern bool GetCursorPos(ref Win32Point pt); [DllImport("user32.dll")] private static extern bool GetPhysicalCursorPos(ref Win32Point pt); [DllImport("user32.dll")] private static extern bool ScreenToClient(IntPtr hwnd, ref Win32Point pt); public static Point GetMousePosition(Visual relativeTo) { var mouse = new Win32Point(); GetCursorPos(ref mouse); var presentationSource = (System.Windows.Interop.HwndSource)PresentationSource.FromVisual(relativeTo); var factor = 2D - presentationSource.CompositionTarget.TransformToDevice.M22; ScreenToClient(presentationSource.Handle, ref mouse); var transform = relativeTo.TransformToAncestor(presentationSource.RootVisual); var offset = transform.Transform(new Point(0, 0)); if (factor > 0) { offset.Y = offset.Y + offset.Y * (presentationSource.CompositionTarget.TransformToDevice.M22 - 1); } return new Point(mouse.X - offset.X, mouse.Y - offset.Y); } } }