2014-08-27 33 views
0

我试图将ColorDialog的Color值存储到注册表中。 我在我的实用程序中使用下面的代码。不过,我注意到,当我重新运行实用程序时,分配到Button1(从的注册表中读取的值)的颜色与我在注册表中首先存储的值不同。如何将正确的颜色对话框值存储到Windows注册表

我开发此实用程序的主要应用程序内置了类似的功能以保存/调用注册表中的颜色设置。我检查了我的实用程序中返回来自表单加载的注册表颜色的代码很好,并且颜色与通过主应用程序设置的颜色相匹配。

有人可以检查下面的代码,让我知道什么是错的?

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 

    Dim CLR = ColorDialog1.Color.GetHashCode.ToString 

    If Me.ColorDialog1.ShowDialog = DialogResult.OK Then 
     Dim regKey As RegistryKey 
     regKey = Registry.CurrentUser.OpenSubKey("Software\MyApp\Settings\Tags", True) 
     regKey.SetValue("DefaultColor", CLR, RegistryValueKind.DWord) 
     regKey.Close() 

     Button1.BackColor = Me.ColorDialog1.Color 
    End If 
End Sub 

代码用于从注册表恢复色彩:

If My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\MyApp\Settings\Tags", "DefaultColor", Nothing) Is Nothing Then 
    MsgBox("Value does not exist.") 
    'creates the DWORD value if not found 
    My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\MyApp\Settings\Tags", "DefaultColor", 0, RegistryValueKind.DWord) 
Else 
    Dim HEX = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\MyApp\Settings\Tags", "DefaultColor", Nothing) 
    Dim myColor As Color = System.Drawing.ColorTranslator.FromWin32(HEX.ToString) 
    TagLeaderCLRButton.BackColor = myColor 
End If 
+0

一个明显的错误是在显示对话框之前获得“CLR”值。向注册表写入错误的值,旧的。在If语句中移动Dim CLR * *。并使用Color.ToArgb() – 2014-08-27 11:21:29

+0

感谢您的建议..我改变了代码... – DK2014 2014-08-27 14:09:43

回答

2

散列码并不代表颜色。 Why GetHashCode() matters?

Dim CLR = ColorDialog1.Color.GetHashCode.ToString 

相反,你应该使用:

Dim clr = ColorDialog1.Color.ToARGB() 

如果可能的话,使用My.settings来存储,而不是注册表颜色。您可以通过在项目属性中创建设置来直接存储颜色。 :)

编辑:
Integer.Parse(HEX.ToString)比刚好HEX.ToString()好一点吧? :)
我没有看到任何错误。如果这是您的实际代码,您可以根据需要将其更改为类似的内容。 (只是一个想法):

Dim path = "HKEY_CURRENT_USER\Software\MyApp\Settings\Tags" 
Dim defColor = My.Computer.Registry.GetValue(path, "DefaultColor", Nothing) 

If defColor Is Nothing Then 
     MsgBox("Value does not exist.") 
     'creates the DWORD value if not found 
     My.Computer.Registry.SetValue(path, "DefaultColor", &HFF00BFFF, RegistryValueKind.DWord) 
     defColor = &HFF00BFFF 
End If 
Button1.BackColor = Color.FromArgb(Integer.Parse(defColor.ToString)) 

有了这个,Button1的背景色自动设置为从第一点击我最喜欢的颜色。呵呵。

+0

非常感谢。你可以看看我正在使用的其他代码检索存储的颜色值的表单加载,它被分配到按钮backcolor ...我将在主帖添加此代码.. – DK2014 2014-08-27 14:10:54

+0

感谢hexMint..will给这个尝试... – DK2014 2014-08-28 07:49:28