Twitter iPhone pliant OnePlus 11 PS5 Disney+ Orange Livebox Windows 11

string en color

4 réponses
Avatar
Michel Lemaitre
Bonjour,
Je stocke la valeur d'une couleur dans un string (ex : "0, 0, 192")
Je cherche un moyen de la relire(de retrouver la couleur correspondante).
J'ai essayé avec Color.FromArgb, il refuse de lire un string.
Pouvez-vous m'indiquer la bonne méthode.
Merci.
Michel Lemaitre

4 réponses

Avatar
Zoury
Salut Michel ! :O)

Je stocke la valeur d'une couleur dans un string (ex : "0, 0, 192")



Souhaites-tu que la couleur reste lisible/compréhensible ?


Je cherche un moyen de la relire(de retrouver la couleur correspondante).
J'ai essayé avec Color.FromArgb, il refuse de lire un string.



Tu peux écrire la répresentation de la couleur sous forme d'entier dans la
string et la relire en la reconvertissant :
'***
Dim sColor As String = Color.Aqua.ToArgb().ToString()
Dim oColor As Color = Color.FromArgb(Int32.Parse(sColor))
'***

--
Cordialement
Yanick
MVP pour Visual Basic
Avatar
Michel Lemaitre
Boujours
En fait, je veux enregistrer les préférence de l'utilisateur: ici la
couleur d'un élément de l'interface. Je pensais à un string dans la base
de registre. Je veux a la réouverture du logiciel lire le string, le
transformer en couleur et donner cette couleur à l'élément de mon interface.
Si tu as une idée...
merci
Michel
Zoury a écrit :
Salut Michel ! :O)


Je stocke la valeur d'une couleur dans un string (ex : "0, 0, 192")




Souhaites-tu que la couleur reste lisible/compréhensible ?


Non



Je cherche un moyen de la relire(de retrouver la couleur correspondante).
J'ai essayé avec Color.FromArgb, il refuse de lire un string.




Tu peux écrire la répresentation de la couleur sous forme d'entier dans la
string et la relire en la reconvertissant :
'***
Dim sColor As String = Color.Aqua.ToArgb().ToString()
Dim oColor As Color = Color.FromArgb(Int32.Parse(sColor))
'***



Avatar
Zoury
Salut Michel ! :O)

Je pensais à un string dans la base
de registre.



Si tu veux la sauver dans le registre, j'opterais pour la conserver en DWord
(4 octets = Int32 = Color.ToArgb()) :
'***
'1 Button
'1 ColorDialog
Option Explicit On

Imports Microsoft.Win32

Public Class Form1
Inherits System.Windows.Forms.Form

' Code généré par le Concepteur Windows Form

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim rk As RegistryKey Registry.CurrentUser.CreateSubKey("ApplicationMyAppConfig")
Button1.ForeColor = Color.FromArgb(rk.GetValue("ButtonColor",
Button1.ForeColor.ToArgb()))
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
ColorDialog1.AllowFullOpen = True
ColorDialog1.Color = Button1.ForeColor
If (ColorDialog1.ShowDialog() = DialogResult.OK) Then
Button1.ForeColor = ColorDialog1.Color
End If
End Sub

