Get the name of the active AutoCAD document with .NET

Here's a little sample code to detect if AutoCAD is running. If it does, it displays the full path of the active drawing.

The code use COM (out of process).

VB.NET

Imports System.Runtime.InteropServices

Module Module1

    Sub Main()
        Try
            Dim acad = Marshal.GetActiveObject("AutoCAD.Application")
            Dim activeDocument = acad.ActiveDocument
            MsgBox("Le chemin complet du document actif est : " & activeDocument.FullName)
        Catch ex As COMException
            Const MK_E_UNAVAILABLE As Integer = &H800401E3
            If ex.ErrorCode = MK_E_UNAVAILABLE Then
                MsgBox("AutoCAD n'est pas en cours d'exécution.")
            Else
                Throw
            End If
        End Try
    End Sub

End Module

C#

try {
    dynamic acad = Marshal.GetActiveObject("AutoCAD.Application");
    dynamic activeDocument = acad.ActiveDocument;
    MessageBox.Show("Le document actif est : " + activeDocument.FullName);
} catch (COMException ex) {
    const uint MK_E_UNAVAILABLE = 0x800401e3;
    if ((uint)ex.ErrorCode == MK_E_UNAVAILABLE) {
        MessageBox.Show("AutoCAD n'est pas en cours d'exécution.");
    } else {
        throw;
    }
}

English

Add new comment