繁体   English   中英

查找Wpf WindowsFormsHost中托管的Winforms控件的中心

[英]Finding the Center of a Winforms Control hosted in a Wpf WindowsFormsHost

我正在将Winforms项目转换为WPF的过程中,遇到了一个非常特殊的问题。 请允许我解释。 在我的项目中,我正在使用OpenTK,这意味着我需要在WindowsFormHost中托管GLControl。 GLControl使用了第一人称摄影机,并且要使其正常工作,我需要计算GLControl的确切中心,当用户“环顾四周”时,我将鼠标置于该中心。 这是我在WPF中的应用示例:

在此处输入图片说明

我以前在WinForms中使用的功能是:

        public static Point FindCenterOfControl(Form parent, Control control)
        {
            Point location = parent.PointToScreen(control.Location);
            return new Point(location.X + control.Width / 2, location.Y + control.Height / 2);
        }

但是自然地,这在WPF中不起作用。 我尝试了各种参数,但是我总是收到空崩溃的消息,主要是因为我的GLControl在WPF应用程序中托管时显然不再使用“ Location”属性。 因此,坦率地说,我不知道如何实现这一目标。

另外要注意的是,只要我猜中心应该在哪里,我的代码就可以工作。 我可以移动相机,看起来还不错。 当我调整窗口大小时会出现问题,因为这样中心距应该放置的位置很远,而我的第一人称相机却弹道。 我需要一种方法来复制我以前在WPF应用程序中计算控件绝对中心的功能。

有谁知道如何在WPF环境中将旧功能转换为支持托管控件的东西?

没关系,我找到了解决方案,或者至少……是一个肮脏的hack。 诀窍是不要尝试找到我的GLControl的中心,而是找到WindowsFormsHost的中心。 这是我的代码,以便将来对其他人有帮助。

        public Point FindCenter()
        {
            System.Windows.Point relativePoint = _host.TransformToAncestor(_parent).Transform(new System.Windows.Point(0, 0));
            return new Point((int) (relativePoint.X + _host.ActualWidth / 2), (int) (relativePoint.Y + _host.ActualHeight / 2));
        }

更新:

事实证明,上述方法实际上是错误的。 无论我的窗口大小或位置如何,它都将光标居中在预定位置。 这个位置错了。 但是,我精心设计了一种新方法,可以达到预期的效果。

        public Point FindCenter()
        {
            System.Windows.Point relativePoint = _host.PointToScreen(new System.Windows.Point(0, 0));
            return new Point((int)(relativePoint.X + (this.Width/2)), (int)(relativePoint.Y + (this.Height/2)));
        }

该方法的确将光标居中在控件的正确位置。 如果您打算在自己的应用程序中使用它,则建议两者都尝试确定哪一个适合您的需求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM