1

を使用するときに発生した問題を説明するために、小さなサンプルアプリケーションを作成しました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>
4

1 に答える 1

5

違いを定量化しませんでした。いくつかの説明がありますが、明らかな不一致が1つあります。WindowsとWPFは異なる単位を使用します。GetWindowRect()はピクセル単位でウィンドウ位置を返し、Window.Leftは1/96インチ単位で位置を返します。ビデオアダプタが1インチあたり96ドットで実行されていない場合、これらは一致しません。96 dpiは従来の設定であり、新しいバージョンのWindowsでは非常に簡単に変更できます。WPFを使用すると、dpi設定を取得するのが少し難しくなります。コードについては、このブログ投稿を確認してください。

于 2013-03-09T19:43:42.237 に答える