首页 文章

大胆,斜体和下划线-vb.net

提问于
浏览
0

我的程序根据点击的按钮使标签变为粗体,斜体或下划线 . 但是当我试图同时获得两种效果时,第一次消失 .

Private Sub bold_Click(sender As Object, e As EventArgs) Handles bold.Click

    Dim con4 As Control
    For Each con4 In Me.Controls
        Select Case con4.Name
            Case "Label1"
                If con4.Font.Bold = False Then
                    con4.Font = New Font(con4.Font, FontStyle.Bold)
                Else
                    con4.Font = New Font(con4.Font, FontStyle.Regular)
                End If
            Case "Label2"
                If con4.Font.Bold = False Then
                    con4.Font = New Font(con4.Font, FontStyle.Bold)
                Else
                    con4.Font = New Font(con4.Font, FontStyle.Regular)
                End If

...

End Select
    Next
End Sub

此代码可用于Label24 .

所以我对3个不同的按钮使用相同的程序,他们得到了我的结果 . 但是试图将两个效果放在一起会覆盖前一个效果 .


多谢你们 .

1 回答

  • 3

    您可以使用下一个测试覆盖字体样式,因为您一次只检查和设置所有条件 .

    将每个标签的测试组合一次,然后选择正确的字体:

    If con4.Font.Bold = False Then
        If con4.Font.Italic = False Then
            con4.Font = New Font(con4.Font, FontStyle.Bold Or FontSryle.Italic)
        Else ' not italic
            con4.Font = New Font(con4.Font, FontStyle.Bold)
        End If
    Else ' not bold
        If con4.Font.Italic = False Then
            con4.Font = New Font(con4.Font, FontStyle.Italic)
        Else ' not italic
            con4.Font = New Font(con4.Font, FontStyle.Regular)
        End If
     End If
    

    正如你所看到的,这很快就变得笨拙;特别是如果你为24个标签重复相同的代码 . 因此,步骤#1将使该序列成为一个函数 .

    第二步是摆脱所有这些比较 - 添加下划线会为所有单独的案例添加另一个级别的 if..else..end if !您可以将 FontStyle 位与 Or 组合以形成最终值,然后才设置它:

    fontstyle = FontStyle.Regular
    If cond4.Font.Bold = False Then
        fontstyle = fontStyle.Bold
    End If
    If cond4.Font.Italic = False Then
        fontstyle = fontstyle Or fontStyle.Italic
    End If
    If cond4.Font.Underline = False Then
        fontstyle = fontstyle Or fontStyle.Underline
    End If
    target.Font = New Font(con4.Font, fontstyle)
    

    (这可能不完全是正确的语法,但一般的想法应该是清楚的 . )

相关问题