DataGridView表头右键菜单X位置异常:PointToScreen未正确计算X值
问题原因与解决方法
问题根源
DataGridViewCellMouseEventArgs中的e.Location是当前列头单元格内部的相对坐标,而非相对于整个DataGridView控件的坐标。直接将这个值转成屏幕坐标时,X坐标只包含了单元格内的点击偏移,没有加上该列头单元格在DataGridView控件中的X轴偏移量,导致菜单总是显示在屏幕左边界附近。
修正代码
private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if(e.Button == MouseButtons.Right && e.ColumnIndex >= 0) { DataGridView dgv = sender as DataGridView; // 获取目标列头单元格在DataGridView控件内的显示矩形 Rectangle cellRect = dgv.GetCellDisplayRectangle(e.ColumnIndex, -1, true); // 计算鼠标在控件内的绝对位置:单元格左上角坐标 + 单元格内的点击偏移 Point controlRelativePoint = new Point(cellRect.X + e.Location.X, cellRect.Y + e.Location.Y); // 转换为屏幕坐标并显示菜单 Point screenPoint = dgv.PointToScreen(controlRelativePoint); cmsSpalten.Show(screenPoint); } }
关键说明
- 用
GetCellDisplayRectangle(e.ColumnIndex, -1, true)获取列头单元格的控件内坐标:列头的行索引固定为-1,这个方法能准确返回单元格在DataGridView内的位置和大小。 - 新增
e.ColumnIndex >=0判断,避免点击表头空白区域时触发错误。 - 通过
cellRect.X + e.Location.X计算出鼠标在DataGridView控件内的绝对X坐标,再转成屏幕坐标后,菜单就能准确显示在点击位置了。
内容的提问来源于stack exchange,提问作者UHM
相关产品推荐
相关产品推荐

