.net - ToString 再次变回颜色(Visual basic 2008)

标签 .net vb.net string visual-studio

我的问题是我试图将字符串解析为 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

提前致谢。

最佳答案

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

如果你想使用Color.FromName,你必须只传递"Yellow",否则它会返回一些意想不到的东西。可能是具有默认值或无值的颜色对象。

我建议您使用 ColorConverter

Dim colorConv As New ColorConverter
TextBox1.Text = colorConv.ConvertToString(cdg.Color)

这将返回一个字符串“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)

您还可以使用子字符串获取“颜色[黄色]” 中的“黄色” 部分。 :P

关于.net - ToString 再次变回颜色(Visual basic 2008),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9791421/

相关文章:

c# - 如何在 C# 中获取 Hotmail 联系人列表?

vb.net - Or 与 OrElse

vb.net - 如何忽略vb.net中的服务器错误?在C#中,您只需尝试/捕获并忽略然后异常

c# - 模式匹配案例 when

c# - 奇怪的 SNMP 移位操作

vb.net - WCF/SSL 问题

string - 将文字字符串(纯文本)附加到 XPath 结果

javascript - 转义反斜杠在javascript中打印两个反斜杠

php - 在 PHP 中生成 4 到 8 个字符的随机字符串

c# - CodeDomProvider.CompileAssemblyFromSource - 找不到 Roslyn (csc.exe)