0
我創建了一個小的示例應用程序來說明我在使用GetWindowRect
時遇到的問題。當我點擊Foo按鈕時,它顯示GetWindowRect
返回的Left
值不同於Window.Left
。GetWindowRect與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>
很好的解決了它,我不得不調用矩陣上的Invert,因爲我想從rct轉換爲wpf單位 – 2013-03-10 00:10:07