c# - 事件 "While Button is Pressed"

标签 c# wpf mouseevent mousemove

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

The MouseMove Event.

我想在鼠标左键被按下时触发MouseMove事件,并且即使鼠标脱离网格或什至不在网格中也保留事件主窗口

When Button is Pressed Keep the Mousemove event for the Grid All over the screen Until Button is Releasd.

认为这是网格的鼠标移动事件方法

    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 但它失败了,你知道这是因为单线程。

所以我的想法是,当在原始网格内按下按钮时,以某种方式在整个屏幕上扩展一个新的网格,并保留它直到释放。

And of course Dummy Grid witch is Hidden.

最佳答案

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

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

    ...

    N。鼠标左键向上(停止旋转)

有一个有趣的概念,叫做 Reactive Programminghttp://rxwiki.wikidot.com/101samples

有一个 C# 库 ( Reactive-Extensions )

您的代码可能如下所示:

// 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 构造函数中订阅此事件流,这样您就不必依赖于 Grid,也不必绘制假的 Grid!

一些不错的链接:

  1. The Rx Framework by example
  2. Rx. Introduction

关于c# - 事件 "While Button is Pressed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30822764/

相关文章:

c# - 我如何替换要求提升的文件

c# - 在 WPF 中打印 DataGrid 中的所有数据

c# - 我如何使用 System.Data.SQLite merge 制作单一可执行文件?

java - AWT(扩展)修饰符何时保证有效?

swift - 快速连续点击不同的按钮

c# - 找不到类型 '' 的构造函数

c# - wpf绑定(bind)问题

c# - 通过加法或减法更新值

c# - WPF 创建滑出面板

javascript - 如何在javascript中检测鼠标右键释放事件?