现在有这样一个需求,拖拽UserControl中的一个Rectangle做的标题栏,然后新建一个Window把UserControl中的内容填充到新的窗口中去。Window.Show()不会把窗口创建的理想的位置。就需要将Window Show到桌面的指定位置。
首先获取鼠标相对于Rectangle的位置。
private Rectangle _rectTitle;
private Point _pointInRectangle;
private void RectTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
_pointInRectangle = e.GetPosition(_rectTitle);
}
然后获取鼠标相对于桌面的绝对位置。
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
//Copy from http://blog.csdn.net/withdreams/article/details/7497583
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetCursorPos(out POINT pt);
计算的时候需要用到英寸跟像素的单位转换。
using (Drawing.Graphics g = Drawing.Graphics.FromHdc(dc))
{
xDpi = g.DpiX;
yDpi = g.DpiY;
}
//Copy from http://codego.net/28224/
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
Single xDpi, yDpi;
IntPtr dc = GetDC(IntPtr.Zero);
最后计算新窗口需要Show的相对于桌面的绝对位置。
POINT p = new POINT();
if (GetCursorPos(out p))//API方法
{
_winFloat.Top = (p.Y - 10) / yDpi * 96 - _pointInRectangle.Y;//window有边框,需要往上偏移10像素。
_winFloat.Left = (p.X - 10) / xDpi * 96 - _pointInRectangle.X;//window有边框,需要往左偏移10像素。
}
注意Window.Top和Window.Left的单位是1/96英寸。而GetCursorPos获取的单位是像素,需要根据屏幕的DPI转换为英寸;貌似System.Windows.Point的单位也是1/96英寸。
上边的方法是可以实现将Window显示到桌面的指定位置的。