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

但是发现有误差

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

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

最后经过分析,是由于获取标题栏高度不正确导致的,当搜索如何获取标题栏高度时 所有的答案都是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) / ;
screenY -= (child.Height - child.ClientRectangle.Height - windowBorder);
p.X = screenX - windowBorder;
p.Y = screenY;
return p;
}
else
{
return GetPoint(screenX, screenY, child.Parent);
}
}

最新文章

  1. 【JAVA面试题系列一】面试题总汇--JAVA基础部分
  2. [开源]C#二维码生成解析工具,可添加自定义Logo
  3. 003:Posix IPC的消息队列
  4. 反编译dtsi
  5. [转]连续创建多个Oracle触发器失败,单个创建才成功的解决方法
  6. 百度UEditor编辑器使用教程与使用方法
  7. poj 1904 King&#39;s Quest
  8. jQuery表格操作
  9. 【转】Ubuntu Linux 下文件名乱码(无效的编码)的快速解决办法
  10. HBase文件格式演变之路
  11. ecshop循环计数
  12. CodeForces-731A
  13. 压力测试工具ab - Apache HTTP server benchmarking tool
  14. [3]第二章 C++编程简介
  15. asp.net core 系列 19 EFCore介绍
  16. 监控 | open-falcon | 安装
  17. IDEA将项目上传至码云/GitHub托管
  18. go依赖包下载加速方法及github加速
  19. Docker环境的持续部署优化实践
  20. 安卓的SlidingMenu配置

热门文章

  1. uboot主Makefile分析
  2. a, b交换与比较问题
  3. 登录页面jsp跳转到另一个jsp 与jsp-Servlet-jsp
  4. JQuery直接调用asp.net后台WebMethod方法(转)
  5. SVN 用户名切换
  6. C#调用EasyPusher推送到EasyDarwin实现视频流中转
  7. I.MX6 Android 5.1 纯Linux、U-Boot编译
  8. Python之contextlib库及源码分析
  9. JavaWeb中验证码的实现
  10. erlang的dict和maps模块