Search code examples
c#winformspopupbackground-imagemdiparent

Winforms c# Changing background Image of Parent form from popup form


I have two forms a & b. Form a is main form and on one of its button click event form b is shown as a small window. On the popup (form b), I have an option to select image. What I need to do is when I click on save button of popup (form b), form a (main form's) background image should be set to image selected via popup form (b).

I have tried following code but this.Parent, this.Owner all is returning null for popup form (b). I have specified form a as MDI.

this.Owner.BackgroundImage = pictureBoxBackground.Image;
this.Parent.BackgroundImage = pictureBoxBackground.Image;

Solution

  • What I would do is have a public Image property like so inside Form b:

    private Image image;
    public Image SelectedImage
    {
        get
        {
            return image;
        }
    }
    

    And then I would add a button_Click event (or whatever you use to confirm selection). This event would close the form and set the return image.

    private void Button_Click(object sender, EventArgs e)
    {
        image = [Whatever Image variable that you want to return];
        Close();
    }
    

    Making FormB look like this.

    public class FormB : Form
    {
        //[...]Stuff
        private Image image;
        public Image SelectedImage
        {
            get
            {
                return image;
            }
        }
        private void Button_Click(object sender, EventArgs e)
        {
            image = [Whatever Image variable that you want to return];
            Close();
        }
    }
    

    And finally, to use this for the background image of FormA. Simply have the following procedure.

    public void ChangeBackground()
    {
        FormB b = new FormB();
        b.ShowDialog();
        this.BackgroundImage = b.SelectedImage;
    }