zoukankan      html  css  js  c++  java
  • 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);
                }
            }
  • 相关阅读:
    [51nod] 1301 集合异或和
    [BZOJ] 1088: [SCOI2005]扫雷Mine
    [LUOGU] P4251 [SCOI2015]小凸玩矩阵
    8.21模拟赛
    [BZOJ] 3163: [Heoi2013]Eden的新背包问题
    [BZOJ] 1001: [BeiJing2006]狼抓兔子
    【NOIP2017提高A组冲刺11.8】好文章
    [BZOJ] 1520: [POI2006]Szk-Schools
    [BZOJ] 1877: [SDOI2009]晨跑
    day23(事务管理)
  • 原文地址:https://www.cnblogs.com/njcxwz/p/6867575.html
Copyright © 2011-2022 走看看