2013-03-09 13 views
0

我創建了一個小的示例應用程序來說明我在使用GetWindowRect時遇到的問題。當我點擊Foo按鈕時,它顯示GetWindowRect返回的Left值不同於Window.LeftGetWindowRect與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> 

回答

4

你沒有量化的不同,有幾種解釋,但有一個明顯的不匹配。 Windows和WPF使用不同的單位。 GetWindowRect()以像素爲單位返回窗口位置,Window.Left返回1/96英寸的位置。當視頻適配器未以每英寸96點運行時,它們不匹配。 96 dpi是傳統設置,在更高版本的Windows上更改很容易。 WPF使得獲取dpi設置有點困難,請檢查代碼this blog post

+0

很好的解決了它,我不得不調用矩陣上的Invert,因爲我想從rct轉換爲wpf單位 – 2013-03-10 00:10:07