In this post, I use some code to show what happen when AutoCAD is closed by user (via clicking "Exit" menu, click "x" on AutoCAD main window, or issue command "quit").
In order to track what happen during the AutoCAD closing process, various event handlers are attached to drawings that were open when AutoCAD starts closing, drawing databases and AutoCAD application itself. Because AutoCAD is closing, AutoCAD test window cannot be used to show message regarding the closing process, I created a TextLogger class that holds all closing messages captured in various event handlers and save them to a text file at the end of Terminate() call.
Here is the code of class TextLogger:
Code Snippet
- using System.Text;
- using System.IO;
- namespace IExtensionApp.Terminate
- {
- public class TextLogger
- {
- private StringBuilder _textToWrite;
- private string _logFile;
- public TextLogger(string fileName)
- {
- _logFile = fileName;
- _textToWrite = new StringBuilder();
- }
- public void AddMessageText(string text)
- {
- //Append new text message at the end of StringBuilder
- //with "|" for separating from previous
- _textToWrite.Append(text + "|");
- }
- public void SaveToFile()
- {
- //remove "|" at the end
- if (_textToWrite.Length > 1) _textToWrite.Length -= 1;
- //Split message into array
- string[] output=_textToWrite.ToString().Split(new char[]{'|'});
- //Write to file
- File.WriteAllLines(_logFile,output);
- }
- }
- }
Here is the code that runs an AutoCAD:
Code Snippet
- using System;
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.EditorInput;
- using Autodesk.AutoCAD.Runtime;
- [assembly: CommandClass(typeof(IExtensionApp.Terminate.MyCommands))]
- [assembly: ExtensionApplication(typeof(IExtensionApp.Terminate.MyCommands))]
- namespace IExtensionApp.Terminate
- {
- public class MyCommands : IExtensionApplication
- {
- private static TextLogger _logger = null;
- private const string LOG_FILE_NAME=@"E:\Temp\AcadClosingEvents.txt";
- private static DocumentCollection _dwgs = null;
- private static Form1 _disposedForm = null;
- private static Form2 _hiddenForm = null;
- public void Initialize()
- {
- Document dwg = Application.DocumentManager.MdiActiveDocument;
- Editor ed = dwg.Editor;
- try
- {
- _logger = new TextLogger(LOG_FILE_NAME);
- _dwgs = Application.DocumentManager;
- //Add event handler on DocumentCollection object
- _dwgs.DocumentToBeDestroyed +=
- new DocumentCollectionEventHandler(_dwgs_DocumentToBeDestroyed);
- _dwgs.DocumentDestroyed +=
- new DocumentDestroyedEventHandler(_dwgs_DocumentDestroyed);
- _dwgs.DocumentCreated +=
- new DocumentCollectionEventHandler(_dwgs_DocumentCreated);
- //Add application event handler
- Application.QuitWillStart +=
- new EventHandler(Application_QuitWillStart);
- Application.BeginQuit +=
- new EventHandler(Application_BeginQuit);
- }
- catch (System.Exception ex)
- {
- ed.WriteMessage("\nAcad Addin initializing error: {0}\n", ex.Message);
- }
- }
- void _dwgs_DocumentCreated(object sender, DocumentCollectionEventArgs e)
- {
- Document dwg = e.Document;
- //Add event handler on Document to track document closing
- dwg.CloseWillStart += new EventHandler(dwg_CloseWillStart);
- dwg.BeginDocumentClose +=
- new DocumentBeginCloseEventHandler(dwg_BeginDocumentClose);
- //Database events
- Database db = dwg.Database;
- //Add event handler to track when database is to be removed from momery
- db.DatabaseToBeDestroyed += new EventHandler(db_DatabaseToBeDestroyed);
- }
- void db_DatabaseToBeDestroyed(object sender, EventArgs e)
- {
- Database db = sender as Database;
- string msg =
- "Database in document " + db.Filename + " is about to be destroyed";
- _logger.AddMessageText(msg);
- }
- void dwg_BeginDocumentClose(object sender, DocumentBeginCloseEventArgs e)
- {
- Document d = sender as Document;
- string msg = "Document " + d.Name + " closing begins";
- _logger.AddMessageText(msg);
- }
- void dwg_CloseWillStart(object sender, EventArgs e)
- {
- Document d=sender as Document;
- string msg = "Document " + d.Name + " is abount to be closed";
- _logger.AddMessageText(msg);
- }
- void Application_QuitWillStart(object sender, EventArgs e)
- {
- string msg = "Autodesk is about to quit";
- _logger.AddMessageText(msg);
- }
- void Application_BeginQuit(object sender, EventArgs e)
- {
- string msg = "Quiting Autodesk begins";
- _logger.AddMessageText(msg);
- }
- void _dwgs_DocumentToBeDestroyed(object sender, DocumentCollectionEventArgs e)
- {
- string msg = "Document " + e.Document.Name + " is about to be destroyed";
- _logger.AddMessageText(msg);
- }
- void _dwgs_DocumentDestroyed(object sender, DocumentDestroyedEventArgs e)
- {
- string msg = "Document " + e.FileName + " has been destroyed";
- _logger.AddMessageText(msg);
- }
- public void Terminate()
- {
- string msg;
- //Log the beginning of Terminate() call
- msg = "Terminate() is called";
- _logger.AddMessageText(msg);
- //Log if there is still Document open when Terminate() begins
- msg = "Document count is " + _dwgs.Count;
- _logger.AddMessageText(msg);
- //Proves that although the form itself is disposed,
- //its reference is still in scope when Terminate() runs
- if (_disposedForm.IsDisposed)
- {
- msg = "Form1 is disposed, but its reference is still alive";
- _logger.AddMessageText(msg);
- }
- //Proves that the hidden form object is still alive
- //when terminate() executed.
- if (_hiddenForm != null)
- {
- if (!_hiddenForm.IsDisposed)
- {
- msg = "Form2 has not been disposed";
- _logger.AddMessageText(msg);
- //Calling Dispose() is not necessary in most cases,
- //after all it will be gone with the hosting AutoCAD
- //process. However, if the form object holds other
- //resources outside AutoCAD open, such as files, data
- //connections, graphic devices...(which could be bad
- //practice in most cases, if a form holds these kind
- //of resources open for entire AutoCAD session), then
- //you may want to call Dispose() here with the
- //appropriate overridden Form.Dispose().
- _hiddenForm.Dispose();
- }
- }
- //Log Terminate() completion
- msg = "Terminate() call is completed";
- _logger.AddMessageText(msg);
- //Save logs into log file.
- _logger.SaveToFile();
- }
- /// <summary>
- /// Open 2 modeless forms. Close one (i.e. disposed), so that its
- /// reference is still in scope in the Acad session, but the form
- /// object itself is gone (disposed); Close the other
- /// one as invisible (i.e. handling Form_Closing event, and cancel
- /// its closing, set it to invisible instead, so that the form object
- /// and its reference variable stays alive in the Acad session
- /// </summary>
- [CommandMethod("ShowForms")]
- public static void ShowForms()
- {
- if (_disposedForm == null)
- {
- _disposedForm = new Form1();
- }
- else if (_disposedForm.IsDisposed)
- {
- _disposedForm = new Form1();
- }
- Application.ShowModelessDialog(_disposedForm);
- if (_hiddenForm == null)
- {
- _hiddenForm = new Form2();
- }
- Application.ShowModelessDialog(_hiddenForm);
- }
- }
- }
I used 2 forms, which are shown in AutoCAD as modeless dialog box. Both forms are very simple with only one button "Close" on the forms. Clicking the button triggers this.Close() method.
In order to make a point in Terminate() process, I let one form to be closed normally (i.e. when call Form.Close() on a modeless form, the form is disposed). I let the other form change to invisible when Form.Close() is called by handling Form_Closing event, like this:
Code Snippet
- private void Form2_FormClosing(object sender, FormClosingEventArgs e)
- {
- e.Cancel = true;
- this.Visible = false;
- }
Build the code into an assembly (dll file) with VS. Now it is ready to run the code and see what happen during AutoCAD closing process. I do these steps:
1. Start AutoCAD;
2. Netload the DLL file;
3. Open a few drawing. In my case, I open 3 saved drawing: drawing1, drawing 2 and drawing 3 from a folder;
4. Execute command "ShowForms" to bring up the 2 modeless forms, then cloce them by clicking their "Close" button;
5. Close AutoCAD without closing drawing first by going to big "A" button->Exit AutoCAD, or simply click "x" on main AutoCAD window;
6. Open the log file ("E:\Temp\AcadClosingEvents.txt") in NotePad to see what have been logged.
Here is the content of the log file:
Document C:\Users\norm\Documents\Drawing3.dwg closing begins
Document C:\Users\norm\Documents\Drawing3.dwg closing begins
Document C:\Users\norm\Documents\Drawing3.dwg is about to be destroyed
Database in document C:\Users\norm\Documents\Drawing3.dwg is about to be destroyed
Document C:\Users\norm\Documents\Drawing3.dwg has been destroyed
Document C:\Users\norm\Documents\Drawing2.dwg closing begins
Document C:\Users\norm\Documents\Drawing2.dwg closing begins
Document C:\Users\norm\Documents\Drawing2.dwg is about to be destroyed
Database in document C:\Users\norm\Documents\Drawing2.dwg is about to be destroyed
Document C:\Users\norm\Documents\Drawing2.dwg has been destroyed
Document C:\Users\norm\Documents\Drawing1.dwg closing begins
Document C:\Users\norm\Documents\Drawing1.dwg closing begins
Document C:\Users\norm\Documents\Drawing1.dwg is about to be destroyed
Database in document C:\Users\norm\Documents\Drawing1.dwg is about to be destroyed
Document C:\Users\norm\Documents\Drawing1.dwg has been destroyed
Quiting Autodesk begins
Autodesk is about to quit
Terminate() is called
Document count is 0
Form1 is disposed, but its reference is still alive
Form2 has not been disposed
Terminate() call is completed
Form the messages logged in various event handlers we can see:
1. After AutoCAD receives "quit" command, if there is open drawing, AutoCAD will attempt to close all open drawings, which may trigger prompting message asking user to save changes. The quiting process can be cancelled if user click "Cancel" button in the message box.
2. After all open drawing documents are closed, AutoCAD starts quiting, it is only then the IExtensionApplication.Terminate() is called. That is, one cannot do any document/database related clean-up task in Terminate(), because all document is gone. However, DocumentCollection object is still reachable, but it does not contain document any more.
3. Custom object declared at command class level may or may not exist when Terminate() is executed. In my example, since the 2 forms is called in a static command method, thus, they are instantiated at AutoCAD session level, not per document level. Since they are instantiated in static method, they also has to be declared as "static". About the difference of "static" command method and "non-static" command method, one of my previous post discussed it in more details here.
4. As I commented in the code, what clean-up tasks we need to do in the Terminate() method depends on what our custom AutoCAD Addin does, what external (to AutoCAD) resources the code uses and how they are used. If your code have to do some clean-up in Terminate(), such as opened database connection, opened data file...You may want to look back to the code to answer the question: why your code holds those resource until the end of AutoCAD session? In most cases, it might not be a good practice. So, in real practice, there aren't many cases one has to stuff Terminate() method with a lot of code, if things are done correctly.