Saturday, July 21, 2012

How to send AutoCAD commands via C#?

I’m working on an AutoCAD plugin in .Net (C#) and  was trying to insert Blocks from multiple DWG files into drawing area via C#.  Initially I was trying to write routines for Drag & Drop, Rotating, Scaling etc. However, AutoCAD’s built-in command “INSERT” is doing all such tasks. So I started looking for the method to Execute AutoCAD’s built-in commands.

I tried INSERT command and here is a code segment from  my C# Project initiated with AutoCAD.Net Wizards (Download from Autodesk Developer Network).

AutoCAD Command Method (C#)
  1.       [CommandMethod("InsertDWG")]
  2.         static public void SendINSERTCmd()
  3.         {
  4.             string DWG = @"D:\MYDWGs\1047.DWG";
  5.             string InsertCmd = @"_.-INSERT " + DWG + '\r' + '\n';
  6.             Document doc = Application.DocumentManager.MdiActiveDocument;
  7.             doc.SendStringToExecute(InsertCmd, true, false, false);
  8.         }

After compiling your code, use “NetLoad” to load your .net DLL and issue “InsertDWG”. You  will see the command line in AutoCAD’s command window. Drawing Block would be attached to your mouse pointer and you would be able to Drag, Drop, Scale, Rotate and all perform all functions that are provided in AutoCAD normally.

2 comments:

Unknown said...

sorry, for my noob question, but why is there a @ on line 5? thanks!

Farrukh said...

This is the syntax of C#. If you want to use paths like C:\ProgramFiles, then you'll use @"C:\ProgramFiles", but if you don't use @, then you will have to use \\ instead of \ i.e. "C:\\ProgramFiles".