根据该文本框的字符串更改文本框的前景色

Change the forecolor of textbox according to the string of that textbox

是否可以创建一个应用程序来根据单击按钮时文本框中的文本更改文本框的前景色(从而更改该文本框中文本的颜色)?

目前我可以通过if-else来做,我觉得这不是做各种颜色最有效的方法。

我有这个代码

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "red" Then
        TextBox1.ForeColor = Color.Red
    ElseIf TextBox1.Text = "green" Then
        TextBox1.ForeColor = Color.Green
    End If
End Sub

结束Class

问题:不使用if else可以吗?我的意思是系统可以检测到字符串并依靠该字符串来更改其前景色或类似的颜色吗?

当然,您不需要执行按钮单击等额外事件,您可以在 text_change 事件本身中处理。it will not throws any exception if the text is not a valid colour,just maintain the predefined color。你可以这样做:

  Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        TextBox1.ForeColor = Color.FromName(TextBox1.Text)
  End Sub

According to MSDN, A predefined color is also called a known color and is represented by an element of the KnownColor enumeration. If the name parameter is not the valid name of a predefined color, the FromName method creates a Color structure that has an ARGB value of 0 (that is, all ARGB components are 0).

TextBox1.ForeColor = Color.fromname(textbox1.text)