Maria
Maria

Reputation: 41

How do you change the same background color on all forms?

I'm working on this project and I required to allow the user to select a color from the color picker and then it changes into the current form's background, the code I used is:

Dim cd As New ColorDialog()
        If cd.ShowDialog() = DialogResult.OK Then
            Me.BackColor = cd.Color
        End If

This code works fine, but it only changes the current form background color, how will I make it so it changes the background colour of all the forms in the project eg Form 1,2 and 3 at the same time.

Upvotes: 0

Views: 1169

Answers (3)

user10982370
user10982370

Reputation:

I'd create a setting called BackColor. Do so by going to:

Project -> Properties -> Settings.

Then create the setting:

Put the Name you'd like

Type as String

Scope as User

Then in your code put this:

Dim cd As New ColorDialog()
        If cd.ShowDialog() = DialogResult.OK Then
            Me.BackColor = cd.Color
            My.Settings.BackColor = cd.color
            My.Settings.Save()
        End If

Then on each form load put this code:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.BackColor = My.Settings.BackColor
    My.Settings.Save()
End Sub

Upvotes: 1

Idle_Mind
Idle_Mind

Reputation: 39132

Add a Module to your project, then create a global variable to hold the selected color:

Module Module1
    Public FormBackColor As Color = SystemColors.Control
End Module

When you select a new color, store it there. Additionally, loop through all open forms via Application.OpenForms, and change their color:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim cd As New ColorDialog()
    If cd.ShowDialog() = DialogResult.OK Then
        FormBackColor = cd.Color

        For Each frm As Form In Application.OpenForms
            frm.BackColor = FormBackColor
        Next
    End If
End Sub

For all forms, add a line in the Load() event that sets the color to the current color. This will make it so that new forms will load with the current color as well:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.BackColor = FormBackColor
End Sub

Upvotes: 0

If you are working with an MDI parent form then you can loop through all child forms and change the backColor.

Upvotes: 0

Related Questions