winform 如何正确的获取窗体的标题栏高度

最近我需要知道鼠标在一个控件里的相对位置,鼠标相对于屏幕的位置我是可以知道的,所以只要得到控件相对于屏幕的位置,就可以算出鼠标相对于控件的位置了

但是发现有误差

后来经过测试是由于窗体的标题栏高度导致的

所以减去了窗体的标题栏高度,但是还是有细微的误差

最后经过分析,是由于获取标题栏高度不正确导致的,当搜索如何获取标题栏高度时 所有的答案都是child.Height - child.ClientRectangle.Height,这个做法其实是有误差的,误差甚至有10像素只差

正确的做法是

现先获取窗体边框宽度

 int windowBorder = (child.Width - child.ClientRectangle.Width) / 2;

再减去窗体边框高度
screenY -= (child.Height - child.ClientRectangle.Height - windowBorder);

获取控件左上角相对于屏幕的位置

        /// <summary>
        /// 获取鼠标坐标 相对于视图
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="child"></param>
        /// <returns></returns>
        private Point GetPoint(int x, int y, Control child)
        {
            Point p = new Point();
            int screenX = x;
            int screenY = y;
            screenX -= child.Left;
            screenY -= child.Top;
            if (child.Parent == null)
            {
                int windowBorder = (child.Width - child.ClientRectangle.Width) / 2;
                screenY -= (child.Height - child.ClientRectangle.Height - windowBorder);
                p.X = screenX - windowBorder;
                p.Y = screenY;
                return p;
            }
            else
            {
                return GetPoint(screenX, screenY, child.Parent);
            }
        }
原文地址:https://www.cnblogs.com/njcxwz/p/6867575.html