Register COM Based Events (.NET)

The AutoCAD COM Automation library offers some unique events that are not found in the .NET API. Registering events that are in a COM library is different than how you would initialize an event using VB or VBA. You use the VB.NET AddHandler statement or the C# += operator to reigister an event handler with the event. The event handler requires the address of the procedure in which should be called when the event is raised.

Register a COM based event

This example demonstrates how to register the BeginFileDrop event using COM interop. The BeginFileDrop event is associated with the Application object of the AutoCAD COM Automation library. Once the commands are loaded into AutoCAD, enter AddCOMEvent at the Command prompt and then drag and drop a DWG file into the drawing window. A message box will be displayed prompting you to continue. Use the RemoveCOMEvent command to remove the event handler.

C# Example

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
 
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
 
// Global variable for AddCOMEvent and RemoveCOMEvent commands
AcadApplication acAppCom;
 
[CommandMethod("AddCOMEvent")]
public void AddCOMEvent()
{
  // Set the global variable to hold a reference to the application and
  // register the BeginFileDrop COM event
  acAppCom = Application.AcadApplication as AcadApplication;
  acAppCom.BeginFileDrop += 
      new _DAcadApplicationEvents_BeginFileDropEventHandler(appComBeginFileDrop);
}
 
[CommandMethod("RemoveCOMEvent")]
public void RemoveCOMEvent()
{
  // Unregister the COM event handle
  acAppCom.BeginFileDrop -= 
      new _DAcadApplicationEvents_BeginFileDropEventHandler(appComBeginFileDrop);
  acAppCom = null;
}
 
public void appComBeginFileDrop(string strFileName, ref bool bCancel)
{
  // Display a message box prompting to continue inserting the DWG file
  if (System.Windows.Forms.MessageBox.Show("AutoCAD is about to load " + strFileName +
                                       "\nDo you want to continue loading this file?",
                                       "DWG File Dropped",
                                       System.Windows.Forms.MessageBoxButtons.YesNo) == 
                                       System.Windows.Forms.DialogResult.No)
  {
      bCancel = true;
  }
}