如何延长WinForms DataGridView单元格ToolTip的显示时长?
修改DataGridView单元格ToolTip显示时长的方案
通过CellFormatting事件设置的DataGridView单元格ToolTip是控件内置的,无法直接调整它的显示时长——它默认使用系统级的ToolTip延迟设置,没有公开属性供开发者修改。要自定义显示时长,必须手动创建ToolTip对象并通过其属性控制。
具体实现步骤
声明并初始化自定义ToolTip对象
在窗体类中定义全局ToolTip实例,并设置所需的延迟属性:private ToolTip customCellToolTip = new ToolTip(); public YourForm() { InitializeComponent(); // 设置ToolTip显示参数(单位:毫秒) customCellToolTip.AutoPopDelay = 6000; // ToolTip持续显示6秒 customCellToolTip.InitialDelay = 300; // 鼠标悬停300毫秒后触发显示 customCellToolTip.ReshowDelay = 100; // 切换单元格时的重显延迟 customCellToolTip.ShowAlways = true; // 即使窗体非激活也显示 }结合单元格鼠标事件控制ToolTip显示
利用CellMouseEnter和CellMouseLeave事件,替代内置ToolTip的触发逻辑:private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e) { // 跳过表头行 if (e.RowIndex < 0) return; DataGridViewCell targetCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; // 读取通过CellFormatting设置的ToolTipText(或直接指定文本) string tipText = targetCell.ToolTipText; if (!string.IsNullOrWhiteSpace(tipText)) { // 获取单元格在屏幕上的位置,确保ToolTip显示在合适位置 Rectangle cellRect = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); Point screenPos = dataGridView1.PointToScreen(new Point(cellRect.Left, cellRect.Top)); // 显示自定义ToolTip customCellToolTip.Show(tipText, this, screenPos.X + cellRect.Width, screenPos.Y + cellRect.Height); } } private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e) { // 鼠标离开单元格时隐藏ToolTip customCellToolTip.Hide(this); }
补充说明
- 如果你已经通过
CellFormatting完成了ToolTip文本的逻辑编写,上述方案可以直接复用cell.ToolTipText的值,无需重复编写文本判断逻辑。 - 自定义ToolTip的
AutoPopDelay属性直接控制显示时长,最大值为50000毫秒(50秒),超过会被自动截断。
内容的提问来源于stack exchange,提问作者0x30
相关产品推荐
相关产品推荐

