事件“按下按钮时”

本文关键字:按下按钮时 按钮 事件 | 更新日期: 2023-09-27 17:55:53

我在WPF C#中为网格制作了事件。

鼠标移动事件。

我想在按下鼠标左键时触发鼠标移动事件,即使鼠标不在网格甚至主窗口之外,也要保持事件。

按下按钮时将网格的鼠标移动事件保留在整个屏幕上,直到释放按钮。

考虑这是网格的鼠标移动事件方法

    private void Grid_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed) // Only When Left button is Pressed.
        {
            // Perform operations And Keep it Until mouse Button is Released.
        }
    }

目标是当用户按住左按钮时旋转 3D 模型,并在他移动鼠标时旋转模型,直到按钮释放。

这是为了使用户更容易使用程序和轮换。特别是执行长旋转会导致鼠标脱离网格。

我尝试使用while但它失败了,你知道它是因为单线程。

因此,我的想法是,当在原始网格内按下按钮时,以某种方式在整个屏幕上扩展一个新的网格,并将其保留直到发布。

当然,虚拟网格女巫是隐藏的。

事件“按下按钮时”

您要做的是处理事件流。据我了解,您的流程应该如下:

  1. 按下鼠标左键
  2. 鼠标移动1(旋转模型)
  3. 鼠标移动2(旋转模型)

    N. 鼠标左上(停止旋转)

有一个有趣的概念叫做响应式编程。http://rxwiki.wikidot.com/101samples

有一个用于 C# 的库(反应式扩展)

您的代码可能如下所示:

// create event streams for mouse down/up/move using reflection
var mouseDown = from evt in Observable.FromEvent<MouseButtonEventArgs>(image, "MouseDown")
                select evt.EventArgs.GetPosition(this);
var mouseUp = from evt in Observable.FromEvent<MouseButtonEventArgs>(image, "MouseUp")
              select evt.EventArgs.GetPosition(this);
var mouseMove = from evt in Observable.FromEvent<MouseEventArgs>(image, "MouseMove")
                select evt.EventArgs.GetPosition(this);
// between mouse down and mouse up events
// keep taking pairs of mouse move events and return the change in X, Y positions
// from one mouse move event to the next as a new stream
var q = from start in mouseDown
        from pos in mouseMove.StartWith(start).TakeUntil(mouseUp)
                     .Let(mm => mm.Zip(mm.Skip(1), (prev, cur) =>
                          new { X = cur.X - prev.X, Y = cur.Y - prev.Y }))
        select pos;
// subscribe to the stream of position changes and modify the Canvas.Left and Canvas.Top
// property of the image to achieve drag and drop effect!
q.ObserveOnDispatcher().Subscribe(value =>
      {
          //rotate your model here. The new mouse coordinates
          //are stored in value object
          RotateModel(value.X, value.Y);
      });

实际上,构建鼠标事件流是使用 RX 的一个非常经典的示例。

http://theburningmonk.com/2010/02/linq-over-events-playing-with-the-rx-framework/

您可以在 Windows 构造函数中订阅此事件流,这样您就不依赖于网格,也不必绘制假网格!

一些不错的链接可以开始

  1. Rx框架示例
  2. Rx. 简介