Calling AutoCAD commands from .NET
In this earlier entry I showed some techniques for calling AutoCAD commands programmatically from ObjectARX and from VB(A). Thanks to Scott Underwood for proposing that I also mention calling commands from .NET, and also to Jorge Lopez for (in a strange coincidence) pinging me via IM this evening with the C# P/Invoke declarations for ads_queueexpr() and acedPostCommand(). It felt like the planets were aligned... :-)
Here are some ways to send commands to AutoCAD from a .NET app:
- SendStringToExecute from the managed document object
- SendCommand from the COM document object
- acedPostCommand via P/Invoke
- ads_queueexpr() via P/Invoke
Here's some VB.NET code - you'll need to add in a COM reference to AutoCAD 2007 Type Library in addition to the standard .NET references to acmgd.dll and acdbmgd.dll.
Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.Interop
Public Class SendCommandTest
Private Declare Auto Function ads_queueexpr Lib "acad.exe" _
(ByVal strExpr As String) As Integer
Private Declare Auto Function acedPostCommand Lib "acad.exe" _
Alias "?acedPostCommand@@YAHPB_W@Z" _
(ByVal strExpr As String) As Integer
<CommandMethod("TEST1")> _
Public Sub SendStringToExecuteTest()
Dim doc As Autodesk.AutoCAD.ApplicationServices.Document
doc = Application.DocumentManager.MdiActiveDocument
doc.SendStringToExecute("_POINT 1,1,0 ", False, False, True)
End Sub
<CommandMethod("TEST2")> _
Public Sub SendCommandTest()
Dim app As AcadApplication = Application.AcadApplication
app.ActiveDocument.SendCommand("_POINT 2,2,0 ")
End Sub
<CommandMethod("TEST3")> _
Public Sub PostCommandTest()
acedPostCommand("_POINT 3,3,0 ")
End Sub
<CommandMethod("TEST4")> _
Public Sub QueueExprTest()
ads_queueexpr("(command""_POINT"" ""4,4,0"")")
End Sub
End Class
In case you're working in C#, here are the declarations of acedPostCommand() and ads_queueexpr() that Jorge sent to me:
[DllImport("acad.exe", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.Cdecl)]
extern static private int ads_queueexpr(string strExpr);
[DllImport("acad.exe", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.Cdecl,
EntryPoint = "?acedPostCommand@@YAHPB_W@Z")]
extern static private int acedPostCommand(string strExpr);
You'll need to specify:
using System.Runtime.InteropServices;
to get DllImport to work, of course.