MouseUtilities.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Windows;
  4. using System.Windows.Media;
  5. namespace WPF.JoshSmith.Controls.Utilities
  6. {
  7. /// <summary>
  8. /// Provides access to the mouse location by calling unmanaged code.
  9. /// </summary>
  10. /// <remarks>
  11. /// This class was written by Dan Crevier (Microsoft).
  12. /// http://blogs.msdn.com/llobo/archive/2006/09/06/Scrolling-Scrollviewer-on-Mouse-Drag-at-the-boundaries.aspx
  13. /// </remarks>
  14. public class MouseUtilities
  15. {
  16. [StructLayout(LayoutKind.Sequential)]
  17. private struct Win32Point
  18. {
  19. public Int32 X;
  20. public Int32 Y;
  21. };
  22. [DllImport("user32.dll")]
  23. private static extern bool GetCursorPos(ref Win32Point pt);
  24. [DllImport("user32.dll")]
  25. private static extern bool ScreenToClient(IntPtr hwnd, ref Win32Point pt);
  26. /// <summary>
  27. /// Returns the mouse cursor location. This method is necessary during
  28. /// a drag-drop operation because the WPF mechanisms for retrieving the
  29. /// cursor coordinates are unreliable.
  30. /// </summary>
  31. /// <param name="relativeTo">The Visual to which the mouse coordinates will be relative.</param>
  32. public static Point GetMousePosition(Visual relativeTo)
  33. {
  34. Win32Point mouse = new Win32Point();
  35. GetCursorPos(ref mouse);
  36. // Using PointFromScreen instead of Dan Crevier's code (commented out below)
  37. // is a bug fix created by William J. Roberts. Read his comments about the fix
  38. // here: http://www.codeproject.com/useritems/ListViewDragDropManager.asp?msg=1911611#xx1911611xx
  39. return relativeTo.PointFromScreen(new Point((double)mouse.X, (double)mouse.Y));
  40. #region Commented Out
  41. //System.Windows.Interop.HwndSource presentationSource =
  42. // (System.Windows.Interop.HwndSource)PresentationSource.FromVisual( relativeTo );
  43. //ScreenToClient( presentationSource.Handle, ref mouse );
  44. //GeneralTransform transform = relativeTo.TransformToAncestor( presentationSource.RootVisual );
  45. //Point offset = transform.Transform( new Point( 0, 0 ) );
  46. //return new Point( mouse.X - offset.X, mouse.Y - offset.Y );
  47. #endregion // Commented Out
  48. }
  49. }
  50. }