c# - 如何从另一种形式改变背景图像?

标签 c# winforms forms

我有两种形式,我想从第二种形式更改第一种形式的背景。我已经为 form2 中的 form1 和 button1 选择了背景图像,但没有任何反应。提前谢谢(Windows 窗体) 第一种形式:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.ShowDialog();
        }
    }
}

第二种形式:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form1 frm1 = new Form1();
            frm1.BackgroundImage = button1.BackgroundImage;
        }
    }
}

最佳答案

在您的第二个表单中,添加一个私有(private)成员,该成员将保存对第一个表单的引用:

private Form _form1 = null;

然后在 Form2 的构造函数中,允许传入该引用:

public Form2(Form form1)
{
    InitializeComponent();
    _form1 = form1;
}

现在,在该按钮单击处理程序中,您可以:

private void button1_Click(Object sender, EventArgs e)
{
    _form1.BackgroundImage = button1.BackgroundImage;
}

另一种方法是向 Form1 添加一个方法来接收要设置为背景的图像。假设 Form2 中存在相同的 _form1 引用,您将其添加到 Form1:

public void ChangeBGImage(Image bgImage)
{
    this.BackgroundImage = bgImage;
}

在 Form2 中,你称它为:

private void button1_Click(Object sender, EventArgs e)
{
    _form1.ChangeBGImage(button1.BackgroundImage);
}

关于c# - 如何从另一种形式改变背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23909937/

相关文章:

forms - 在表单或属性中定义日期步骤

python - Mechanize br.click_link() 和 br.follow_link() 之间的区别

c# - GridView 中的 Row_DataBound 或 Row_Created 事件

c# - 保存来自选择查询的值,然后在更新查询 SQL Server CE 中使用它们

c# - 根据 USPS 州缩写验证字符串

C# 是否可以将 groupBox 标题设为单选按钮?

C# - TableLayoutPanel 切断标签字符串

ruby-on-rails-3 - 防止用户导航和丢失更改的 Rails 3 表单助手?

c# - 从 Python 调用用 C# 编写的函数时,“NoneType”对象不可调用

c# - Windows Mobile 6.5 与 Windows Embedded Handheld 6.5 - 有何区别?