ToString再次回到颜色(Visual Basic 2008)

min*_*ino 2 .net vb.net string visual-studio

我的问题是我正在尝试将String解析为System.Drawing.Color.我试图设置一个简单的记事本,这是我的代码的一部分:

Private Sub ToolStripMenuItem6_Click(ByVal sender As System.Object, ByVal e As       System.EventArgs) Handles Colorfuente2.Click
    Try
        Dim cdlg As New ColorDialog
        cdlg.ShowDialog()
        cdlg.FullOpen = True
        cdlg.AnyColor = True
        ColorFuente1.Visible = True
        Colorfuente2.Visible = False
        If Windows.Forms.DialogResult.OK Then
            RichTextBox1.ForeColor = cdlg.Color
            reciente2.Text = cdlg.Color.ToString 'I've converted this tostring, so   that recent colors are shown as text, this is what im trying to reverse
        End If
    Catch ex As Exception
    End Try
End Sub

     If Reciente1.Text = "Ninguno" Then
        MessageBox.Show("No hay colores recientes", "Bloc de notas", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    Else : RichTextBox1.ForeColor = Reciente1.Text 'I get the error here, I have to change this text to a System.Drawing.Color.
    End If
Run Code Online (Sandbox Code Playgroud)

提前致谢.

小智 5

当你使用cdlg.Color.ToString它时,它并没有真正将它转换为它之后可以读取的字符串.它只是将它转换为"颜色[黄色]"之类的东西.

如果你想使用Color.FromName你将不得不传递它只是"黄色",否则它将返回意想不到的东西.可能是一个默认值为oa的颜色对象.

我建议你用一个 ColorConverter

Dim colorConv As New ColorConverter
TextBox1.Text = colorConv.ConvertToString(cdg.Color)
Run Code Online (Sandbox Code Playgroud)

这将返回一个字符串"Yellow",您可以随意使用它.

'Using FormName
TextBox1.BackColor = Color.FromName(TextBox1.Text)
'Using the color converter again (recommended).
Dim colorConv As New ColorConverter
TextBox1.BackColor = colorConv.ConvertFromString(TextBox1.Text)
Run Code Online (Sandbox Code Playgroud)

您还可以使用子字符串在"颜色[黄色]"中获取"黄色"部分.:P