-1

I am using C# windows forms and I'm having a problem. I have a form which I want to change the background of, however, I want to do so from a second form. The second for has a button which when pressed, the background of the first form changes. Here is my code First Form:

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

Second Form:

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.TransparencyKey = Color.Turquoise;
            frm1.BackColor = Color.Turquoise;
        }  
    }
}

The button is supposed to turn the first form transparent. This however, does not work. Am I missing something? Thank you!

Jimi
  • 29,621
  • 8
  • 43
  • 61
Skantzy
  • 113
  • 8
  • Yes: `Form1 frm1 = new Form1();` => `Form1` is a new Form instance, not the one that created and opened your `Form2` instance. So, you're changing the background color of a Form instance that has never been shown. You need the current instance of Form1 to interact with it. You can find a lot of Q&A related to this topic. – Jimi May 19 '20 at 17:02
  • For example: [Interaction between forms — How to change a control of a form from another form?](https://stackoverflow.com/a/38769212/7444103) -- [Communicate between two windows forms in C#](https://stackoverflow.com/q/1665533/7444103) -- Also using the [Owner reference](https://stackoverflow.com/a/50161950/7444103). – Jimi May 19 '20 at 17:16

2 Answers2

0

You can do it using delegate and events or by implementing singleton in parent form.

Rajanikant Hawaldar
  • 314
  • 1
  • 5
  • 12
0

You can set the Form 2's owner to Form1. Then access it's properties that way.

Form 1

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

Form 2

private void button1_Click(object sender, EventArgs e)
{
    Form1 frm1 = (Form1)this.Owner;
    frm1.TransparencyKey = Color.Turquoise;
    frm1.BackColor = Color.Turquoise;
}  
preciousbetine
  • 2,959
  • 3
  • 13
  • 29