为什么 WPF 中的鼠标位置不正确而不是缩放桌面上的 Winforms?

Why is mouse position incorrect in WPF and not Winforms on scaled desktops?

我正在制作一个“吸管”工具,可以让您 select/see 在屏幕上鼠标光标下的任何位置添加颜色。我想在 window 上显示颜色信息,并让 WPF window 在您移动光标时跟随光标移动。

颜色部分不错。我实际上最麻烦的是让 window 跟随光标。鼠标数据完​​全错误

Winforms 中的相同代码可以完美运行。

我尝试将 app.manifests 添加到两者以使每个项目都知道 DPI。这似乎对WPF项目没有影响。

使用 .NET 5 和 C#。目前在缩放 150% 的 4k 显示器上进行测试。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.Windows.Threading;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetCursorPos(out POINT lpPoint);

        DispatcherTimer timer = new DispatcherTimer();

        public struct POINT
        {
            public int X;
            public int Y;


            public static implicit operator Point(POINT point)
            {
                return new Point(point.X, point.Y);
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            timer.Interval = new TimeSpan(15);
            timer.Start();
            timer.Tick += Timer_Tick;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            POINT p;
            GetCursorPos(out p);
            this.Left = p.X;
            this.Top = p.Y;
        }
    }
}

检查此线程:
How to configure an app to run correctly on a machine with a high DPI setting (e.g. 150%)?

如果您选择手动检查比例因子,您可以查询显示变换矩阵:

Matrix? matrix = PresentationSource.FromVisual(visual)?.CompositionTarget?.TransformToDevice;

visual 是 System.Windows.Media.Visual 对象 - 您的主要 window。 属性 M11M22 包含水平和垂直比例因子(通常是相同的值)。使用这些比例因子来计算实际的鼠标位置。

如果您正在处理多显示器设置,请小心,检查您得到的是哪个屏幕的缩放系数。

这是另一个可能对您有帮助的话题:
C# - How to get real screen resolution in multiple monitors context?