自定义Windows窗体组合框的外观

时间:2011-02-01 14:31:05

标签: .net winforms combobox custom-controls

这就是我的所作所为:

Public Class ComboBox
    Inherits System.Windows.Forms.ComboBox

    Public Sub New()
        SetStyle(ControlStyles.OptimizedDoubleBuffer _
        Or ControlStyles.UserPaint, True)
    End Sub

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        e.Graphics.FillRectangle(gradient, ClientRectangle)
        // The preceding line is a simplification of about 50 lines of code.

        If Not String.IsNullOrEmpty(Text) Then
            Dim rect As New Rectangle(2, 0, Width - 2, Height)

            Using format As New StringFormat()
                format.LineAlignment = StringAlignment.Center

                Using brush As New SolidBrush(ForeColor)
                    e.Graphics.DrawString(Text, Font, brush, rect, format)
                End Using
            End Using
        End If

        e.Graphics.FillPolygon(Brushes.Black, New Point() { _
        New Point(Width - 5, Height \ 2 - 1), _
        New Point(Width - 12, Height \ 2 - 1), _
        New Point(Width - 9, Height \ 2 + 3)})
    End Sub
End Class

我有两个问题:

  1. 它的高度总是24。
  2. 使用丑陋的Windows 3.1字体呈现下拉列表。
  3. http://i56.tinypic.com/w1p4ph.png

3 个答案:

答案 0 :(得分:1)

要解决字体问题,请在OnControlCreated而不是构造函数中设置UserPaint样式,如下所示:

-F '[|][|][|]'

答案 1 :(得分:0)

您的问题显然在“完整代码”部分。我建议你一次解决一个问题:

1)高度问题:是否可以将高度设置为24,如果更改高度,控件将相应调整大小?你看过Control.PreferredSize属性了吗?在此查看:http://msdn.microsoft.com/en-us/library/system.windows.forms.control.preferredsize.aspx

2)字体问题。如果不查看代码,就无法进行诊断。我可以说的是确保你正确地使用你想要使用的任何字体绘制下拉元素。

答案 2 :(得分:0)

高度问题几乎是肯定的,因为您继承了ComboBox,然后使用标准API调用来绘制大部分内容,当Windows绘制组合框时,高度由字体大小和高度属性的任何更改来修复被忽略了。

同样,Windows使用默认字体,因为您没有更改它或在API调用中的某处设置它。

在继承和进行微小修改时,组合框并不完全友好。您可能必须完全提供自己的自定义实现,这也不是一件容易的事。您可能无法找到第三方自定义控件来呈现您想要的内容。你的公司在没有实际考虑可用控件等的情况下犯了艺术家的错误。抱歉......

相关问题