WinForm实现ComboBox添加ToolTip悬浮文本提示功能
1.代码结构
2.实现代码
using System; using System.Drawing; using System.Windows.Forms; namespace WinFormComboBoxWithTooltipDemo { /// <summary> /// WinForm 实现 ComboBox带有悬浮提示文本 /// LDH @ 2018-6-6 /// </summary> public partial class FrmMain : Form { /// <summary> /// ToolTip /// </summary> private readonly ToolTip _tip = new ToolTip(); public FrmMain() { InitializeComponent(); } private void FrmMain_Load(object sender, EventArgs e) { comboBox1.Items.Clear(); comboBox1.Items.Insert(0, "第一"); comboBox1.Items.Insert(1, "第二"); comboBox1.Items.Insert(2, "第三"); comboBox1.Items.Insert(3, "第四"); comboBox1.DrawMode = DrawMode.OwnerDrawFixed; comboBox1.DrawItem += comboBox1_DrawItem; comboBox1.DropDownClosed += comboBox1_DropDownClosed; comboBox1.SelectedIndex = 1; } private void comboBox1_DropDownClosed(object sender, EventArgs e) { _tip.Hide(comboBox1); } private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) { // 绘制背景 e.DrawBackground(); // 绘制列表项目 e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds); // 将高亮的列表项目的文字传递到toolTip1(之前建立ToolTip的一个实例) if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { _tip.Show(comboBox1.Items[e.Index].ToString(), comboBox1, e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height); } e.DrawFocusRectangle(); } } }
3.运行效果
本文作者:Love In Winter
本文链接:https://www.cnblogs.com/LifeDecidesHappiness/p/9145313.html
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!
本文链接:https://www.cnblogs.com/LifeDecidesHappiness/p/9145313.html
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!
![扫一扫,支付宝打赏](https://files.cnblogs.com/files/LifeDecidesHappiness/%E6%94%AF%E4%BB%98%E5%AE%9D.bmp)
![扫一扫,微信打赏](https://files.cnblogs.com/files/LifeDecidesHappiness/%E5%BE%AE%E4%BF%A1%E6%94%B6%E6%AC%BE%E7%A0%81.bmp)