How can I change the ForeColor of all labels on a form?
Is it possible to change the ForeColor
of all the labels on a form at runtime, including the form which is yet to be called? So that all the labels have the开发者_运维问答 same color throughout the app.
You just need to loop through all of the Form's controls looking for labels. Controls can have child controls so you want to do this recursively:
Private Sub UpdateLabelFG(ByVal controls As ControlCollection, ByVal fgColor As Color)
If controls Is Nothing Then Return
For Each C As Control In controls
If TypeOf C Is Label Then DirectCast(C, Label).ForeColor = fgColor
If C.HasChildren Then UpdateLabelFG(C.Controls, fgColor)
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
UpdateLabelFG(Me.Controls, Color.Red)
End Sub
I don't think this is as trivial as you might think. It's easy enough to cycle through all of the controls on a particular form and set the forecolor. But if you have multiple forms open and set the forecolor in one form; getting all forms to change color is going to be a problem.
I'd say, create your own Form class that inherits from System.Windows.Forms.Form; use this new form throughout your application. Add a private sub that takes in the color and loops through the form's controls, setting the label forecolor to the desired color (see Chris Haas's post for an excellent example of this).
Then create a singleton ColorManager class. The application as a whole will only ever have one foreground color. ColorManager should have a public event that is fired when the color is changed and a 'SetColor' function (or property however you like) that you will use to set the color.
Then, going back to your form class, you add the event handler for the ColorManager's change color event.
Now any form can set the application-wide forecolor and all open forms will respond to that event and set their color appropriately.
精彩评论