0
votes

I'm developing a WinForm app. I have two forms, form1 is the main window and form2 for settings. I'm using this method for interaction between both forms:

code in form1:

   private void startForm2_Click(object sender, EventArgs e)
   {
       Form2 frm = new Form2(this);
       frm.Show();
   }
   public void changeFontSize() //promenq razmera na shrifta
   {
       ...
   }

code in form2:

Form1 F1 = new Form1();

public Form2(Form1 aF1)
{
    InitializeComponent();
    F1 = aF1;
}
private void button1_Click(object sender, EventArgs e)
{
    F1.changeFontSize();
}

When I close form2, it throws an exception:

Cannot access a disposed object. Object name: 'Icon'.

in line

protected override void Dispose(bool disposing)
{
    ChangeClipboardChain(this.Handle, nextClipboardViewer); // Clean up any resources being used.
    ...

in Form1.Designer.cs file.

2

2 Answers

1
votes

The Form F1 = new Form1(); field should be just Form F1;. Right now you are creating a new Form1 instance which is not used at all (you overwrite the field in the constructor), and it will be disposed and collected non-deterministically by the GC.

It's most likely that this "hidden" instance is the one which creates the problem while being disposed.

You can also try moving that method inside the Form.FormClosed event handler, although it certainly seems to fit the Dispose method better.

0
votes

You should Dispose all resources on Form2 closing event.