イベントの登録場所と登録方法を説明します。
イベントの使用は、2 つの手順で処理されます。最初に、イベントの通知を処理する関数が必要です。この関数は次の 2 つのパラメータを取得します。最初のパラメータはイベント通知の「送信者」を示す Object で、2 番目はイベントに固有のイベント引数が含まれているイベント固有のオブジェクトです。 たとえば、DocumentSavingAs イベントを登録するには、イベント ハンドラは DocumentSavingAsEventArgs オブジェクトである 2 番目のパラメータを取る必要があります。
イベントの使用についての 2 番目は、Revit を使用してイベントを登録することです。これは、ControlledApplication パラメータからOnStartup()関数を使用して即時に、または Revit の起動後にいつでも実行できます。イベントは、外部アプリケーションと同様に外部コマンドに登録することができますが、外部コマンドが同じ外部コマンド内でイベントを登録および登録を解除しない限り推奨しません。イベントへの登録とイベントからの登録解除はメイン スレッドで実行中に行われる必要があります。外部アプリケーションが有効な API コンテキストの外部からイベントに登録(またはイベントから登録解除)しようとすると、例外がスローされます。
次の例では、DocumentOpened イベントを登録し、イベントがトリガされたときに、このアプリケーションがプロジェクトのアドレスを設定しています。
|
コード領域 24-1: ControlledApplication.DocumentOpened を登録 |
public class Application_DocumentOpened : IExternalApplication
{
/// <ExampleMethod>
/// <summary>
/// Implement this method to subscribe to event.
/// </summary>
public Result OnStartup(UIControlledApplication application)
{
try
{
// Register event.
application.ControlledApplication.DocumentOpened += new EventHandler
<Autodesk.Revit.DB.Events.DocumentOpenedEventArgs>(application_DocumentOpened);
}
catch (Exception)
{
return Result.Failed;
}
return Result.Succeeded;
}
public Result OnShutdown(UIControlledApplication application)
{
// remove the event.
application.ControlledApplication.DocumentOpened -= application_DocumentOpened;
return Result.Succeeded;
}
public void application_DocumentOpened(object sender, DocumentOpenedEventArgs args)
{
// get document from event args.
Document doc = args.Document;
// Following code snippet demonstrates support of DocumentOpened event to modify the model.
// Because DocumentOpened supports model changes, it allows user to update document data.
// Here, this sample assigns a specified value to ProjectInformation.Address property.
// User can change other properties of document or create(delete) something as he likes.
//
// Please note that ProjectInformation property is empty for family document.
// So please don't run this sample on family document.
using (Transaction transaction = new Transaction(doc, "Edit Address"))
{
if (transaction.Start() == TransactionStatus.Started)
{
doc.ProjectInformation.Address =
"United States - Massachusetts - Waltham - 1560 Trapelo Road";
transaction.Commit();
}
}
}
}
|