从另一个表单更改表单字体颜色

本文关键字:表单 字体 颜色 另一个 | 更新日期: 2023-09-27 18:30:30

我有一个表单,我们称之为formMain,它有一个菜单,可以打开另一个叫做formColors的表单。现在,当formColors打开时,它具有标有颜色的单选按钮,即红色

如何将formMain的字体颜色更改为我在formColors中选择的任何选项?

从另一个表单更改表单字体颜色

formColors中创建一个Event,并在formMain中订阅它,或者正如Hans Passant指出的那样,您可以使用公共属性和Forms DialogResult Property,这将是首选的方法。

WinForm 对话框结果示例

表格1

public partial class Form1 : Form
{
    Form2 frm2;
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        frm2 = new Form2();
        if (frm2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            this.BackColor = frm2.formColor;
        frm2.Close();   
    }
}

表格2

public partial class Form2 : Form
{
    Color newColor;
    public Form2()
    {
        InitializeComponent();
    }
    public Color formColor
    {
        get { return this.newColor; }
        set { this.newColor = value; }
    }
    private void btnRed_Click(object sender, EventArgs e)
    {
        newColor = Color.Red;
    }
    private void btnBlue_Click(object sender, EventArgs e)
    {
        newColor = Color.Blue;
    }
    private void btnOk_Click(object sender, EventArgs e)
    {
        DialogResult = System.Windows.Forms.DialogResult.OK;
    } 
}

WinForm 事件示例:

表格1:

public partial class Form1 : Form
{
    Form2 frm2 = new Form2();
    public Form1()
    {
        InitializeComponent();
        frm2.ColorEvent += new ColorEventHandler(frm2_ColorEvent);
    }
    void frm2_ColorEvent(object sender, ColorEventArgs e)
    {
        this.BackColor = e.formColor;
    }
    private void button1_Click(object sender, EventArgs e)
    {
        frm2.ShowDialog();
    }
}

表格2:

public delegate void ColorEventHandler(object sender, ColorEventArgs e); 
public partial class Form2 : Form
{
    public event ColorEventHandler ColorEvent;
    public Form2()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        ColorEventArgs newColor = new ColorEventArgs();
        newColor.formColor=Color.Red;
        ColorEvent(this, newColor);
    }

}

颜色事件类

public class ColorEventArgs : EventArgs
{
    private Color newColor;
    public Color formColor
    {
        get { return this.newColor; }
        set { this.newColor = value; }
    }
}