GetWindowRect differs from Window.Left



我创建了一个小的示例应用程序来说明我在使用GetWindowRect时遇到的一个问题。当我点击Foo按钮时,显示GetWindowRect返回的Left值与Window.Left不同。

似乎从Window.Left返回的值是相对的,但我不确定是什么。同样奇怪的是,我不能在每台机器上复制这个,在我的家用笔记本电脑上,有或没有额外的显示器,我可以复制这个问题,在我的工作电脑上,这个问题没有发生。两个系统都运行Windows 7

为什么这些值不同,我如何解决这个问题?

MainWindow.xaml.cs

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace PositionTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private IntPtr thisHandle;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            thisHandle = new WindowInteropHelper(this).Handle;
        }
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
        private void ReportLocation(object sender, RoutedEventArgs e)
        {
            var rct = new RECT();
            GetWindowRect(thisHandle, ref rct);
            MessageBox.Show(Left.ToString() + " " + rct.Left);
        }
    }
}

MainWindow.xaml

<Window x:Class="PositionTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Loaded="Window_Loaded" WindowStartupLocation="Manual" Height="150" Width="150" WindowStyle="SingleBorderWindow" ResizeMode="NoResize" BorderThickness="0,1,0,0" >
    <Grid>
        <Button Content="Foo" HorizontalAlignment="Left" Margin="35,50,0,0" VerticalAlignment="Top" Width="75" Click="ReportLocation"/>
    </Grid>
</Window>

您没有量化差异,有几种解释,但有一个明显的不匹配。Windows和WPF使用不同的单位。gettwindowrect()返回以像素为单位的窗口位置。Left返回1/96英寸的位置。当视频适配器不是以每英寸96点的速度运行时,它们将不匹配。96 dpi是旧设置,在以后的Windows版本中很容易更改。WPF使得获取dpi设置有点困难,查看这篇博客文章获取代码。

最新更新