21

我在 WPF 4 和 vb.net 2010 中有一个项目。

我在窗户里有一块画布。窗口是全屏的,但画布设置为窗口中心的纯色 640x480。我需要在画布内获取鼠标位置,而不是在窗口内。我该怎么做呢?

4

3 回答 3

54

Doesn't this work?

Point p = Mouse.GetPosition(canvas);

The position of the mouse pointer is calculated relative to the specified element with the upper-left corner of element being the point of origin,

于 2011-04-17T01:16:17.013 回答
2

嗨,重要的是

不在窗户上

画布也是窗口的一部分。一个例子:

  • Window.AllowsTransparency 状态为真
  • Window.Background 是 #00000000 (完全透明)
  • Window.Style 为无
  • Window.State 被最大化并且
  • 窗口上没有控件或元素!

...因此,如果您启动应用程序,您将看到现在没有任何内容告诉我如何以像素为单位获取屏幕上的鼠标位置

!警告!如果你觉得Mouse.GetPosition(this);它每次都会返回 x0 y0

于 2013-03-28T17:04:15.837 回答
1

所以我通过使用System.Windows.Forms.Control.MousePositionwpf 和 Windows.Forms 的混合解决了这个问题,但我已经放弃了 xD。

对不起大喊大叫:/

为了方便我,我做了一个扩展:

<DebuggerHidden> _
<System.Runtime.CompilerServices.Extension> _
Public Function toWfpPoint(p As System.Drawing.Point) As Point
    Return new Point(p.X, p.Y)
End Function

现在我只能这样:

Dim MousPos As Point = System.Windows.Forms.Control.MousePosition.toWfpPoint
于 2014-10-31T14:10:55.867 回答