2009/01/01 | C# ComboBox下拉表单显示ToolTip(非API函数)
类别(程序语言) | 评论(0) | 阅读(2929) | 发表于 10:49
    近日由于自已一个小程序的需要,要求在ComboBox下拉项目(每个item)上显示ToolTip,用Google搜了几圈,在Codeproject上浏览的几遍,发现相关的介绍比较少,介绍的方法也主要是基于api捕捉实现,这种方法的代码看起来似乎比较复杂(比较完整的实现代码见参考文献[3])。仔细阅读MSDN上关于ComboBox的内容[1],可以看到,更为简单的实现方法是通过ComboBox的DrawItem(绘制下拉菜单时产生的事件)。下面是我通过参考文献[1]与[2]得到的实现代码。主要思路是当下拉项目高亮时(DrawItemState.Selected),即显示TooLTip(这里我们先要new一个ToolTip的实例,这里为toolTip1)。如果你有多个ComboBox需要显示ToolTip,那么应该考虑新建一个ComboBox的继承类。这里我建议采用文献[2]中介绍的方法,文献[2]中的方法还可以实现一个功能,即如果下拉项目的内容长度没有超过ComboBox的宽度时,不显示ToolTip。要注意的一点是使用文献[2]中的代码时,你需要将显示ToolTip的条件改为(e.State & DrawItemState.Selected) == DrawItemState.Selected 并把Else后面的条件语句删除,不然可能得不到我们想要的结果。
-----------------------------------------------------------------------------------------------------------------------------------------------------------          
 //[界面设计中的代码,desigener]
           // 建立名为kineticFileComboBox 下拉表单
            this.kineticFileComboBox.FormattingEnabled = true;
            this.kineticFileComboBox.Location = new System.Drawing.Point(213, 197);
            this.kineticFileComboBox.Name = "kineticFileComboBox";
            this.kineticFileComboBox.Size = new System.Drawing.Size(170, 20);
            this.kineticFileComboBox.TabIndex = 14;
            this.kineticFileComboBox.Text = "请先载入文件...";
           //重绘下拉表单窗口,需要在窗口设计代码中加入下面这一句
            this.kineticFileComboBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            //下拉表单重绘事件
            this.kineticFileComboBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(kineticFileComboBox_DrawItem);
            this.kineticFileComboBox.DropDownClosed += new System.EventHandler(kineticFileComboBox_DropDownClosed);
 
 -----------------------------------------------------------------------------------------------------------------------------------------------------------
  //[主程序中的代码]
  private void kineticFileComboBox_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
        {
            // 绘制背景
            e.DrawBackground();
             //绘制列表项目
            e.Graphics.DrawString(kineticFileComboBox .Items [e.Index ].ToString (), e.Font , System.Drawing.Brushes.Black, e.Bounds );
          //将高亮的列表项目的文字传递到toolTip1(之前建立ToolTip的一个实例)
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                toolTip1.Show(kineticFileComboBox.Items[e.Index].ToString(), kineticFileComboBox, e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height);
            e.DrawFocusRectangle();
        }
        //关闭列表时,同时关闭toolTip1的显示
        private void kineticFileComboBox_DropDownClosed(object sender, System.EventArgs e)
        {  toolTip1.Hide(kineticFileComboBox ); }
(效果图)
 
                    [3]ComboBox的ToolTip显示(注:API方式)
1

评论Comments

日志分类
首页[227]
+随笔[68]
学习札记[67]
科研工具[44]
文献摘译[2]
程序语言[20]
网络技巧[26]
--[0]