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