使用ChrW

时间:2017-11-20 11:13:34

标签: vb.net winforms performance

我使用Visual Studio在VB.NET中编写了一个小游戏。这是“尽可能快地输入字母”游戏。

用户控制显示从A到Z的所有字母,当您按下与该字母关联的键盘上的键时(按照从A到Z的正确顺序),它将变为灰色。

以下是我到目前为止编写的代码:

Public Class UserControl_Alphabet

    Public Shared CurrentKey As Integer = 65

    Private Sub UserControl_Alphabet_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress

        If e.KeyChar = ChrW(CurrentKey) Or e.KeyChar = ChrW(CurrentKey + 32) Then

            ' This section of the code will gray out labels
            Select Case CurrentKey
                Case 65 : Label_A.ForeColor = Color.LightGray
                Case 66 : Label_B.ForeColor = Color.LightGray
                Case 67 : Label_C.ForeColor = Color.LightGray
                ' AND SO ON...
            End Select

            CurrentKey += 1

                If CurrentKey = 91 Then
                    MsgBox("Done")
                End If

            End If

    End Sub

End Class

我的问题是:

  1. 是否有更简单的方法来更改标签上的颜色而不必为每个字母添加一个案例。所有标签按顺序命名,Label_A,Label_B,Label_C等
  2. 我尝试了(Label_ & ChrW(CurrentKey)).ForeColor = Color.LightGray,但这不起作用。

    1. 代码If e.KeyChar = ChrW(CurrentKey) Or e.KeyChar = ChrW(CurrentKey + 32) Then感觉非常草率。必须有更好的方法来写这个。我尝试使用KeyDown事件而不是KeyPress,但这意味着我无法使用ChrW。据我所知KeyDown并不区分大小写KeyPress,这就是为什么我需要将ChrW用于低壳和高壳信件的原因。

1 个答案:

答案 0 :(得分:0)

将标签放入查找表中,并使用字母的键码作为索引。

尝试这样的事情:

Public Class UserControl_Alphabet

    Public Shared CurrentKey As Integer = 65
    private labels As Label() = {Label_A, Label_B, Label_C}

    Private Sub UserControl_Alphabet_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress

        If e.KeyChar = ChrW(CurrentKey) Or e.KeyChar = ChrW(CurrentKey + 32) Then

            ' This section of the code will gray out labels
            labels((CurrentKey-65) Mod labels.length).ForeColor = Color.LightGray

            CurrentKey += 1

                If CurrentKey = 91 Then
                    MsgBox("Done")
                End If

            End If

    End Sub

End Class

<强>增加: 您也可以使用Dictionary而不是数组。这样你就不必根据你的返回值来计算某些东西,你也可以使用,比方说'数字'。 但是,如果您只使用A-Z,则查找表没有任何问题。