Okay so I know how to close the application completely but when I have multiple forms it tends to mess up my main form and cause bugs when I close my secondary forms. Can anyone help me with this problem?

// The bug I get is in Program.cs and it is with this line;
Application.Run(new Form1());

// The bug it tells me is occurring is:
// Cannot access a disposed object.
// Object name: 'ShapeContainer'.
// The way the user exits the form is by clicking a red spherical graphic;
// Also known as 'OvalShape' in the toolbox;

// This is the snippet that closes my current form;
void exitBrowser(object sender, EventArgs e)
        {
            this.Close();
        }

Any help to fix it is appreciated. As far as I know it's no application fatal but it pauses the debugging sessions when I exit the form.

Recommended Answers

All 17 Replies

Don't close the main form, just call Application.Exit().

Well, thing is, I don't want the entire application to close. Just the single form that I exit from. So application.exit(); won't work for it. I thought about it and tried it to confirm. Basically I need it to just close the form it's written into. Like this one is called "agBrowse" so like .NET should be, agBrowse.Close() or something like that, but with C# I was told it's this.Close(); Help? :(

Yes it it, or even better it to use:

this.Dispose();

The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.
Read here.

this.Dispose(); gave the same error as this.Close(); unfortunately.

Look. YOu have to create a Form_Closing even handler. Insite you do:

public Form2()
        {
            InitializeComponent();
            this.FormClosing+=new FormClosingEventHandler(Form1_FormClosing);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = false; 
            this.Dispose();
        }

Hope it helps,
Mitja

Unfortunately once again that didn't work either.

void exitBrowser(object sender, EventArgs e)
        {
            this.Close();
        }

        void agWebBrowserClose(object sender, FormClosingEventArgs myEvent)
        {
            myEvent.Cancel = false;
            this.Dispose();
        }

The form closes when I click on the red oval shape I've placed on the form. There is no exit button on the form. I removed the sizable border completely so it is a custom made exit, minimize, and maximize button this is for all of the forms.

I dont understand a think any more. How can be closing a window so hard?
Have you ever heard of "Google"? Well if you might did, try to use it. There is written every thing. I have no imagination left, sorry...

From what perspective are you closing the forms? That is, are you trying to close all of the forms from the main form, or are you just trying to close a secondary form when you are done with it? As in, you open the second form, do some stuff, then press a button or object to close the form.

Since you state you are getting errors saying you can't access a disposed object, you need to check to ensure you are not trying to do something with a form or items on a form after you've destroyed it.

Most likely, I think that you may be trying to access a piece of data on the secondary form after you've called "Close" or "Dispose" on it.

void exitBrowser(object sender, EventArgs e)
        {
            this.Close();
        }

        void ovalShape3_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        void agWebBrowserClose(object sender, FormClosingEventArgs myEvent)
        {
            myEvent.Cancel = false;
            this.Dispose();
        }

That's the order it's all in, this is the very bottom of the source for the secondary form. To answer your question, yes it's a secondary form that I'm discarding after I'm done with it. I'm using Application.Exit(); for the main form so I can close it all from there. But I want the secondary forms to basically close just themselves not the entire program.

Now does the order of the functions matter? I can't really figure it out other than that. That's a little more progress towards fixing the bug. As far as I know it's not a fatal bug it's just a hiccup that stalls the application and then goes back to the main window. But then again I haven't built the application for actual full use testing. I just use the debugger to test it.

Okay just tested it as a .exe and this is the error message along with details:

Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.

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

See the end of this message for details on invoking 
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'ShapeContainer'.
   at System.Windows.Forms.Control.CreateHandle()
   at System.Windows.Forms.Control.get_Handle()
   at System.Windows.Forms.Control.PointToScreen(Point p)
   at Microsoft.VisualBasic.PowerPacks.ShapeContainer.OnMouseClick(MouseEventArgs e)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ContainerControl.WndProc(Message& m)
   at System.Windows.Forms.UserControl.WndProc(Message& m)
   at Microsoft.VisualBasic.PowerPacks.ShapeContainer.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4952 (win7RTMGDR.050727-4900)
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
----------------------------------------
agDev Sharp
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/Users/*%20*/Documents/Visual%20Studio%202010/Projects/agDev%20Sharp/agDev%20Sharp/bin/Debug/agDev%20Sharp.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Configuration
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
Microsoft.VisualBasic.PowerPacks.Vs
    Assembly Version: 10.0.0.0
    Win32 Version: 10.0.30319.1
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualBasic.PowerPacks.Vs/10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.PowerPacks.Vs.dll
----------------------------------------
Microsoft.VisualBasic
    Assembly Version: 8.0.0.0
    Win32 Version: 8.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualBasic/8.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

That's really all the info I have guys sorry. I'm new to C# and this is the first time I've ever had this much trouble closing a secondary form. When I click continue the program continues just fine, all the functions still seem to be working.

OK, can you post the code snip from your main form (or wherever you call your secondary form) along with the code for the secondary form (all of it)? Just by nature of the error statement:

************** Exception Text **************
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'ShapeContainer'.

You're trying to access something that's been blown away already.

You need to enable JIT debugging so you can see what line of your code is actually throwing the exception. Or run it in visual studio.

Okay so this first snippet is where I'm calling the secondary form.

void agBrowseMenu(object sender, EventArgs e)
        {
            agWebBrowser agWB = new agWebBrowser();
            agWB.Show();
        }

This is the entire snippet for the secondary form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Net.NetworkInformation;

namespace agDev_Sharp
{
    public partial class agWebBrowser : Form
    {
        public agWebBrowser()
        {
            InitializeComponent();
        }

        public const int buttonDown = 0xA1;
        public const int caption = 0x2;

        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        void sendURL(object sender, EventArgs e)
        {
            string myURL;
            myURL = label1.Text + urlPT1.Text + label2.Text + urlPT2.Text;

            this.webBrowser1.Url = new System.Uri(myURL, System.UriKind.Absolute);
        }

        void appMove(object sender, MouseEventArgs mouse)
        {
            if (mouse.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, buttonDown, caption, 0);
            }
        }

        void minimizeByDoubleClick(object sender, MouseEventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        void minimizeApp(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        void exitBrowser(object sender, EventArgs e)
        {
            this.Close();
        }

        void agWebBrowserClose(object sender, FormClosingEventArgs myEvent)
        {
            myEvent.Cancel = false;
            this.Dispose();
        }
    }
}

Still confused. :(

One last thing - please post the code for the Windows Forms Designer-generated code. The file should be something list "agWebBrowser.Designer.cs". The code you've posted so far doesn't shed any light on "ShapeContainer".

namespace agDev_Sharp
{
    partial class agWebBrowser
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(agWebBrowser));
            this.rectangleShape1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
            this.shapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
            this.ovalShape3 = new Microsoft.VisualBasic.PowerPacks.OvalShape();
            this.ovalShape2 = new Microsoft.VisualBasic.PowerPacks.OvalShape();
            this.ovalShape1 = new Microsoft.VisualBasic.PowerPacks.OvalShape();
            this.webBrowser1 = new System.Windows.Forms.WebBrowser();
            this.urlPT1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.urlPT2 = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // rectangleShape1
            // 
            this.rectangleShape1.BorderColor = System.Drawing.Color.Black;
            this.rectangleShape1.FillColor = System.Drawing.Color.Gray;
            this.rectangleShape1.FillGradientColor = System.Drawing.Color.Black;
            this.rectangleShape1.FillGradientStyle = Microsoft.VisualBasic.PowerPacks.FillGradientStyle.Vertical;
            this.rectangleShape1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
            this.rectangleShape1.Location = new System.Drawing.Point(-2, 0);
            this.rectangleShape1.Name = "rectangleShape1";
            this.rectangleShape1.SelectionColor = System.Drawing.Color.Transparent;
            this.rectangleShape1.Size = new System.Drawing.Size(905, 24);
            this.rectangleShape1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.rectangleShape1_MouseDoubleClick);
            this.rectangleShape1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.rectangleShape1_MouseDown);
            // 
            // shapeContainer1
            // 
            this.shapeContainer1.Location = new System.Drawing.Point(0, 0);
            this.shapeContainer1.Margin = new System.Windows.Forms.Padding(0);
            this.shapeContainer1.Name = "shapeContainer1";
            this.shapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
            this.ovalShape3,
            this.ovalShape2,
            this.ovalShape1,
            this.rectangleShape1});
            this.shapeContainer1.Size = new System.Drawing.Size(900, 527);
            this.shapeContainer1.TabIndex = 0;
            this.shapeContainer1.TabStop = false;
            // 
            // ovalShape3
            // 
            this.ovalShape3.BorderColor = System.Drawing.Color.Yellow;
            this.ovalShape3.FillColor = System.Drawing.Color.SaddleBrown;
            this.ovalShape3.FillGradientColor = System.Drawing.Color.Goldenrod;
            this.ovalShape3.FillGradientStyle = Microsoft.VisualBasic.PowerPacks.FillGradientStyle.Vertical;
            this.ovalShape3.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
            this.ovalShape3.Location = new System.Drawing.Point(24, 3);
            this.ovalShape3.Name = "ovalShape3";
            this.ovalShape3.SelectionColor = System.Drawing.Color.Transparent;
            this.ovalShape3.Size = new System.Drawing.Size(17, 17);
            this.ovalShape3.Click += new System.EventHandler(this.ovalShape3_Click);
            // 
            // ovalShape2
            // 
            this.ovalShape2.BorderColor = System.Drawing.Color.Red;
            this.ovalShape2.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
            this.ovalShape2.FillGradientColor = System.Drawing.Color.Maroon;
            this.ovalShape2.FillGradientStyle = Microsoft.VisualBasic.PowerPacks.FillGradientStyle.Vertical;
            this.ovalShape2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
            this.ovalShape2.Location = new System.Drawing.Point(3, 3);
            this.ovalShape2.Name = "ovalShape2";
            this.ovalShape2.SelectionColor = System.Drawing.Color.Transparent;
            this.ovalShape2.Size = new System.Drawing.Size(17, 17);
            this.ovalShape2.Click += new System.EventHandler(this.exitBrowser);
            // 
            // ovalShape1
            // 
            this.ovalShape1.BorderColor = System.Drawing.Color.Lime;
            this.ovalShape1.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
            this.ovalShape1.FillGradientColor = System.Drawing.Color.Green;
            this.ovalShape1.FillGradientStyle = Microsoft.VisualBasic.PowerPacks.FillGradientStyle.Vertical;
            this.ovalShape1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Solid;
            this.ovalShape1.Location = new System.Drawing.Point(876, 3);
            this.ovalShape1.Name = "ovalShape1";
            this.ovalShape1.SelectionColor = System.Drawing.Color.Transparent;
            this.ovalShape1.Size = new System.Drawing.Size(17, 17);
            // 
            // webBrowser1
            // 
            this.webBrowser1.Location = new System.Drawing.Point(0, 51);
            this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
            this.webBrowser1.Name = "webBrowser1";
            this.webBrowser1.Size = new System.Drawing.Size(900, 444);
            this.webBrowser1.TabIndex = 1;
            this.webBrowser1.Url = new System.Uri("http://www.youtube.com/user/lxXTaCoXxl", System.UriKind.Absolute);
            // 
            // urlPT1
            // 
            this.urlPT1.Location = new System.Drawing.Point(83, 501);
            this.urlPT1.Name = "urlPT1";
            this.urlPT1.Size = new System.Drawing.Size(136, 20);
            this.urlPT1.TabIndex = 2;
            this.urlPT1.Text = "youtube";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(798, 501);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(90, 23);
            this.button1.TabIndex = 3;
            this.button1.Text = "Go To URL";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
            this.label1.Location = new System.Drawing.Point(12, 506);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 13);
            this.label1.TabIndex = 4;
            this.label1.Text = "http://www.";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
            this.label2.Location = new System.Drawing.Point(225, 504);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(35, 13);
            this.label2.TabIndex = 5;
            this.label2.Text = ".com/";
            // 
            // urlPT2
            // 
            this.urlPT2.Location = new System.Drawing.Point(266, 501);
            this.urlPT2.Name = "urlPT2";
            this.urlPT2.Size = new System.Drawing.Size(388, 20);
            this.urlPT2.TabIndex = 6;
            this.urlPT2.Text = "user/lxXTaCoXxl";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Eras Light ITC", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
            this.label3.Location = new System.Drawing.Point(395, 28);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(59, 20);
            this.label3.TabIndex = 7;
            this.label3.Text = "agWeb";
            // 
            // agWebBrowser
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.Black;
            this.ClientSize = new System.Drawing.Size(900, 527);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.urlPT2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.urlPT1);
            this.Controls.Add(this.webBrowser1);
            this.Controls.Add(this.shapeContainer1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "agWebBrowser";
            this.Text = "agWeb";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.agWebBrowserClose);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private Microsoft.VisualBasic.PowerPacks.RectangleShape rectangleShape1;
        private Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer1;
        private Microsoft.VisualBasic.PowerPacks.OvalShape ovalShape3;
        private Microsoft.VisualBasic.PowerPacks.OvalShape ovalShape2;
        private Microsoft.VisualBasic.PowerPacks.OvalShape ovalShape1;
        private System.Windows.Forms.WebBrowser webBrowser1;
        private System.Windows.Forms.TextBox urlPT1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox urlPT2;
        private System.Windows.Forms.Label label3;
    }
}

try this one;

Do not close form2 just hide it and leave it to form1 to close the application.
This is the code(by the way in my code form2 is the main form and form1 is the second form)

in the first form (form2) create a button to open the second form (form2)

public Form2()
        {
            InitializeComponent();
        }

        Form1 newform = new Form1();
        private void button1_Click(object sender, EventArgs e)
        {
            newform.ShowDialog();
        }

AND DO THIS IN THE SECOND FORM (form1 in my example)
In the second form i am not using button control i used rectangular shape

private void rectangleShape4_Click(object sender, EventArgs e)
        {
            
            this.Hide();

         }

THIS WORKS 100% any progress inform me.

System.Environment.Exit(0); Try this code, i was stuck same as you

commented: 3 year old thread, don't resurect old threads. -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.