WPF 客户端到屏幕点转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18103540/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:23:07  来源:igfitidea点击:

WPF client to screen point transformation

c#wpftransformtransformation

提问by HerpDerpington

I'm looking for a way to transofrm given points that are relative to a Visual to Points on the screen. I found this solution:

我正在寻找一种方法来转换与屏幕上的视觉点相关的给定点。我找到了这个解决方案:

http://social.msdn.microsoft.com/Forums/vstudio/en-US/b327c0bc-d27e-44fe-b833-c7db3400d632/how-to-get-control-location-in-screen-coordinate-system

http://social.msdn.microsoft.com/Forums/vstudio/en-US/b327c0bc-d27e-44fe-b833-c7db3400d632/how-to-get-control-location-in-screen-coordinate-system

I can't understand the different beween the pointRootand the pointClientas they seem to be equal all the time:

我无法理解 thepointRoot和 the 之间的不同,pointClient因为它们似乎一直都是平等的:

// [...]
// Translate the point from the visual to the root.
GeneralTransform transformToRoot = relativeTo.TransformToAncestor(root);
Point pointRoot = transformToRoot.Transform(point);

// Transform the point from the root to client coordinates.
Matrix m = Matrix.Identity;
Transform transform = VisualTreeHelper.GetTransform(root);
if (transform != null)
    m = Matrix.Multiply(m, transform.Value);

Vector offset = VisualTreeHelper.GetOffset(root);
m.Translate(offset.X, offset.Y);
Point pointClient = m.Transform(pointRoot);
// [...]

(for the full code click on the link)

(完整代码请点击链接)

It seems that the VisualTreeHelper.GetOffset(root)tries to get the transform of the window...

似乎VisualTreeHelper.GetOffset(root)试图获得窗口的变换......

回答by Sheridan

Assuming that your Visualcomes from a Buttoncontrol... are you looking for something like this?:

假设你Visual来自一个Button控件......你在寻找这样的东西吗?:

Point locationFromWindow = button1.TranslatePoint(new Point(0, 0), this);

Point locationFromScreen = button1.PointToScreen(locationFromWindow);

Note: these are both methods of the Visualclass, so you can also call them from your Visualdirectly.

注意:这些都是Visual类的方法,所以你也可以Visual直接调用它们。