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



我正在制作一个"滴管";该工具可以让您在屏幕上的任何位置选择/查看鼠标光标下的颜色。我想在一个窗口上显示颜色信息,并让WPF窗口跟随光标移动。

颜色部分很好。实际上,我遇到的最大麻烦就是让窗口跟随光标。鼠标数据完全不正确。

Winforms中的相同代码可以完美地工作。

我已经尝试将app.manifest添加到两者中,以使每个项目DPI都知道。这似乎对WPF项目没有任何影响。

使用.NET 5和C#。目前在4k显示器上测试的比例为150%。

这是我的代码:

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;
}
}
}

检查此线程:
如何配置应用程序以在具有高DPI设置(例如150%(的机器上正确运行?

如果您选择手动检查缩放因子,您可以查询显示转换矩阵:

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

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

如果你正在进行多显示器设置,请小心,检查你得到的是哪个屏幕的缩放因子。

这里还有另一个可以帮助您的线程:
C#-如何在多个监视器上下文中获得真实的屏幕分辨率?

最新更新