在 WPF 中“捕获鼠标”是什么意思?

System.Windows.UIElement上有一个 CaptureMouse()和一个配对的 ReleaseMouseCapture()方法。在这个 WPF 拖拽机示例中,他们在 MouseDown 上调用 CaptureMouse 并在 MouseUp 上发布它。MSDN 中的文档几乎没有任何用处——“捕捉鼠标—— > 捕捉鼠标。”

在尝试之前,我认为它以某种方式锁定了 UIElement 边界内的鼠标,但是当我尝试它时,情况显然并非如此。从实验来看,它似乎与响应事件有关,当鼠标在 UIElement 之外,但不想成为一个 货物邪教程序员,我不想仅仅使用它,因为这个例子,我想要一个权威的描述,它的意思是什么。

38172 次浏览

From Capture and Uncapture the Mouse on MSDN:

When an object captures the mouse, all mouse related events are treated as if the object with mouse capture perform the event, even if the mouse pointer is over another object.

Only the capturing control receives the mouse events until released.

Capturing the mouse is useful for dragging because all the dragging code can exist in the one control, rather than being spread over multiple controls.

The Silverlight 2 documentation for it has a more verbose description, I don't know why it isn't a part of the 3.5 documentation page too:

When an object has captured the mouse, that object receives mouse input whether or not the mouse pointer is within its bounding area. The mouse is typically only captured during simulated drag operations.
...

It works the same with WPF, and so the reason it is used with DragDrop, is that is how the it knows to report back to the control being dragged from when the mouse may be outside of that control. If you comment out the MyCanvas.Capture() and the Capture(Null) (which clears it) then you can no longer drop.

When it has captured the mouse, a control will receive mouse events even if the mouse pointer is no longer within its bounding area.

Typically, it's used for:

  • Drag and drop
  • Buttons (to handle Mouse Up when you put the mouse down on the button and move the mouse before you release the button)