Autodesk Community Tips- ADNオープン
Autodesk Community Tipsではちょっとしたコツ、やり方、ショートカット、アドバイスやヒントを共有しています。

AutoCAD .NET API:アプリケーション実行コンテキスト下のコマンド実行

Issue

連続実行で図形を順番に開いて、処理、保存しようとしています。図面を順次開く必要があるので、定義コマンドに CommandFlags.Session フラグを指定してアプリケーション実行コンテキスト コマンドにしていますが、この実行コンテキストだと、 開いた図面に対して Editor.Command メソッドでコマンド実行させることが出来ません。 

 

次の C# コードでは、C:\temp フォルダ内の図面(.dwg)を順に開き、ZOOM コマンドを実行、図面を同じ名前で保存するものですが、ZOOM コマンドの実行で例外エラーになってしまいます。 

[CommandMethod("UpdateDrawings", CommandFlags.Session)]
public void UpdateDrawings()
{
    Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
    DocumentCollection docMgr = Application.DocumentManager;
    Document doc = null;
    try
    {
        string[] fnames = Directory.GetFiles(@"c:\temp", "*.dwg");
        foreach (string fname in fnames)
        {
            ed.WriteMessage("\n--- {0}", fname);
            doc = docMgr.Open(fname, false);
            Application.DocumentManager.MdiActiveDocument.Editor.Command("ZOOM", "E");
            doc.CloseAndSave(fname);
        }
    }
    catch (Autodesk.AutoCAD.Runtime.Exception ex)
    {
        ed.WriteMessage("\n ERROR:{0}", ex.Message);
    }
}

なにかよい方法はないでしょうか? 

 

Solution

プリケーション実行コンテキスト コマンド(CommandFlags.Session フラグ指定コマンド)では、Editor.Command メソッドを利用したコマンドの同期コマンド呼び出しは出来ません。

今回のようなケースでは、通常、Document.SendStringToExecute メソッドで非同期的に実行させたいコマンドを送信することで、便宜上、ドキュメント実行コンテキスト でコマンド実行する対応が考えられます。

また、実行する内容にもよりますが、AutoCAD .NET API 環境では、DocumentCollection.ExecuteInCommandContextAsync メソッドを用いることで、アプリケーション実行コンテキスト コマンド内でドキュメント実行コンテキストを非同期的(Async/Await)にコマンド実行することも可能です。

[CommandMethod("UpdateDrawings", CommandFlags.Session)]
public async void UpdateDrawings()
{
    Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
    DocumentCollection docMgr = Application.DocumentManager;
    Document doc = null;
    try
    {
        string[] fnames = Directory.GetFiles(@"c:\temp", "*.dwg");
        foreach (string fname in fnames)
        {
            ed.WriteMessage("\n--- {0}", fname);
            doc = docMgr.Open(fname, false);
            await Application.DocumentManager.ExecuteInCommandContextAsync(
                async (obj) =>
                {
                    await Application.DocumentManager.MdiActiveDocument.Editor.CommandAsync("ZOOM", "E");
                },
                null
            );
            doc.CloseAndSave(fname);
        }
    }
    catch (Autodesk.AutoCAD.Runtime.Exception ex)
    {
        ed.WriteMessage("\n ERROR:{0}", ex.Message);
    }
}

UpdateDrawings.gif

同様に、 スクリプト(.scr)を用いた処理も考えることも出来ます。

ご参考:AutoCAD 雑学:図面のサムネイル画像 - Technology Perspective from Japan (typepad.com)