开发者

Controls disposed second time form is opened

The first time I open one of my child forms from the main form it opens normally. If I close the first instance of the child form and then reopen it however I get a crash the first time I try to call CreateGraphics() outside of the OnPaint() method. The exception I get is: "Cannot access a disposed object. Object name: 'MyControlClass'."

I've set breakpoints to monitor what's going on. Dispose() is called as expected the first time I close the form. When I start the form the second time MyControlClass's constructor is called, and the Dispose method isn't called prior to the exception. At the point of the exception this is still valid. Because of that I'm wondering if somehow it's actually the static component of MyControlClass that ended up being disposed; not the instance object.

I am creating a new copy of the form each time the button to show it is called. MyChildForm is a member held by my mt parentform and is also used to prevent multiple copies of the form from being opened at once.

ShowMyForm()
{
    myChildForm = new myChildForm Form();
    myChildForm.FormClosed += myChildFormFormClosed;
开发者_如何学编程    myChildForm.Show();
}

private void myChildFormFormClosed(object sender, FormClosedEventArgs e)
{
    myChildForm = null;
}

The line of code that crashes: MyControlClass inherits from MyControlClassBase, which in turn inherits from MyControlClassBaseBase. This line of code is triggered by a mouse event in MyControlClassBase and is in MyControlClassBaseBase. The code after this would take a cached image of MyControl, display it using the newly created Graphics object, and then draw an overlay based on the mouse cursor position.

Graphics g = CreateGraphics();

PS Since I'm sure someone will ask: The rube goldberg in question is due to the utter fail that is fake 'transparency' in winforms in any but the most trivial cases and the fact that MyControlClass takes too long to paint to keep up with the mouse cursor; but that's a separate question entirely.


After a form is closed, it is disposed - meaning that it exists just to read fields.

If you want to show the same form again, create another instance or just hide it instead of closing.


MyForm f = new MyForm();
f.Show();
// After closed, it will be disposed.

So we need to do the same steps to show it again:

f = new MyForm();
f.Show();

Now you will get a brand new and identical form.


But to hide it when closed, you might need this code:

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        e.Cancel = true;

        Hide();
    }
}

Note that it will not work with modal forms. (ShowDialog();)
(Thanks to Sorax) This will also not work with MDI children.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