Winform Combobox.Items tooltip

问题情境:

  需要给下拉框每一个下拉项注释tooltip。

思路解析:

  1.简单做就是每一次下拉框选值改变时,给combobox的tooltip进行替换。缺点是提示不够友好。

  2.结合tooltip可以指定位置显示的属性,在drawItem事件中分情况特定显示。

具体代码:

        ToolTip toolTip1;
        public Form1()
        {
            InitializeComponent();

            //tooltip定义
            toolTip1 = new ToolTip();
            toolTip1.AutoPopDelay = 800;
            toolTip1.InitialDelay = 200;
            toolTip1.ReshowDelay = 200;
            toolTip1.ShowAlways = true;
            toolTip1.SetToolTip(button1, "yeah");
            //toolTip1.SetToolTip(comboBox1, "8888888888888");
        }
        //两个事件结合使用
        private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) return;
            // 绘制背景
            e.DrawBackground();
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                Rectangle rectangle = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
                e.Graphics.FillRectangle(new SolidBrush(SystemColors.ControlDark), rectangle);//重画选中颜色
                toolTip1.Show(comboBox1.Items[e.Index].ToString(), comboBox1, e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height);//tooltip跟随被选中item显示
            }
            e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font, System.Drawing.Brushes.Black, e.Bounds);
            e.DrawFocusRectangle();
        }
        private void ComboBox1_DropDownClosed(object sender, EventArgs e)
        {
            this.button1.Focus();
            toolTip1.Hide(comboBox1);
        }

 注意:

  1.使用drawItem事件,需要修改drawMode属性。

原文地址:https://www.cnblogs.com/gaara-zhang/p/12599955.html