2014-08-27 34 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