WPF布局(3)坐标(转)

在动态定位布局时,经常需要获取控件或鼠标的相对位置,WPF提供了这样的函数可以我们使用。

1、获取元素相对于父控件的位置
使用Vector VisualTreeHelper.GetOffset(Visual visual)方法,返回visual在其父控件中的偏移量,然后你再将返回值的Vector对象转换成Point对象

2、获取元素相对于祖宗控件或子孙控件的位置
使用元素的 GeneralTransform TransformToAncetor(Visual ancetor)方法与GeneralTransform TransformToDescendent(Visual descendent),其返回元素相对于祖宗或子孙的GeneralTransform ,然后再使用Transform(new Point(0,0))方法得到的thePoint对象即可。

3、获取任意两个元素见的相对位置
如果元素是Visual,可以使用元素的GeneralTransform TransformToVisual(Visual visual)方法。

如果元素是UIElement,可以使用元素的TranslatePoint(Point pt, UIElement relativeTo)方法来得到元素上的pt点相对于relativeTo时的值,将pt为(0,0)那么就可以得到元素上(0,0)点的相对位置

4、获取鼠标相对于界面元素的位置

使用Mouse.GetPosition(IInputElement relativeTo)或MouseEventArgs.GetPosition(IInputElement relativeTo)来获取鼠标相对于某一界面元素的相对位置

5、获取鼠标相对于整个屏幕的位置

第一种:采用System.Windows.Forms.Control类中的静态属性System.Windows.Forms.Control.MousePosition,需要因用这个命名空间。

第二种:采用API函数:

在VB的文档中可以找到一个API:Declare Function GetCursorPos Lib "user32" Alias "GetCursorPos" (lpPoint As POINTAPI) As Long,我们可以在C#中使用它,代码如下:

以下是引用片段:
  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.Runtime.InteropServices;
  
  namespace Samples
  {
   class Win32
   {
   [StructLayout(LayoutKind.Sequential)]
   public struct POINT
   {
   public int X;
   public int Y;
  
   public POINT(int x, int y)
   {
   this.X = x;
   this.Y = y;
   }
   }
  
  
  
   [DllImport("user32.dll", CharSet = CharSet.Auto)]
   public static extern bool GetCursorPos(out POINT pt);
  
   }
  }

参考:http://www.cnblogs.com/zhouyinhui/archive/2007/08/27/871523.html

http://www.builder.com.cn/2007/1119/642354.shtml

原文地址:https://www.cnblogs.com/jyz/p/1286931.html