【发布时间】:2021-09-04 17:24:33
【问题描述】:
我正在制作一个“吸管”工具,可让您在鼠标光标下选择/查看屏幕上任何位置的颜色。我想在窗口上显示颜色信息,并让 WPF 窗口在您移动时跟随光标。
颜色部分很好。实际上,我在让窗口跟随光标移动时遇到了最大的麻烦。鼠标数据完全不正确。
Winforms 中的相同代码可以完美运行。
我尝试将 app.manifests 添加到两者中,以使每个项目都可以识别 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;
}
}
}
【问题讨论】:
-
请注意,
new TimeSpan(15)创建的计时器间隔为 15 个“滴答”,即 1.5 微秒。当然不是你想要的。 -
您是否尝试处理
WM_MOUSEMOVE事件而不是使用计时器来轮询光标位置?