如何在所有表格上更改相同的背景色?

时间:2019-03-22 11:33:52

标签: vb.net visual-studio

我正在从事这个项目,我需要允许用户从颜色选择器中选择一种颜色,然后将其更改为当前表单的背景,我使用的代码是:

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

此代码可以正常工作,但是它只会更改当前表单的背景颜色,我将如何更改它,以便它可以同时更改项目中所有表单(例如表单1,2和3)的背景颜色。

3 个答案:

答案 0 :(得分:1)

我将创建一个名为BackColor的设置。为此,请执行以下操作:

Project -> Properties -> Settings.

然后创建设置:

Put the Name you'd like

Type as String

Scope as User

然后在您的代码中输入以下内容:

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

然后在每次加载表格时都输入以下代码:

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

答案 1 :(得分:0)

如果使用的是MDI父表单,则可以遍历所有子表单并更改backColor。

答案 2 :(得分:0)

在您的项目中添加一个模块,然后创建一个全局变量来保存所选的颜色:

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

当您选择一种新颜色时,将其存储在那里。另外,通过Application.OpenForms循环浏览所有打开的表单,并更改其颜色:

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

对于所有表单,在Load()事件中添加一行,将颜色设置为当前颜色。这样一来,新表格也将以当前颜色加载:

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