Hi Guys
I'm using CSharp and I want to call -INSERT command while passing it the path of my dwg files. This call would be done via my DragDrop class.
I tried doc.SendStringToExecute(InsertCmd, true, false, true); but it then waits for user to press enter there...
So how can we call AutoCAD's Commands from our .Net code?
Any help?
Thanks
Solved! Go to Solution.
Solved by Alfred.NESWADBA. Go to Solution.
Hi,
Try this (with your blockname):
Dim tCmd as String = "_INSERT" & vbCr & "C:\TEMP\myBlock.DWG" & vbCr
doc.SendStringToExecute(tCmd, true, true, false)
The orange parts show how to send <ENTER>
- alfred -
Hi Alferd,
Thanks a lot for quick reply....It worked... I also was reading similar thing (in the example code) here:
http://adndevblog.typepad.com/autocad/2012/06/use-log-file-and-setvar-command-to-get-a-list-of-autoc...
So equivalent of VbCrlf is \r \n and Here is my little code:
[CommandMethod("cmdTest")]
static public void SendCmd()
{
string File_DWG = @"D:\sym\1047.DWG";
string InsertCmd = @"_.-INSERT " + File_DWG + '\r' + '\n';
Document doc = Application.DocumentManager.MdiActiveDocument;
doc.SendStringToExecute(InsertCmd, true, false, false);
}
Thanks a bunch
Having the same problem using C#
string InsertCmd = @"_.-INSERT " + File_DWG + '\r' + '\n';
still didn't work? and causes CAD to crash? Any ideas?
Mine is working properly at this time by adding \r and \n.. Try using only \n...I'm using AutoCAD 2012...
Is that closing AutoCAD? or there is some crash report???
can you please post your code segment?
I've tried various combinations to no avail? Not sure what's wrong? I'm running 2012, my code passes a blkNam which is present in the block table. It asks for the insertion point and then crashes.
string InsertCmd = @"_.-INSERT " + blkNam + '\r' + '\n';
doc.SendStringToExecute(InsertCmd, true, false, false);
I've also tried this approach, which works but I can't figure out how to pass the scales prompt?
string InsertCmd = "(command \"_insert\" \"" + blkNam + "\" " + ")\n";
...confused
Hi,
you can always try it manually by typing the commands/options/values into the command-line .. .and for every <ENTER> you have to use \n instead.
So start typing
_-INSERT<ENTER>
TABLE<ENTER> ...or whatever your block's name is
....and now see the options you can set before the block is inserted, e.g.
_SCALE<ENTER>
1<ENTER>
...
So the LISP-result (without C#-conventions) may look like that:
(command "_-INSERT" "TABLE" "_SCALE" "1")
HTH, - alfred -
As far I remember, when you issue -INSERT, it will give your Scale, Move and rotate prompt. In addition, while experimenting with different *.dwg files, it also prompted to enter Tag number and at some file, it prompted to Select Tag.
I guess, that is due to the Block Attributes present in that dwg, but I'm not sure...
And -INSERT automate those Prompts for you.
Is there a reason you have to use "-Insert"?
It is my understanding, and general rule to avoid using "Sendcommand" and "Sendstringtoexecute" whenever possible.
Why can't you use dot net and add the desired block to the current drawing database?
Same case here. I wrote .Net routines to move and rotate the Block, but then I realized that it would be complicated when I will have to deal with the behavior related to Block's attributes. So I decided to use built-in functionality.
BTW, why is it that you do not recommend to use built-in functionality?
First of all I'm a dot net newbie so this is mostly from what I've read on the forums. In my actual experience I had a program that used "SendCommand" and when in debug mode it would not run (VB.Net Express). It would crash on the SendCommands so to debug a program I had to comment those lines out.
The program ran fine with the "SendCommand" lines in Release mode, but just not in Debug.
I think, you might be referencing ObjectARX apis in your VB Code.
I'm switched to C# just because of better support and management in .Net Apis.
Try this code
internal class BlockRefJig : EntityJig { Point3d m_Position,m_BasePoint; double m_Angle; int m_PromptCounter; Matrix3d m_Ucs; Matrix3d m_Mat; //键值对集合(属性定义/引用) Dictionary<AttributeDefinition, AttributeReference> m_Attribs; public BlockRefJig(BlockReference blkref, Dictionary<AttributeDefinition, AttributeReference> attribs) : base(blkref) { m_Position = new Point3d(); m_Angle = 0; m_Ucs = SystemManager.Editor.CurrentUserCoordinateSystem; m_Attribs = attribs; Update(); } protected override SamplerStatus Sampler(JigPrompts prompts) { switch (m_PromptCounter) { case 0: { JigPromptPointOptions jigOpts = new JigPromptPointOptions("\n请输入基点:"); jigOpts.UserInputControls = UserInputControls.Accept3dCoordinates | UserInputControls.NoZeroResponseAccepted | UserInputControls.NoNegativeResponseAccepted; PromptPointResult res = prompts.AcquirePoint(jigOpts); Point3d pnt = res.Value; if (pnt != m_Position) { m_Position = pnt; m_BasePoint = m_Position; } else return SamplerStatus.NoChange; if (res.Status == PromptStatus.Cancel) return SamplerStatus.Cancel; else return SamplerStatus.OK; } case 1: { JigPromptAngleOptions jigOpts = new JigPromptAngleOptions("\n请输入旋转角度:"); jigOpts.UserInputControls = UserInputControls.Accept3dCoordinates | UserInputControls.NoNegativeResponseAccepted | UserInputControls.GovernedByUCSDetect | UserInputControls.UseBasePointElevation; jigOpts.Cursor = CursorType.RubberBand; jigOpts.UseBasePoint = true; jigOpts.BasePoint = m_BasePoint; PromptDoubleResult res = prompts.AcquireAngle(jigOpts); double angleTemp = res.Value; if (angleTemp != m_Angle) m_Angle = angleTemp; else return SamplerStatus.NoChange; if (res.Status == PromptStatus.Cancel) return SamplerStatus.Cancel; else return SamplerStatus.OK; } default: return SamplerStatus.NoChange; } } protected override bool Update() { try { /*Ucs下Jig的流程: * 1.先将图元在Wcs下摆正,即//xy平面 * 2.将获取点坐标转换到Ucs下 * 3.将图元在Ucs下摆正 * 4.矩阵变换到Wcs */ BlockReference blkref = (BlockReference)Entity; blkref.Normal = Vector3d.ZAxis; blkref.Position = m_Position.Wcs2Ucs(); blkref.Rotation = m_Angle; blkref.TransformBy(m_Ucs); //将属性引用按块引用的Ocs矩阵变换 if (m_Attribs != null) { m_Mat = blkref.BlockTransform; foreach (KeyValuePair<AttributeDefinition, AttributeReference> att in m_Attribs) { AttributeReference attref = att.Value; string s = attref.TextString; attref.SetAttributeFromBlock(att.Key, m_Mat); attref.TextString = s; } } } catch { return false; } return true; } public void SetPromptCounter(int i) { if (i == 0 || i == 1) { m_PromptCounter = i; } } }
/// <summary> /// 添加属性到块参照 /// </summary> /// <param name="blkref">块参照</param> /// <param name="atts">属性集合</param> /// <returns>属性定义和属性参照对照表</returns> public Dictionary<AttributeDefinition, AttributeReference> AppendAttribToBlock(BlockReference blkref, List<string> atts) { var blkdef = GetObject<BlockTableRecord>(blkref.BlockTableRecord); int i = 0; if (blkdef.HasAttributeDefinitions) { var attribs = new Dictionary<AttributeDefinition, AttributeReference>(); var attdefs = blkdef.GetEntities<AttributeDefinition>(Transaction) .Where(attdef => !(attdef.Constant || attdef.Invisible)); foreach (var attdef in attdefs) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(attdef, blkref.BlockTransform); if (i < atts.Count) attref.TextString = atts[i]; else attref.TextString = attdef.TextString; i++; blkref.AttributeCollection.AppendAttribute(attref); Transaction.AddNewlyCreatedDBObject(attref, true); attribs.Add(attdef, attref); } return attribs; } return null; }
/// <summary> /// 动态添加块参照 /// </summary> /// <param name="blkdefid">块定义Id</param> /// <param name="atts">属性集合</param> /// <returns>块参照Id</returns> public ObjectId InsertBlockRef(ObjectId blkdefid, List<string> atts) { BlockTableRecord btr = OpenCurrentSpace(); BlockReference blkref = new BlockReference(Point3d.Origin, blkdefid); ObjectId id = AddEntity(btr, blkref); BlockRefJig jig = new BlockRefJig(blkref, AppendAttribToBlock(blkref, atts)); jig.SetPromptCounter(0); PromptResult res = Editor.Drag(jig); if (res.Status == PromptStatus.OK) { jig.SetPromptCounter(1); res = Editor.Drag(jig); if (res.Status == PromptStatus.OK) { return id; } } blkref.Erase(); return ObjectId.Null; }
using System.Collections.Generic; using System.Linq; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.ApplicationServices; [assembly: CommandClass(typeof(InsertBlock.Commands))] namespace InsertBlock { public class Commands { public static Dictionary<AttributeDefinition, AttributeReference> AppendAttribToBlock(Transaction tr, BlockReference blkref, List<string> atts) { var blkdef = (BlockTableRecord)tr.GetObject(blkref.BlockTableRecord, OpenMode.ForRead); int i = 0; if (blkdef.HasAttributeDefinitions) { var attribs = new Dictionary<AttributeDefinition, AttributeReference>(); var attdefs = blkdef.Cast<ObjectId>() .Select(id => tr.GetObject(id, OpenMode.ForRead)) .OfType<AttributeDefinition>() .Where(attdef => !(attdef.Constant || attdef.Invisible)); foreach (var attdef in attdefs) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(attdef, blkref.BlockTransform); if (i < atts.Count) attref.TextString = atts[i]; else attref.TextString = attdef.TextString; i++; blkref.AttributeCollection.AppendAttribute(attref); tr.AddNewlyCreatedDBObject(attref, true); attribs.Add(attdef, attref); } return attribs; } return null; } public static ObjectId InsertBlockRef(Transaction tr, Database db, Editor ed, ObjectId blkdefid, List<string> atts) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); BlockReference blkref = new BlockReference(Point3d.Origin, blkdefid); ObjectId id = btr.AppendEntity(blkref); tr.AddNewlyCreatedDBObject(blkref, true); BlockRefJig jig = new BlockRefJig(blkref, AppendAttribToBlock(tr, blkref, atts)); jig.SetPromptCounter(0); PromptResult res = ed.Drag(jig); if (res.Status == PromptStatus.OK) { jig.SetPromptCounter(1); res = ed.Drag(jig); if (res.Status == PromptStatus.OK) { return id; } } blkref.Erase(); return ObjectId.Null; } [CommandMethod("MIB")] public static void MyInsertBlock() { var doc = Application.DocumentManager.MdiActiveDocument; var db = doc.Database; var ed = doc.Editor; using (Transaction tr = db.TransactionManager.StartTransaction()) { var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite); ObjectId id; if (bt.Has("Test1")) { id = bt["Test1"]; } else { BlockTableRecord btr = new BlockTableRecord(); btr.Name = "Test1"; id = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); AttributeDefinition att = new AttributeDefinition(Point3d.Origin, "1", "Number", "input number:", db.Textstyle); att.Height = 6; Circle c = new Circle(Point3d.Origin, Vector3d.ZAxis, 10); btr.AppendEntity(att); tr.AddNewlyCreatedDBObject(att, true); btr.AppendEntity(c); tr.AddNewlyCreatedDBObject(c, true); } InsertBlockRef(tr, db, ed, id, new List<string> { "1" }); tr.Commit(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; namespace InsertBlock { internal class BlockRefJig : EntityJig { Point3d m_Position, m_BasePoint; double m_Angle; int m_PromptCounter; Matrix3d m_Ucs; Matrix3d m_Mat; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; //键值对集合(属性定义/引用) Dictionary<AttributeDefinition, AttributeReference> m_Attribs; public BlockRefJig(BlockReference blkref, Dictionary<AttributeDefinition, AttributeReference> attribs) : base(blkref) { m_Position = new Point3d(); m_Angle = 0; m_Ucs = ed.CurrentUserCoordinateSystem; m_Attribs = attribs; Update(); } protected override SamplerStatus Sampler(JigPrompts prompts) { switch (m_PromptCounter) { case 0: { JigPromptPointOptions jigOpts = new JigPromptPointOptions("\n请输入基点:"); jigOpts.UserInputControls = UserInputControls.Accept3dCoordinates | UserInputControls.NoZeroResponseAccepted | UserInputControls.NoNegativeResponseAccepted; PromptPointResult res = prompts.AcquirePoint(jigOpts); Point3d pnt = res.Value; if (pnt != m_Position) { m_Position = pnt; m_BasePoint = m_Position; } else return SamplerStatus.NoChange; if (res.Status == PromptStatus.Cancel) return SamplerStatus.Cancel; else return SamplerStatus.OK; } case 1: { JigPromptAngleOptions jigOpts = new JigPromptAngleOptions("\n请输入旋转角度:"); jigOpts.UserInputControls = UserInputControls.Accept3dCoordinates | UserInputControls.NoNegativeResponseAccepted | UserInputControls.GovernedByUCSDetect | UserInputControls.UseBasePointElevation; jigOpts.Cursor = CursorType.RubberBand; jigOpts.UseBasePoint = true; jigOpts.BasePoint = m_BasePoint; PromptDoubleResult res = prompts.AcquireAngle(jigOpts); double angleTemp = res.Value; if (angleTemp != m_Angle) m_Angle = angleTemp; else return SamplerStatus.NoChange; if (res.Status == PromptStatus.Cancel) return SamplerStatus.Cancel; else return SamplerStatus.OK; } default: return SamplerStatus.NoChange; } } protected override bool Update() { try { /*Ucs下Jig的流程: * 1.先将图元在Wcs下摆正,即//xy平面 * 2.将获取点坐标转换到Ucs下 * 3.将图元在Ucs下摆正 * 4.矩阵变换到Wcs */ BlockReference blkref = (BlockReference)Entity; blkref.Normal = Vector3d.ZAxis; blkref.Position = m_Position.TransformBy(ed.CurrentUserCoordinateSystem); blkref.Rotation = m_Angle; blkref.TransformBy(m_Ucs); //将属性引用按块引用的Ocs矩阵变换 if (m_Attribs != null) { m_Mat = blkref.BlockTransform; foreach (KeyValuePair<AttributeDefinition, AttributeReference> att in m_Attribs) { AttributeReference attref = att.Value; string s = attref.TextString; attref.SetAttributeFromBlock(att.Key, m_Mat); attref.TextString = s; } } } catch { return false; } return true; } public void SetPromptCounter(int i) { if (i == 0 || i == 1) { m_PromptCounter = i; } } } }