using System; using System.Collections.Generic; using System.Text; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.ApplicationServices; namespace T_cad { class OldCls2 { [CommandMethod("CTK")] public void ctk() { Document document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database database = HostApplicationServices.WorkingDatabase; using (Transaction traction = database.TransactionManager.StartTransaction()) { DocumentLock documentlock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument(); BlockTable blocktable = traction.GetObject(database.BlockTableId, OpenMode.ForWrite) as BlockTable; BlockTableRecord blocktablerecord = traction.GetObject(blocktable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // 获得当前文档的编辑器 Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; // 创建一个 TypedValue 数组,用于定义过滤条件 TypedValue[] typedvalue = new TypedValue[1]; typedvalue.SetValue(new TypedValue((int)DxfCode.LayerName, "VC"), 0); // 赋值过滤条件给 SelectionFilter 对象 SelectionFilter selectionfilter = new SelectionFilter(typedvalue); // 要求在图形区域中手动选择对象 PromptSelectionResult psr = editor.GetSelection(selectionfilter); if (psr.Status == PromptStatus.OK) { SelectionSet selectionset = psr.Value; ObjectId[] obj = new ObjectId[selectionset.Count]; obj = selectionset.GetObjectIds(); for (int i = 0; i < obj.Length; i++) { ObjectId objid = obj[i]; Entity entity = (Entity)traction.GetObject(objid, OpenMode.ForRead); Polyline line = entity as Polyline; Point3dCollection coll = new Point3dCollection(); line.GetStretchPoints(coll); double max_x = coll[0].X; double max_y = coll[0].Y; double min_x = coll[0].X; double min_y = coll[0].Y; for (int j = 1; j < coll.Count; j++) { if (coll[j].X > max_x) { max_x = coll[j].X; } if (coll[j].Y > max_y) { max_y = coll[j].Y; } if (coll[j].X < min_x) { min_x = coll[j].X; } if (coll[j].Y < min_y) { min_y = coll[j].Y; } } Point3dCollection coll2 = new Point3dCollection(); Point3d p1 = new Point3d(min_x, min_y, 0); Point3d p2 = new Point3d(min_x, max_y, 0); Point3d p3 = new Point3d(max_x, max_y, 0); Point3d p4 = new Point3d(max_x, min_y, 0); coll2.Add(p1); coll2.Add(p2); coll2.Add(p3); coll2.Add(p4); Polyline2d pline = new Polyline2d(Poly2dType.SimplePoly, coll2, 0, true, 0, 0, null); pline.Layer = "qtk"; pline.SetDatabaseDefaults(); blocktablerecord.AppendEntity(pline); traction.AddNewlyCreatedDBObject(pline, true); } } traction.Commit(); documentlock.Dispose(); traction.Dispose(); } } } }