を使用するときに発生した問題を説明するために、小さなサンプルアプリケーションを作成しましたGetWindowRect
。Fooボタンをクリックすると、Left
によって返される値がGetWindowRect
とは異なることが示されWindow.Left
ます。
からの戻り値Window.Left
は相対的なもののようですが、何がわかりません。また、すべてのマシンでこれを再現できないことも不思議です。自宅のラップトップでは、追加のモニターの有無にかかわらず、この問題を再現できます。仕事用のPCでは問題は発生しません。どちらのシステムもWindows7を実行しています
これらの値が異なるのはなぜですか?これを修正するにはどうすればよいですか?
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>