简体   繁体   中英

ObjectDisposedException: Cannot access a disposed object

I am trying to create a program for my project in school, and I have come across a problem. I am using LinqPad premium and when I launch the program it starts fine. However, when I try and start it for the second or third time it throws the exception: "ObjectDisposedException: Cannot access a disposed object." "Object name: 'Form'."

Here is my code:

void Main()
{
    MenuClass.Main();
}
class MenuClass
{
    static public Form MenuWindow = new Form();
    static public void Main()
    {
        MenuWindow.Height = 300;
        MenuWindow.Width = 300;
        MenuWindow.Text = "Menu";

        Button btnPlay = new Button();
        btnPlay.Left = 10;
        btnPlay.Top = 290;
        btnPlay.Text = "Reset";
        //btnPlay.Click += btnReset_click;

        Button btnTakeTurn = new Button();
        btnTakeTurn.Left = 10;
        btnTakeTurn.Top = 270;
        btnTakeTurn.Text = "Take Turn";
        //btnTakeTurn.Click += btnTakeTurn_click;

        Graphics g = MenuWindow.CreateGraphics();

        MenuWindow.Controls.Add(btnPlay);
        MenuWindow.Controls.Add(btnTakeTurn);

        //MenuWindow.Paint += f_Paint;

        MenuWindow.Show();
    }
}

The error occurs where it says "Graphics g = MenuWindow.CreateGraphics();" and also when i take that out it does it on "MenuWindow.Show();"

Please help, as I am powerless in this situation.

Change:

static public Form MenuWindow = new Form();
static public void Main()
{

to:

static public void Main()
{
    var MenuWindow = new Form();

to ensure that each invocation generates a new form.

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