我的应用程序中有一些字体组合框。
我可以从一个子组中启动它们,即:
Public Sub InitFontCombo(ByVal uCombo As ComboBox)
uCombo.DrawMode = DrawMode.OwnerDrawFixed
uCombo.Font = New Font("Microsoft Sans Serif, 11.25pt", 11.25)
uCombo.ItemHeight = 20
Dim objFontFamily As FontFamily
Dim objFontCollection As System.Drawing.Text.FontCollection
objFontCollection = New System.Drawing.Text.InstalledFontCollection()
For Each objFontFamily In objFontCollection.Families
modControls.ComboAddItem(uCombo, objFontFamily.Name)
Next
End Sub
但是,我仍然需要对每个表单进行DrawItem调用,如下所示:
Private Sub cboFont_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles cboFontName.DrawItem
e.DrawBackground()
If (e.State And DrawItemState.Focus) <> 0 Then
e.DrawFocusRectangle()
End If
Dim objBrush As Brush = Nothing
Try
If e.Index > -1 Then
objBrush = New SolidBrush(e.ForeColor)
Dim sFontName As String = Me.cboFontName.Items(e.Index).ToString
Dim nFont As Font = Nothing
Dim nFontFamily = New FontFamily(sFontName)
If nFontFamily.IsStyleAvailable(FontStyle.Regular) Then
nFont = New Font(nFontFamily, 14, FontStyle.Regular)
ElseIf nFontFamily.IsStyleAvailable(FontStyle.Bold) Then
nFont = New Font(nFontFamily, 14, FontStyle.Bold)
ElseIf nFontFamily.IsStyleAvailable(FontStyle.Italic) Then
nFont = New Font(nFontFamily, 14, FontStyle.Italic)
End If
e.Graphics.DrawString(sFontName, nFont, objBrush, e.Bounds)
End If
Finally
If objBrush IsNot Nothing Then
objBrush.Dispose()
End If
objBrush = Nothing
End Try
End Sub
有没有办法自动化这两个电话? 或者我是否需要将组合框放在用户控件中并在那里做所有事情?
答案 0 :(得分:0)
如果您希望来自多个控件的相同自定义行为,则应创建自定义控件。声明一个名为FontComboBox
的新类,并使其继承ComboBox
类。然后,您可以将初始化放在类中,并覆盖类中的OnDrawItem
方法,而不是在外部处理DrawItem
事件。