MouseUtil.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Windows;
  4. using System.Windows.Media;
  5. namespace GeekDesk.Util
  6. {
  7. class MouseUtil
  8. {
  9. [DllImport("user32.dll")]
  10. [return: MarshalAs(UnmanagedType.Bool)]
  11. internal static extern bool GetCursorPos(ref Win32Point pt);
  12. [StructLayout(LayoutKind.Sequential)]
  13. internal struct Win32Point
  14. {
  15. public Int32 X;
  16. public Int32 Y;
  17. };
  18. /// <summary>
  19. /// 获取鼠标坐标
  20. /// </summary>
  21. /// <returns></returns>
  22. public static Point GetMousePosition()
  23. {
  24. var w32Mouse = new Win32Point();
  25. GetCursorPos(ref w32Mouse);
  26. return new Point(w32Mouse.X, w32Mouse.Y);
  27. }
  28. public static Point GetMousePosition(Visual relativeTo)
  29. {
  30. Win32Point mouse = new Win32Point();
  31. GetCursorPos(ref mouse);
  32. // Using PointFromScreen instead of Dan Crevier's code (commented out below)
  33. // is a bug fix created by William J. Roberts. Read his comments about the fix
  34. // here: http://www.codeproject.com/useritems/ListViewDragDropManager.asp?msg=1911611#xx1911611xx
  35. return relativeTo.PointFromScreen(new Point((double)mouse.X, (double)mouse.Y));
  36. #region Commented Out
  37. //System.Windows.Interop.HwndSource presentationSource =
  38. // (System.Windows.Interop.HwndSource)PresentationSource.FromVisual( relativeTo );
  39. //ScreenToClient( presentationSource.Handle, ref mouse );
  40. //GeneralTransform transform = relativeTo.TransformToAncestor( presentationSource.RootVisual );
  41. //Point offset = transform.Transform( new Point( 0, 0 ) );
  42. //return new Point( mouse.X - offset.X, mouse.Y - offset.Y );
  43. #endregion // Commented Out
  44. }
  45. }
  46. }