使用第二种形式更改一个表单的不透明度

时间:2013-05-25 10:15:33

标签: c# winforms

所以我希望我的form2 Trackbar改变我的form1的不透明度,但它似乎没有完成工作?

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

    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        Form1 frm1 = new Form1();

        frm1.Opacity = trackBar1.Value * 000.1d;

    }
}

2 个答案:

答案 0 :(得分:1)

您没有更改 Form1的不透明度,而是更改 new Form1的不透明度。您需要确保更改要更改的表单实例的不透明度:

public partial class Form2 : Form
{
    private Form1 form;

    public Form2(Form1 form)
    {
        InitializeComponent();
        this.form = form;
    }

    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        form.Opacity = trackBar1.Value * 000.1d;
    }
  }
}

然后,当您创建Form2时,传递要更改的Form1的实例。例如,从Form1中的按钮:

public void opacityChangeButton_Click(object sender , EventArgs e)
{
    Form2 opacityChangeForm = new Form2(this);
    opacityChangeForm.ShowDialog();
}

答案 1 :(得分:0)

不是每次创建新表单而是使用现有表单的id:

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

    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        // Do not create a new form: Form1 frm1 = new Form1();

        // Use name of original form
        whateverVariableyourCreateedForYourForm.Opacity = trackBar1.Value * 000.1d;

    }
}