简体   繁体   中英

Changing opacity of one form using a second form

So I want my form2's Trackbar to change the opacity of my form1 but it doesn't seem to get the job done?

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;

    }
}

You are not changing the opacity of your Form1, you are changing the opacity of a new Form1. You need to make sure you change the opacity of the form instance you want to change:

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;
    }
  }
}

Then when you create Form2, pass the instance of Form1 you want to change. For example from a button in your Form1:

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

Instead of creating a new form everytime use the id of the existing form:

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;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM