c# - 使用 DrawingContext.DrawRectangle 绘制的矩形会阻塞鼠标

标签 c# wpf

下面的 WPF 程序会显示一个如下所示的窗口:

enter image description here

黑色方 block 外的鼠标移动会导致窗口标题随鼠标位置更新。当鼠标进入正方形时停止更新。

我希望 MouseMove 继续触发,即使鼠标在正方形上也是如此。有办法做到这一点吗?

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Wpf_Particle_Demo
{
    class DrawingVisualElement : FrameworkElement
    {
        public DrawingVisual visual;

        public DrawingVisualElement() { visual = new DrawingVisual(); }

        protected override int VisualChildrenCount { get { return 1; } }

        protected override Visual GetVisualChild(int index) { return visual; }
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var canvas = new Canvas();

            Content = canvas;

            var element = new DrawingVisualElement();

            canvas.Children.Add(element);

            CompositionTarget.Rendering += (s, e) =>
                {
                    using (var dc = element.visual.RenderOpen())
                        dc.DrawRectangle(Brushes.Black, null, new Rect(0, 0, 50, 50));
                };

            MouseMove += (s, e) => Title = e.GetPosition(canvas).ToString();
        }
    }
}

最佳答案

到目前为止,最简单的方法是使用窗口上的“隧道”事件 PreviewMouseDown。它首先被传送到窗口,然后在层次结构中向上移动。因此,窗口中还有哪些其他元素根本无关紧要。在代码中:

public partial class Window1 : Window {
    public Window1() {
        InitializeComponent();
        this.PreviewMouseMove += new MouseEventHandler(Window1_PreviewMouseMove);
    }
    void Window1_PreviewMouseMove(object sender, MouseEventArgs e) {
        this.Title = e.GetPosition(this).ToString();
    }
}

关于c# - 使用 DrawingContext.DrawRectangle 绘制的矩形会阻塞鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13326226/

相关文章:

c# - 解决方案中存在冲突的对象名称

WPF:工具栏是一个键盘陷阱

c# - 是否可以在 WPF 的 Control 本身中添加航空效果?

c# - 在 Click 事件中从 TextBox 中选择文本

C# - 在项目之间共享资源文件

WPF渲染卡住

c# - 如何在 C# 中调用外部 exe 时使 UI 响应?

wpf - 工具提示与弹出窗口(WPF控件)

c# - 任务和垃圾收集存在哪些问题?

c# - MS Graph API Drive 创建新文件夹