Private Sub Form1_Closed(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Closed
Dim rk As RegistryKey Registry.CurrentUser.CreateSubKey("ApplicationMyAppConfig")
rk.SetValue("ButtonColor", Button1.ForeColor.ToArgb())
End Sub

End Class
'***

Tu aussi aussi écrire tes préférences dans un fichier conservé localement. À
mon avis cette méthode à plusieurs avantages sur l'emploi des registres pour
conservé tes préférences..
Regarde ce message pour plus de détails :
http://groups.google.com/groups?selm=ulZa4RCcFHA.1448%40TK2MSFTNGP14.phx.gbl

Pour y parvenir, tu peux employer un simple fichier INI, un fichier XML (qui
est plus à la mode de par sa structure clair et son normalisme) ou encore un
fichier binaire (par sérialisation).

Voici un exemple concret de l'emploi de la sérialisation pour ce type de
manoeuvre (Les objets serialisés doivent posséder l'attribut Serializable())
:
'***
' 2 Buttons
Option Explicit On

Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters
Imports System.Runtime.Serialization.Formatters.Binary

Public Class Form1
Inherits System.Windows.Forms.Form

Private Const FILE_NAME As String = "config.bin"
Private _sFilePath As String
Private _ac As AppConfig

' Code généré par le Concepteur Windows Form

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

' on détermine le chemin du fichier
_sFilePath = String.Format("{0}..{1}", Application.StartupPath(),
FILE_NAME)

' on récupère les configs et les appliquent au besoin
_ac = DeserializeAppConfig(_sFilePath)
If (_ac Is Nothing) Then
_ac = GetDefaultAppConfig()
Else
ApplyAppConfig(_ac)
End If

Button1.Text = "ForeColor"
Button2.Text = "BackColor"

End Sub

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

If (UserChangeColor(_ac.ButtonForeColor)) Then
ApplyAppConfig(_ac)
End If

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click

If (UserChangeColor(_ac.ButtonBackColor)) Then
ApplyAppConfig(_ac)
End If

End Sub

Private Sub Form1_Closed(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Closed

' on sauvegarde les configs
SerializeAppConfig(_sFilePath, _ac)

End Sub

Private Sub SerializeAppConfig(ByVal FilePath As String, ByVal Config As
AppConfig)

Dim fs As FileStream
Dim bf As BinaryFormatter

' on créer le fichier et stocke le Font dedans
fs = New FileStream(FilePath, FileMode.Create, FileAccess.Write,
FileShare.None)
bf = New BinaryFormatter
bf.Serialize(DirectCast(fs, Stream), Config)
fs.Close()

End Sub

Private Function DeserializeAppConfig(ByVal FilePath As String) As
AppConfig

Dim obj As Object

' vérifie si le fichier existe
' si oui, on retourne le Font contenu dedans
' si non, on renvoit Nothing

If (File.Exists(FilePath)) Then

Dim fs As FileStream
Dim bf As BinaryFormatter

fs = New FileStream(FilePath, FileMode.Open, FileAccess.Read,
FileShare.None)
' on vérifie si le fichier n'est pas vide
If (fs.Length > 0) Then
bf = New BinaryFormatter
obj = DirectCast(bf.Deserialize(DirectCast(fs, Stream)),
AppConfig)
fs.Close()
End If

End If

Return obj

End Function

Private Function GetDefaultAppConfig() As AppConfig

Dim appConfig As New AppConfig

appConfig.ButtonForeColor = SystemColors.ControlText
appConfig.ButtonBackColor = SystemColors.Control

Return appConfig

End Function

Private Sub ApplyAppConfig(ByVal appConfig As AppConfig)

For Each ctl As Control In Me.Controls
If (ctl.GetType() Is GetType(Button)) Then
Dim btn As Button = DirectCast(ctl, Button)
btn.ForeColor = appConfig.ButtonForeColor
btn.BackColor = appConfig.ButtonBackColor
End If
Next

End Sub

Private Function GetColor(ByVal CurrentColor As Color) As Color

ColorDialog1.AllowFullOpen = True
ColorDialog1.Color = CurrentColor
If (ColorDialog1.ShowDialog() = DialogResult.OK) Then
Return ColorDialog1.Color
Else
Return Color.Empty
End If

End Function

Private Function UserChangeColor(ByRef CurrentColor As Color) As Boolean

Dim col As Color = GetColor(CurrentColor)
If (Not col.Equals(Color.Empty)) Then
CurrentColor = col
UserChangeColor = True
End If

End Function

End Class
'***
<Serializable()> _
Public NotInheritable Class AppConfig

Private _buttonForeColor As Color
Private _buttonBackColor As Color

Public Sub New()
End Sub

Public Property ButtonForeColor() As Color
Get
Return _buttonForeColor
End Get
Set(ByVal Value As Color)
_buttonForeColor = Value
End Set
End Property

Public Property ButtonBackColor() As Color
Get
Return _buttonBackColor
End Get
Set(ByVal Value As Color)
_buttonBackColor = Value
End Set
End Property

End Class
'***

Si tu as besoin de plus de détails et/ou d'autres exemples n'hésite pas .
;O)

--
Cordialement
Yanick
MVP pour Visual Basic
Avatar
Michel Lemaitre
Merci de cette réponse clair;-)
Je vais me mettre au travail
Michel
Zoury a écrit :
Salut Michel ! :O)


Je pensais à un string dans la base
de registre.




Si tu veux la sauver dans le registre, j'opterais pour la conserver en DWord
(4 octets = Int32 = Color.ToArgb()) :
'***
'1 Button
'1 ColorDialog
Option Explicit On

Imports Microsoft.Win32

Public Class Form1
Inherits System.Windows.Forms.Form

' Code généré par le Concepteur Windows Form

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim rk As RegistryKey > Registry.CurrentUser.CreateSubKey("ApplicationMyAppConfig")
Button1.ForeColor = Color.FromArgb(rk.GetValue("ButtonColor",
Button1.ForeColor.ToArgb()))
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
ColorDialog1.AllowFullOpen = True
ColorDialog1.Color = Button1.ForeColor
If (ColorDialog1.ShowDialog() = DialogResult.OK) Then
Button1.ForeColor = ColorDialog1.Color
End If
End Sub

