COM ベースのイベントを登録する(.NET)

AutoCAD COM オートメーション ライブラリには、.NET API にはない固有のイベントがいくつかあります。COM ライブラリに含まれるイベントを登録することは、VB または VBA を使用してイベントを初期化することとは異なります。イベント ハンドラをイベントに登録するには、VB.NET の AddHandler ステートメントまたは C# の += 演算子を使用します。イベント ハンドラには、イベントが発生したときに呼び出されるプロシージャのアドレスが必要です。

COM ベースのイベントを登録する

次の例では、COM 相互運用機能を使用して BeginFileDrop イベントを登録する方法を示します。BeginFileDrop イベントは、AutoCAD COM オートメーション ライブラリの Application オブジェクトと関連付けられます。コマンドが AutoCAD にロードされた後、コマンド プロンプトで AddCOMEvent を入力し、DWG ファイルを図面ウィンドウにドラッグしてドロップします。メッセージ ボックスに続行を問い合わせるメッセージが表示されます。イベント ハンドラを削除するには、RemoveCOMEvent コマンドを使用します。

C# の例

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;
  }
}