wpf 在画布上获取鼠标位置(但不在窗口上)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5690698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Mouse Position on Canvas (But NOT on window)?
提问by CodeMouse92
I have a project in WPF 4 and vb.net 2010.
我在 WPF 4 和 vb.net 2010 中有一个项目。
I have a canvas inside a window. The window is full screen, but the canvas is set to a solid 640x480 in the center of the window. I need to get the mouse position inside of the canvas, but NOT inside of the window. How do I do this?
我在窗口中有一个画布。窗口是全屏的,但画布设置为窗口中心的 640x480 实心尺寸。我需要在画布内获取鼠标位置,但不在窗口内。我该怎么做呢?
回答by H.B.
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,
鼠标指针的位置是相对于指定元素计算的,元素的左上角为原点,
回答by Phillip
Hi the important thing is the
嗨,重要的是
NOT on the Window
不在窗户上
the canvas is part of the window as well. one example:
画布也是窗口的一部分。一个例子:
- the Window.AllowsTransparency state is on true
- the Window.Background is #00000000 (completely transparent)
- the Window.Style is None
- the Window.State is Maximized and
- there are NO controls or elements on the window!
- Window.AllowsTransparency 状态为真
- Window.Background 是 #00000000(完全透明)
- Window.Style 为 None
- Window.State 被最大化并且
- 窗口上没有控件或元素!
... so if you start the application you will see Nothing now tell me how to get the mouseposition on the screen in pixel
...因此,如果您启动该应用程序,您将看到什么都没有告诉我如何以像素为单位在屏幕上获取鼠标位置
!Warning!
if you juse Mouse.GetPosition(this);
it will return x0 y0 every time
!警告!如果你判断Mouse.GetPosition(this);
它每次都会返回 x0 y0
回答by Phillip
so I solved the Problem by using System.Windows.Forms.Control.MousePosition
it's a bit a mix of wpf and Windows.Forms but I've given up xD.
所以我通过使用System.Windows.Forms.Control.MousePosition
wpf 和 Windows.Forms 的混合解决了这个问题,但我已经放弃了 xD。
Sorry for yelling :/
抱歉大喊大叫:/
To make it easy for me I made a Extension:
为了方便我,我做了一个扩展:
<DebuggerHidden> _
<System.Runtime.CompilerServices.Extension> _
Public Function toWfpPoint(p As System.Drawing.Point) As Point
Return new Point(p.X, p.Y)
End Function
Now I just can juse it like this:
现在我可以这样使用它:
Dim MousPos As Point = System.Windows.Forms.Control.MousePosition.toWfpPoint