Private Sub Form1_Closed(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Closed
Dim rk As RegistryKey > Registry.CurrentUser.CreateSubKey("ApplicationMyAppConfig")
rk.SetValue("ButtonColor", Button1.ForeColor.ToArgb())
End Sub

End Class
'***

Tu aussi aussi écrire tes préférences dans un fichier conservé localement. À
mon avis cette méthode à plusieurs avantages sur l'emploi des registres pour
conservé tes préférences..
Regarde ce message pour plus de détails :
http://groups.google.com/groups?selm=ulZa4RCcFHA.1448%40TK2MSFTNGP14.phx.gbl

Pour y parvenir, tu peux employer un simple fichier INI, un fichier XML (qui
est plus à la mode de par sa structure clair et son normalisme) ou encore un
fichier binaire (par sérialisation).

Voici un exemple concret de l'emploi de la sérialisation pour ce type de
manoeuvre (Les objets serialisés doivent posséder l'attribut Serializable())
:
'***
' 2 Buttons
Option Explicit On

Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters
Imports System.Runtime.Serialization.Formatters.Binary

Public Class Form1
Inherits System.Windows.Forms.Form

Private Const FILE_NAME As String = "config.bin"
Private _sFilePath As String
Private _ac As AppConfig

' Code généré par le Concepteur Windows Form

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

' on détermine le chemin du fichier
_sFilePath = String.Format("{0}..{1}", Application.StartupPath(),
FILE_NAME)

' on récupère les configs et les appliquent au besoin
_ac = DeserializeAppConfig(_sFilePath)
If (_ac Is Nothing) Then
_ac = GetDefaultAppConfig()
Else
ApplyAppConfig(_ac)
End If

Button1.Text = "ForeColor"
Button2.Text = "BackColor"

End Sub

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

If (UserChangeColor(_ac.ButtonForeColor)) Then
ApplyAppConfig(_ac)
End If

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click

If (UserChangeColor(_ac.ButtonBackColor)) Then
ApplyAppConfig(_ac)
End If

End Sub

Private Sub Form1_Closed(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Closed

' on sauvegarde les configs
SerializeAppConfig(_sFilePath, _ac)

End Sub

Private Sub SerializeAppConfig(ByVal FilePath As String, ByVal Config As
AppConfig)

Dim fs As FileStream
Dim bf As BinaryFormatter

' on créer le fichier et stocke le Font dedans
fs = New FileStream(FilePath, FileMode.Create, FileAccess.Write,
FileShare.None)
bf = New BinaryFormatter
bf.Serialize(DirectCast(fs, Stream), Config)
fs.Close()

End Sub

Private Function DeserializeAppConfig(ByVal FilePath As String) As
AppConfig

Dim obj As Object

' vérifie si le fichier existe
' si oui, on retourne le Font contenu dedans
' si non, on renvoit Nothing

If (File.Exists(FilePath)) Then

Dim fs As FileStream
Dim bf As BinaryFormatter

fs = New FileStream(FilePath, FileMode.Open, FileAccess.Read,
FileShare.None)
' on vérifie si le fichier n'est pas vide
If (fs.Length > 0) Then
bf = New BinaryFormatter
obj = DirectCast(bf.Deserialize(DirectCast(fs, Stream)),
AppConfig)
fs.Close()
End If

End If

Return obj

End Function

Private Function GetDefaultAppConfig() As AppConfig

Dim appConfig As New AppConfig

appConfig.ButtonForeColor = SystemColors.ControlText
appConfig.ButtonBackColor = SystemColors.Control

Return appConfig

End Function

Private Sub ApplyAppConfig(ByVal appConfig As AppConfig)

For Each ctl As Control In Me.Controls
If (ctl.GetType() Is GetType(Button)) Then
Dim btn As Button = DirectCast(ctl, Button)
btn.ForeColor = appConfig.ButtonForeColor
btn.BackColor = appConfig.ButtonBackColor
End If
Next

End Sub

Private Function GetColor(ByVal CurrentColor As Color) As Color

ColorDialog1.AllowFullOpen = True
ColorDialog1.Color = CurrentColor
If (ColorDialog1.ShowDialog() = DialogResult.OK) Then
Return ColorDialog1.Color
Else
Return Color.Empty
End If

End Function

Private Function UserChangeColor(ByRef CurrentColor As Color) As Boolean

Dim col As Color = GetColor(CurrentColor)
If (Not col.Equals(Color.Empty)) Then
CurrentColor = col
UserChangeColor = True
End If

End Function

End Class
'***
<Serializable()> _
Public NotInheritable Class AppConfig

Private _buttonForeColor As Color
Private _buttonBackColor As Color

Public Sub New()
End Sub

Public Property ButtonForeColor() As Color
Get
Return _buttonForeColor
End Get
Set(ByVal Value As Color)
_buttonForeColor = Value
End Set
End Property

Public Property ButtonBackColor() As Color
Get
Return _buttonBackColor
End Get
Set(ByVal Value As Color)
_buttonBackColor = Value
End Set
End Property

End Class
'***

Si tu as besoin de plus de détails et/ou d'autres exemples n'hésite pas .
;O)