赞
踩
由于工作需要,最近在学习二次开发,将其记录于此,以便日后查看。
涉及“特性”,“进程”知识点,需要有所了解
#region CAD二次开发--第一节 /// <summary> /// 进程内或进程外 /// </summary> [CommandMethod("ConnectToAcad")] public static void ConnectToAcad() { AcadApplication acAppComObj = null; const string strProgID = "AutoCAD.Application.19"; try { acAppComObj = (AcadApplication)Marshal.GetActiveObject(strProgID); } catch { try { //创建新的AutoCAD实例 acAppComObj = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgID), true); } catch { //创建新实例不成功就显示信息并退出 MessageBox.Show("Instace of 'AutoCAD.Application'" + " could not be created."); return; } } //显示获得的应用程序实例并返回名称、版本 acAppComObj.Visible = true; MessageBox.Show("Now running " + acAppComObj.Name + " Version " + acAppComObj.Version); //获取当前文档 AcadDocument acDocComObj; acDocComObj = acAppComObj.ActiveDocument; //可选的,加载程序集并启动命令,如果进程内程序集 //已被加载,直接启动命令即可 acDocComObj.SendCommand("(command " + (char)34 + "NETLOAD" + (char)34 + " " + (char)34 + "E:/VS2017/C#/CAD二次开发/CADSyntheticalDemo/CADExtends/bin/Debug/CADExtends.dll" + (char)34 + ")"); acDocComObj.SendCommand("你好CAD"); } /// <summary> /// LISPFunction /// </summary> /// <param name="rbArgs"></param> [LispFunction("DisplayFullName")] public static void DisplayFullName(ResultBuffer rbArgs) { if (rbArgs != null) { string strVal1 = ""; string strVal2 = ""; int nCnt = 0; foreach (TypedValue rb in rbArgs) { if (rb.TypeCode == (int)Autodesk.AutoCAD.Runtime.LispDataType.Text) { switch (nCnt) { case 0: strVal1 = rb.Value.ToString(); break; case 1: strVal2 = rb.Value.ToString(); break; } nCnt++; } } Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor. WriteMessage("\nName: " + strVal1 + " " + strVal2); } } /// <summary> /// 最大、最小化应用窗体 /// </summary> [CommandMethod("MinMaxApplicationWindow")] public static void MinMaxApplicationWindow() { //最小化应用程序窗口 Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.WindowState = Window.State.Minimized; System.Windows.Forms.MessageBox.Show("Minimized", "MinMax", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.None, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.ServiceNotification); //最大化应用窗口 Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.WindowState = Window.State.Maximized; System.Windows.Forms.MessageBox.Show("Maximized", "MinMax"); } /// <summary> /// 获取应用窗口当前状态 /// </summary> [CommandMethod("CurrentWindowState")] public static void CurrentWindowState() { System.Windows.Forms.MessageBox.Show("The application window is " + Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.WindowState.ToString(), "Window State"); } /// <summary> /// 使应用程序窗体可见或不可见 /// </summary> [CommandMethod("HideWindowState")] public static void HideWindowState() { //隐藏应用程序窗口 Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.Visible = false; System.Windows.Forms.MessageBox.Show("Invisible", "Show/Hide"); //显示应用程序窗口 Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.Visible = true; System.Windows.Forms.MessageBox.Show("Visible", "Show/Hide"); } /// <summary> /// 设置当前文档窗口的位置和大小 /// </summary> [CommandMethod("SizeDocumentWindow")] public static void SizeDocumemntWindow() { //获取当前文档窗口 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; acDoc.Window.WindowState = Window.State.Normal; //设置文档窗口位置 Point ptDoc = new Point(0, 0); //acDoc.Window.Location=ptDoc; //设置文档窗口大小 Size szDoc = new Size(400, 400); //acDoc.Window.Size = szDoc; } /// <summary> /// 最大最小化当前窗口 /// </summary> [CommandMethod("MinMaxDocumentWindow")] public static void MinMaxDocumentWindow() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; //最小化文档窗口 acDoc.Window.WindowState = Window.State.Minimized; System.Windows.Forms.MessageBox.Show("Minimized", "MinMax"); //最大化文档窗口 acDoc.Window.WindowState = Window.State.Maximized; System.Windows.Forms.MessageBox.Show("Maximized", "MinMax"); } /// <summary> /// 获取当前活动文档窗口的状态 /// </summary> [CommandMethod("CurrentDocWindowState")] public static void CurrentDocWindowState() { Document acDoc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument; System.Windows.Forms.MessageBox.Show("The document window is " + acDoc.Window.WindowState.ToString(), "Window State"); } /// <summary> /// 获得当前文档视图 /// </summary> /// <param name="pMin">区域左下角3D点</param> /// <param name="pMax">区域右上角3D点</param> /// <param name="pCenter">视图中心的3D点</param> /// <param name="dFactor">视图缩放比例</param> static void Zoom(Point3d pMin, Point3d pMax, Point3d pCenter, double dFactor) { //获取当前文档及数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; int nCurVport = System.Convert.ToInt32(Autodesk.AutoCAD.ApplicationServices. Application.GetSystemVariable("CVPORT")); //没提供点或只提供了一个中心点时,获取当前空间范围 //检查当前空间是否为模型空间 if (acCurDb.TileMode == true) { if (pMin.Equals(new Point3d()) == true && pMax.Equals(new Point3d()) == true) { pMin = acCurDb.Extmin; pMax = acCurDb.Extmax; } } else { //检查当前空间是否为图纸空间 if (nCurVport == 1) { //获取图纸空间范围 if (pMin.Equals(new Point3d()) == true && pMax.Equals(new Point3d()) == true) { pMin = acCurDb.Pextmin; pMax = acCurDb.Pextmax; } } else { //获取模型空间范围 if (pMin.Equals(new Point3d()) == true && pMax.Equals(new Point3d()) == true) { pMin = acCurDb.Extmin; pMax = acCurDb.Extmax; } } } //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //获取当前视图 using (ViewTableRecord acView = acDoc.Editor.GetCurrentView()) { Extents3d eExtents; //将WCS坐标变换为DCS坐标 Matrix3d matWCS2DCS; matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection); matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS; matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist, acView.ViewDirection, acView.Target) * matWCS2DCS; //如果指定了中心点,就为中心模式和比例模式 //设置显示范围的最小点和最大点 if (pCenter.DistanceTo(Point3d.Origin) != 0) { pMin = new Point3d(pCenter.X - (acView.Width / 2), pCenter.Y - (acView.Height / 2), 0); pMax = new Point3d((acView.Width / 2) + pCenter.X, (acView.Height / 2) + pCenter.Y, 0); } //用直线创建范围对象 using (Line acLine = new Line(pMin, pMax)) { eExtents = new Extents3d(acLine.Bounds.Value.MinPoint, acLine.Bounds.Value.MaxPoint); } //计算当前视图的宽高比 double dViewRatio; dViewRatio = (acView.Width / acView.Height); //变换视图范围 matWCS2DCS = matWCS2DCS.Inverse(); eExtents.TransformBy(matWCS2DCS); double dWidth; double dHeight; Point2d pNewCentPt; //检查是否提供了中心点(中心模式和比例模式) if (pCenter.DistanceTo(Point3d.Origin) != 0) { dWidth = acView.Width; dHeight = acView.Height; if (dFactor == 0) { pCenter = pCenter.TransformBy(matWCS2DCS); } pNewCentPt = new Point2d(pCenter.X, pCenter.Y); } else//窗口、范围和界限模式下 { //计算当前视图的宽高新值; dWidth = eExtents.MaxPoint.X - eExtents.MinPoint.X; dHeight = eExtents.MaxPoint.Y - eExtents.MinPoint.Y; //获取视图中心点 pNewCentPt = new Point2d(((eExtents.MaxPoint.X + eExtents.MinPoint.X) * 0.5), ((eExtents.MaxPoint.Y + eExtents.MinPoint.Y) * 0.5)); } //检查宽度新值是否适于当前窗口 if (dWidth > (dHeight * dViewRatio)) dHeight = dWidth / dViewRatio; //调整视图大小 if (dFactor != 0) { acView.Height = dHeight * dFactor; acView.Width = dWidth * dFactor; } //设置视图中心; acView.CenterPoint = pNewCentPt; //更新当前视图 acDoc.Editor.SetCurrentView(acView); } //提交更改 acTrans.Commit(); } } /// <summary> /// 缩放窗口 /// </summary> [CommandMethod("ZoomWindow")] public static void ZoomWindow() { //Zoom to a window boundary defined by 1.3,7.8 and 13.7,-2.6 //缩放到由点(1.3,7.8)和点(13.7,-2.6)定义的窗口 Point3d pMin = new Point3d(1.3, 7.8, 0); Point3d pMax = new Point3d(13.7, -2.6, 0); Zoom(pMin, pMax, new Point3d(), 1); } /// <summary> /// 按比例缩放视图 /// </summary> [CommandMethod("ZoomScale")] static public void ZoomScale() { //获取当前文档 Document acDoc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument; //获取当前视图 using (ViewTableRecord acView = acDoc.Editor.GetCurrentView()) { //获取当前视图中心 Point3d pCenter = new Point3d(acView.CenterPoint.X, acView.CenterPoint.Y, 0); //设置比例系数 double dScale = 0.5; //基于当前视图中心按比例缩放视图 Zoom(new Point3d(), new Point3d(), pCenter, 1 / dScale); } } /// <summary> /// 移动当前图形到指定中心点 /// </summary> [CommandMethod("ZoomCenter")] public static void ZoomCenter() { //设置视图的中心点为(5,5,0) Zoom(new Point3d(), new Point3d(), new Point3d(5, 5, 0), 1); } //显示图形范围和界限 //Extmin and Extmax 返回模型空间的范围 //Pextmin and Pextmax 返回当前图纸空间布局的范围 [CommandMethod("ZoomExtents")] public static void ZoomExtents() { //缩放到当前空间的范围 Zoom(new Point3d(), new Point3d(), new Point3d(), 1.01075); } [CommandMethod("ZoomLimits")] public static void ZoomLimits() { Document acDoc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //放到模型空间的界限 Zoom(new Point3d(acCurDb.Limmin.X, acCurDb.Limmin.Y, 0), new Point3d(acCurDb.Limmax.X, acCurDb.Limmax.Y, 0), new Point3d(), 1); } /// <summary> /// 创建命名视图 /// </summary> [CommandMethod("CreateNamedView")] public static void CreateNamedView() { //获取当前数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以只读模式打开View表 ViewTable acViewTbl; acViewTbl = acTrans.GetObject(acCurDb.ViewTableId, OpenMode.ForRead) as ViewTable; //检查名为View1的视图是否存在 if (acViewTbl.Has("View1") == false) { //以只读模式打开View表 acViewTbl.UpgradeOpen(); //新建一个View表记录并命名为View1 ViewTableRecord acViewTblRec = new ViewTableRecord(); acViewTblRec.Name = "View1"; //添加到View表及事务 acViewTbl.Add(acViewTblRec); acTrans.AddNewlyCreatedDBObject(acViewTblRec, true); //置View1为当前视图 acDoc.Editor.SetCurrentView(acViewTblRec); //提交修改 acTrans.Commit(); } } } /// <summary> /// 删除命名空间 /// </summary> [CommandMethod("EraseNamedView")] public static void EraseNamedView() { //获取当前数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开View表 ViewTable acViewTbl; acViewTbl = acTrans.GetObject(acCurDb.ViewTableId, OpenMode.ForRead) as ViewTable; //检查名为“View1”的视图是否存在 if (acViewTbl.Has("View1") == true) { //以写模式打开View表 acViewTbl.UpgradeOpen(); //获取命名视图的记录 ViewTableRecord acViewTblRec; acViewTblRec = acTrans.GetObject(acViewTbl["View1"], OpenMode.ForWrite) as ViewTableRecord; //从View表删除命名视图 acViewTblRec.Erase(); //提交修改 acTrans.Commit(); } } } /// <summary> /// 创建一个有两个水平窗口的平铺视口配置 /// </summary> [CommandMethod("CreateModelViewport")] public static void CteateModelViewport() { //获取当前数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Viewport表 ViewportTable acVportTbl; acVportTbl = acTrans.GetObject(acCurDb.ViewportTableId, OpenMode.ForRead) as ViewportTable; //检查视图"TEST_VIEWPORT"是否存在 if (acVportTbl.Has("TEST_VIEWPORT") == false) { //以写模式打开Viewport表 acVportTbl.UpgradeOpen(); //添加新视口到Viewport表并添加事务记录 ViewportTableRecord acVportTblRecLwr = new ViewportTableRecord(); acVportTbl.Add(acVportTblRecLwr); acTrans.AddNewlyCreatedDBObject(acVportTblRecLwr, true); //新视口命名为”TEST_VIEWPORT“并将绘图窗口的下半部分赋给它 acVportTblRecLwr.Name = "TEST_VIEWPORT"; acVportTblRecLwr.LowerLeftCorner = new Point2d(0, 0); acVportTblRecLwr.UpperRightCorner = new Point2d(1, 0.5); //添加新视口到Viewport表并添加事务记录 ViewportTableRecord acVportTblRecUpr = new ViewportTableRecord(); acVportTbl.Add(acVportTblRecUpr); acTrans.AddNewlyCreatedDBObject(acVportTblRecUpr, true); //新视口命名为”TEST_VIEWPORT"并将绘图窗口的上半部分赋给它 acVportTblRecUpr.Name = "TEST_VIEWPORT"; acVportTblRecUpr.LowerLeftCorner = new Point2d(0, 0.5); acVportTblRecUpr.UpperRightCorner = new Point2d(1, 1); //将新视口设为活动视口,需要删除名为”*Active“的视口 //并基于”TEST_VIEWPORT“重建,遍历符号表里的每个对象 foreach (ObjectId acObjId in acVportTbl) { //以读模式打开对象 ViewportTableRecord acVportTblRec; acVportTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as ViewportTableRecord; //检查是否为活动视口,是就删除 if (acVportTblRec.Name == "*Active") { acVportTblRec.UpgradeOpen(); acVportTblRec.Erase(); } } //复制新视口为活动视口 foreach (ObjectId acObjId in acVportTbl) { //以读模式打开对象 ViewportTableRecord acVportTblRec; acVportTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as ViewportTableRecord; //检查是否为活动视口,是就删除 if (acVportTblRec.Name == "TEST_VIEWPORT") { ViewportTableRecord acVportTblRecClone; acVportTblRecClone = acVportTblRec.Clone() as ViewportTableRecord; ; //添加新视口到Viewport表并添加事务记录 acVportTbl.Add(acVportTblRecClone); acVportTblRecClone.Name = "*Active"; acTrans.AddNewlyCreatedDBObject(acVportTblRecClone, true); } } //用新的平铺视口排列更新显示 acDoc.Editor.UpdateTiledViewportsFromDatabase(); //提交修改 acTrans.Commit(); } } } /// <summary> /// 分割视图并遍历 /// </summary> [CommandMethod("SplitAndIterateModelViewports")] public static void SplitAndIterateModelViewports() { //获取当前数据库 Document acDox = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDox.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以写模式打开Viewport表 ViewportTable acVportTbl; acVportTbl = acTrans.GetObject(acCurDb.ViewportTableId, OpenMode.ForWrite) as ViewportTable; //以写模式打开当前视口 ViewportTableRecord acVportTblRec; acVportTblRec = acTrans.GetObject(acDox.Editor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord; ViewportTableRecord acVportTblRecNew = new ViewportTableRecord(); //添加新视口到Viewport表,记录事务 acVportTbl.Add(acVportTblRecNew); acTrans.AddNewlyCreatedDBObject(acVportTblRecNew, true); //新视口的Name设置为"*Active" acVportTblRecNew.Name = "*Active"; //用当前左下角作为新视口的左下角 acVportTblRecNew.LowerLeftCorner = acVportTblRec.LowerLeftCorner; //获取当前右上角X值的一半 acVportTblRecNew.UpperRightCorner = new Point2d(acVportTblRec.UpperRightCorner.X, acVportTblRec.LowerLeftCorner.Y + ((acVportTblRec.UpperRightCorner.Y + acVportTblRec.LowerLeftCorner.Y) / 2)); //重新计算活动视口的两个角 acVportTblRec.LowerLeftCorner = new Point2d(acVportTblRec.LowerLeftCorner.X, acVportTblRecNew.UpperRightCorner.Y); //用新平铺视口布局更新显示 acDox.Editor.UpdateTiledViewportsFromDatabase(); //遍历视口表中的每个对象 foreach (ObjectId acObjID in acVportTbl) { //以读打开对象 ViewportTableRecord acVportTblRecCur; acVportTblRecCur = acTrans.GetObject(acObjID, OpenMode.ForRead) as ViewportTableRecord; if (acVportTblRecCur.Name == "*Active") { Autodesk.AutoCAD.ApplicationServices.Application. SetSystemVariable("CVPORT", acVportTblRecCur.Number); Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Viewport: " + acVportTblRecCur.Number + " is now active." + "\nLower left corner: " + acVportTblRecCur.LowerLeftCorner.X + ", " + acVportTblRecCur.LowerLeftCorner.Y + "\nUpper right corner: " + acVportTblRecCur.UpperRightCorner.X + ", " + acVportTblRecCur.UpperRightCorner.Y); } } //提交修改,关闭事务 acTrans.Commit(); } } /// <summary> /// 改变文档窗口的几何信息 /// </summary> public static void RewlyDrawing() { //重画图形 Autodesk.AutoCAD.ApplicationServices.Application.UpdateScreen(); Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor.UpdateScreen(); //重新生成图形 Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument. Editor.Regen(); } /// <summary> /// 创建新图形 /// </summary> [CommandMethod("NewDrawing", CommandFlags.Session)] public static void NewDrawing() { //指定使用的样板,如果这个样板没找到,就使用默认设置 string strTemplatePath = "acad.dwt"; DocumentCollection acDocMgr = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager; Document acDoc = acDocMgr.Add(strTemplatePath); acDocMgr.MdiActiveDocument = acDoc; } /// <summary> /// 打开图形 /// </summary> [CommandMethod("OpenDrawing", CommandFlags.Session)] public static void OpenDrawing() { string strFileName = "E:/VS2017/C#/CAD二次开发/CADDocument/MyDrawing1.dwg"; DocumentCollection acDocMgr = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager; if (File.Exists(strFileName)) { acDocMgr.Open(strFileName, false); } else { acDocMgr.MdiActiveDocument.Editor.WriteMessage("File " + strFileName + " does not exist."); } } /// <summary> /// 关闭图形文件 /// </summary> [CommandMethod("CloseDrawing", CommandFlags.Session)] public static void CloseDrawing() { string strFileName = "E:/VS2017/C#/CAD二次开发/CADDocument/MyDrawing1.dwg"; Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; //Database acCurDb = acDoc.Database; acDoc.CloseAndSave(strFileName); } /// <summary> /// 保存图形文件 /// </summary> [CommandMethod("SaveActiveDrawing")] public static void SaveActiveDrawing() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; string strDWGName = acDoc.Name; object obj = Autodesk.AutoCAD.ApplicationServices. Application.GetSystemVariable("DWGTITLED"); //图形命名了嘛?0-没呢 if (System.Convert.ToInt16(obj) == 0) { //如果图形使用了默认名(Drawing1、Drawing2等) //就提供一个新文件名 strDWGName = "d:\\MyDrawing.dwg"; } //保存图形 acDoc.Database.SaveAs(strDWGName, true, DwgVersion.Current, acDoc.Database.SecurityParameters); } /// <summary> /// 检查图形中是否有未保存的修改 /// </summary> [CommandMethod("DrawingSaved")] public static void DrawingSaved() { object obj = Autodesk.AutoCAD.ApplicationServices.Application. GetSystemVariable("DBMOD"); //检查系统变量DBMOD的值,0表示没有未保存修改 //检查系统变量DBMOD的值,0表示没有未保存修改 if (System.Convert.ToInt16(obj) != 0) { if (System.Windows.Forms.MessageBox.Show("Do you wish to save this drawing?", "Save Drawing", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; acDoc.Database.SaveAs(acDoc.Name, true, DwgVersion.Current, acDoc.Database.SecurityParameters); } } } //为自定义应用程序菜单项创建命令处理器 public class MyCommandHandler : System.Windows.Input.ICommand { public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("MyMenuItem has been clicked."); } } class Chp02_3_3 { //Global var for ZeroDocState 全局变量 ApplicationMenuItem acApMenuItem = null; [CommandMethod("AddZeroDocEvent")] public void AddZeroDocEvent() { //获取DocumentCollection并注册DocumentDestroyed时间 DocumentCollection acDocMgr = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager; acDocMgr.DocumentDestroyed += new DocumentDestroyedEventHandler(docDestroyed); } public void docDestroyed(object obj, DocumentDestroyedEventArgs acDocDesEvtArgs) { //确定菜单项是否已存在 //确定打开的文档数 if (Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.Count == 1 && acApMenuItem == null) { //添加事务处理器来守候应用程序菜单 //记着添加引用AdWindows.dll啊~ ComponentManager.ApplicationMenu.Opening += new EventHandler<EventArgs>(ApplicationMenu_Opening); } } void ApplicationMenu_Opening(object sender, EventArgs e) { //检查菜单项,看看之前添加过嘛 if (acApMenuItem == null) { //获取应用程序菜单组件 ApplicationMenu acApMenu = ComponentManager.ApplicationMenu; //创建新菜单项 acApMenuItem = new ApplicationMenuItem(); acApMenuItem.CommandHandler = new MyCommandHandler(); //追加新菜单项 acApMenu.MenuContent.Items.Add(acApMenuItem); //移除事件处理器 ComponentManager.ApplicationMenu.Opening -= new EventHandler<EventArgs>(ApplicationMenu_Opening); } } } /// <summary> /// 修改对象前锁定数据库 /// </summary> [CommandMethod("LockDoc", CommandFlags.Session)] public static void LockDoc() { //新建图形 DocumentCollection acDocMgr = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager; Document acNewDoc = acDocMgr.Add("acad.dwt"); Database acDbNewDoc = acNewDoc.Database; //锁定新文档 using (DocumentLock acLckDoc = acNewDoc.LockDocument()) { //启动新数据库事务 using (Transaction acTrans = acDbNewDoc.TransactionManager.StartTransaction()) { //以读模式打开块表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acDbNewDoc.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开块表记录模型空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //在(5,5)创建一个半径为3的圆 Circle acCirc = new Circle(); acCirc.Center = new Point3d(5, 5, 0); acCirc.Radius = 3; //添加新对象到模型空间和事务 acBlkTblRec.AppendEntity(acCirc); acTrans.AddNewlyCreatedDBObject(acCirc, true); //提交修改 acTrans.Commit(); } //解锁文档(Using 语句到此结束) } //将新文档置为当前 acDocMgr.MdiActiveDocument = acNewDoc; } /// <summary> /// 设置十字光标为全屏幕 /// </summary> [CommandMethod("PrefsSetCursor")] public static void PrefsSetCursor() { //本示例设置绘图窗口的十字光标为全屏 //获得Preferences对象 AcadPreferences acPrefComObj = (AcadPreferences)Autodesk.AutoCAD.ApplicationServices. Application.Preferences; //使用CursorSize属性设置十字光标的大小 acPrefComObj.Display.CursorSize = 100; } /// <summary> /// 隐藏滚动条 /// </summary> [CommandMethod("PrefsSetDisplay")] public static void PrefsSetDisplay() { //本例使滚动条失效 //获得Preferences对象 AcadPreferences acPrefComObj = (AcadPreferences)Autodesk.AutoCAD.ApplicationServices. Application.Preferences; //不显示滚动条 acPrefComObj.Display.DisplayScrollBars = false; } public class Class_FunGridSnap { [CommandMethod("ChangeGridAndSnap")] public static void ChangeGridAndSnap() { //获取当前数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //打开当前视口 ViewportTableRecord acVportTblRec; acVportTblRec = acTrans.GetObject(acDoc.Editor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord; //打开栅格 acVportTblRec.GridEnabled = true; //调整栅格间距为1,1 acVportTblRec.GridIncrements = new Point2d(1, 1); //打开当前视口的捕捉模式 acVportTblRec.SnapEnabled = true; //调整捕捉间距为0.5,0.5 acVportTblRec.SnapIncrements = new Point2d(0.5, 0.5); //修改捕捉旋转角度为30度(0.524弧度) acVportTblRec.SnapAngle = 0.524; //更新平铺视口的显示 acDoc.Editor.UpdateTiledViewportsFromDatabase(); //提交修改,关闭事务 acTrans.Commit(); } } } /// <summary> /// 获取相对于x轴的角度 /// </summary> [CommandMethod("AngleFromXAxis")] public static void AngleFromXAxis() { Point2d pt1 = new Point2d(2, 5); Point2d pt2 = new Point2d(5, 2); Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Angle from XAxis: " + pt1.GetVectorTo(pt2).Angle.ToString()); } static Point2d PolarPoints(Point2d pPt, double dAng, double dDist) { return new Point2d(pPt.X + dDist * Math.Cos(dAng), pPt.Y + dDist * Math.Sin(dAng)); } static Point3d PolarPoints(Point3d pPt, double dAng, double dDist) { return new Point3d(pPt.X + dDist * Math.Cos(dAng), pPt.Y + dDist * Math.Sin(dAng), pPt.Z); } [CommandMethod("PolarPoints")] public static void PolarPoints() { Point2d pt1 = PolarPoints(new Point2d(5, 2), 0.785398, 12); Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("\nPolarPoint: " + "\nX=" + pt1.X + "\nY=" + pt1.Y); Point3d pt2 = PolarPoints(new Point3d(5, 2, 0), 0.785398, 12); Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("\nPolarPoint: " + "\nX=" + pt2.X + "\nY=" + pt2.Y + "\nZ=" + pt2.Z); } /// <summary> /// 用Distance()计算两点间距离 /// </summary> [CommandMethod("GetDistanceBetweenTwoPoints")] public static void GetDistanceBetweenTwoPoints() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; PromptDoubleResult pDbRes; pDbRes = acDoc.Editor.GetDistance("\nPick two points: "); Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("\nDistance between points: " + pDbRes.Value.ToString()); } /// <summary> /// 计算由用户输入点定义的面积 /// </summary> [CommandMethod("CalculateDefinedArea")] public static void CalculateDefinedArea() { //提示用户输入5个点 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; PromptPointResult pPtRes; Point2dCollection colPt = new Point2dCollection(); PromptPointOptions pPtOpts = new PromptPointOptions(""); //提示输入第一个点 pPtOpts.Message = "\nSpecify first point: "; pPtRes = acDoc.Editor.GetPoint(pPtOpts); colPt.Add(new Point2d(pPtRes.Value.X, pPtRes.Value.Y)); //如果用户按ESC键或取消命令就退出 if (pPtRes.Status == PromptStatus.Cancel) return; int nCounter = 1; while (nCounter <= 4) { //提示下一个点 switch (nCounter) { case 1: pPtOpts.Message = "\nSpecify second point: "; break; case 2: pPtOpts.Message = "\nSpecify third point: "; break; case 3: pPtOpts.Message = "\nSpecify fourth point: "; break; case 4: pPtOpts.Message = "\nSpecify fifth point: "; break; } //用前一个点作为基点 pPtOpts.UseBasePoint = true; pPtOpts.BasePoint = pPtRes.Value; pPtRes = acDoc.Editor.GetPoint(pPtOpts); colPt.Add(new Point2d(pPtRes.Value.X, pPtRes.Value.Y)); if (pPtRes.Status == PromptStatus.Cancel) return; //计数加1 nCounter = nCounter + 1; } //用5个点创建多段线 //所有的2D实体对象和3D实体对象都实现了IDisposable,故可以使用using语句 using (Polyline acPoly = new Polyline()) { acPoly.AddVertexAt(0, colPt[0], 0, 0, 0); acPoly.AddVertexAt(1, colPt[1], 0, 0, 0); acPoly.AddVertexAt(2, colPt[2], 0, 0, 0); acPoly.AddVertexAt(3, colPt[3], 0, 0, 0); acPoly.AddVertexAt(4, colPt[4], 0, 0, 0); //闭合多段线 acPoly.Closed = true; //查询多段线面积 Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Area of polyline: " + acPoly.Area.ToString()); } //销毁多段线 } /// <summary> /// 从AutoCAD命令行获取用户输入的字符串--GetString() /// </summary> [CommandMethod("GetStringFromUser")] public static void GetStringFromUser() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: "); pStrOpts.AllowSpaces = true; PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("The name entered was: " + pStrRes.StringResult); } /// <summary> /// 获取用户选取的点---GetPoint() /// </summary> [CommandMethod("GetPointsFromUser")] public static void GetPointsFromUser() { //获取当前数据库,启动事务管理器 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); //提示起点 pPtOpts.Message = "\nEnter the start point of the line: "; pPtRes = acDoc.Editor.GetPoint(pPtOpts); Point3d ptStart = pPtRes.Value; //如果用户按ESC键或取消命令,就退出 if (pPtRes.Status == PromptStatus.Cancel) return; //提示终点 pPtOpts.Message = "\nEnter the end point of the line: "; pPtOpts.UseBasePoint = true; pPtOpts.BasePoint = ptStart; pPtRes = acDoc.Editor.GetPoint(pPtOpts); Point3d ptEnd = pPtRes.Value; if (pPtRes.Status == PromptStatus.Cancel) return; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { BlockTable acBlkTbl; BlockTableRecord acBlkTblRec; //以写模式打开模型空间 acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建直线 Line acLine = new Line(ptStart, ptEnd); //添加直线 acBlkTblRec.AppendEntity(acLine); acTrans.AddNewlyCreatedDBObject(acLine, true); //缩放图形到全部显示 acDoc.SendStringToExecute("._zoom _all", true, false, false); //提交修改,关闭事务 acTrans.Commit(); } } /// <summary> /// 从命令行中获取关键字 /// </summary> [CommandMethod("GetKeywordFromUser2")] public static void GetKeywordFromUser2() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nEnter an option "; pKeyOpts.Keywords.Add("Line"); pKeyOpts.Keywords.Add("Circle"); pKeyOpts.Keywords.Add("Arc"); pKeyOpts.AllowNone = true; PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts); Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Entered keyword: " + pKeyRes.StringResult); } /// <summary> /// 限制用户输入 /// </summary> [CommandMethod("GetIntegerOrKeywordFromUser")] public static void GetIntegerOrKeywordFromUser() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; PromptIntegerOptions pIntOpts = new PromptIntegerOptions(""); pIntOpts.Message = "\nEnter the size or "; //限制输入必须大于0 pIntOpts.AllowZero = false; pIntOpts.AllowNegative = false; //定义合法关键字并允许直接按Enter键 pIntOpts.Keywords.Add("Big"); pIntOpts.Keywords.Add("Small"); pIntOpts.Keywords.Add("Regular"); pIntOpts.Keywords.Default = "Regular"; pIntOpts.AllowNone = true; //获取用户键入的值 PromptIntegerResult pIntRes = acDoc.Editor.GetInteger(pIntOpts); if (pIntRes.Status == PromptStatus.Keyword) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Entered keyword: " + pIntRes.StringResult); } else { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Entered value: " + pIntRes.Value.ToString()); } } /// <summary> /// 发送一个命令到AutoCAD命令行 /// </summary> [CommandMethod("SendACommandToAutoCAD")] public static void SendACommandToAutoCAD() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; //画圆并缩放到图形界限 acDoc.SendStringToExecute("._circle 2,2,0 4 ", true, false, false); acDoc.SendStringToExecute("._zoom _all ", true, false, false); } /// <summary> /// 使用事务打开并查询对象 /// </summary> [CommandMethod("OpenTransactionManager")] public static void OpenTransactionManager() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以读模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; //遍历块表记录 foreach (ObjectId asObjId in acBlkTblRec) { acDoc.Editor.WriteMessage("\nDXF name: " + asObjId.ObjectClass.DxfName); acDoc.Editor.WriteMessage("\nObjectID: " + asObjId.ToString()); acDoc.Editor.WriteMessage("\nHandle: " + asObjId.Handle.ToString()); acDoc.Editor.WriteMessage("\n"); } }//关闭事务 } /// <summary> /// 使用事务向数据库添加对象 /// </summary> [CommandMethod("AddNewCircleTransaction")] public static void AddNewCircleTransaction() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //以半径3圆心5,5画圆 Circle acCirc = new Circle(); acCirc.Center = new Point3d(5, 5, 0); acCirc.Radius = 3; //将新对象添加到Model空间并进行事务登记 acBlkTblRec.AppendEntity(acCirc); acTrans.AddNewlyCreatedDBObject(acCirc, true); //提交修改并关闭事务 acTrans.Commit(); } } /// <summary> /// 使用嵌套事务创建对象 /// </summary> [CommandMethod("NestedTransactions")] public static void NestedTransactions() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //创建对事务管理器的引用 Autodesk.AutoCAD.DatabaseServices.TransactionManager acTransMgr; acTransMgr = acCurDb.TransactionManager; //新建事务 using (Transaction acTrans1 = acTransMgr.StartTransaction()) { //打印当前活动事务的个数 acDoc.Editor.WriteMessage("\nNumber of transaction active: " + acTransMgr.NumberOfActiveTransactions.ToString()); //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans1.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans1.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建半径2 圆心5,5的圆 Circle acCirc = new Circle(); acCirc.Center = new Point3d(5, 5, 0); acCirc.Radius = 3; //添加新对象到模型空间并添加新事务 acBlkTblRec.AppendEntity(acCirc); acTrans1.AddNewlyCreatedDBObject(acCirc, true); //创建第2个事务 using (Transaction acTrans2 = acTransMgr.StartTransaction()) { acDoc.Editor.WriteMessage("\nNumber of transaction actives: " + acTransMgr.NumberOfActiveTransactions.ToString()); //修改圆的颜色 acCirc.ColorIndex = 5; //新建一天直线 Line acLine = new Line(new Point3d(2, 5, 0), new Point3d(10, 7, 0)); acLine.ColorIndex = 3; //将直线对象添加到Model空间并进行事务登记(事务2) acBlkTblRec.AppendEntity(acLine); acTrans2.AddNewlyCreatedDBObject(acLine, true); //创建第3个事务 using (Transaction acTrans3 = acTransMgr.StartTransaction()) { acDoc.Editor.WriteMessage("\nNumber of transactions active: " + acTransMgr.NumberOfActiveTransactions.ToString()); //修改圆的颜色 acCirc.ColorIndex = 3; //更新图形显示 acDoc.Editor.WriteMessage("\n"); acDoc.Editor.Regen(); //询问保留还是取消第3个事务中的修改 PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nKeep color change "; pKeyOpts.Keywords.Add("Yes"); pKeyOpts.Keywords.Add("No"); pKeyOpts.Keywords.Default = "No"; pKeyOpts.AllowNone = true; PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts); if (pKeyRes.StringResult == "No") { //取消事务3中的修改 acTrans3.Abort(); } else { //保存事务3中的修改 acTrans3.Commit(); } acDoc.Editor.WriteMessage("\nNumber of transactions active: " + acTransMgr.NumberOfActiveTransactions.ToString()); //保留事务2中的修改 acTrans2.Commit(); } acDoc.Editor.WriteMessage("\nNumber of transactions active: " + acTransMgr.NumberOfActiveTransactions.ToString()); //保留事务1中的修改 acTrans1.Commit(); } } } /// <summary> /// 使用事务查询对象 /// </summary> [CommandMethod("OpenCloseObjectId")] public static void OpenCloseObjectId() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager. MdiActiveDocument; Database acCurDb = acDoc.Database; //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acCurDb.BlockTableId.Open(OpenMode.ForRead) as BlockTable; //以读模式打开模型空间记录 BlockTableRecord acBlkTblRec; acBlkTblRec = acBlkTbl[BlockTableRecord.ModelSpace].Open(OpenMode.ForRead) as BlockTableRecord; //遍历块表记录 foreach (ObjectId acObjId in acBlkTblRec) { acDoc.Editor.WriteMessage("\nDXF name: " + acObjId.ObjectClass.DxfName); acDoc.Editor.WriteMessage("\nObjectID: " + acObjId.ToString()); acDoc.Editor.WriteMessage("\nHandle: " + acObjId.Handle.ToString()); acDoc.Editor.WriteMessage("\n"); } //关闭块表记录 acBlkTblRec.Close(); acBlkTblRec.Dispose(); //关闭块表 acBlkTbl.Close(); acBlkTbl.Dispose(); } /// <summary> /// 以通知方式打开对象 /// </summary> [CommandMethod("FreezeDoorLayer")] public static void FreezeDoorLayer() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开图层表 LayerTable acLyrTbl; acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; //遍历图层,将图层名以“Door”开头的图层升级为写打开 foreach (ObjectId acObjId in acLyrTbl) { //以读模式打开图层表记录以读打开图层表记录 LayerTableRecord acLyrTblRec; acLyrTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as LayerTableRecord; //检查图层名是否以“Door”开头 if (acLyrTblRec.Name.StartsWith("Door", StringComparison.OrdinalIgnoreCase) == true) { //检查是否为当前层 if (acLyrTblRec.ObjectId != acCurDb.Clayer) { //升级打开模式 acLyrTblRec.UpgradeOpen(); //冻结图层 acLyrTblRec.IsFrozen = true; } } } //提交修改并关闭事务 acTrans.Commit(); } } /// <summary> /// 访问模型/图纸空间 /// </summary> [CommandMethod("AccessSpace")] public static void AccessSpace() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以读模式打开块表表记录 BlockTableRecord acBlkTblRec; //打开的是哪个块表记录? PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nEnter which space to create the line in "; pKeyOpts.Keywords.Add("Model"); pKeyOpts.Keywords.Add("Paper"); pKeyOpts.Keywords.Add("Current"); pKeyOpts.AllowNone = false; pKeyOpts.AppendKeywordsToMessage = true; PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts); if (pKeyRes.StringResult == "Model") { //从Block表获取Model空间的ObjectID acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; } else if (pKeyRes.StringResult == "Paper") { //从Block表获取Paper空间的ObjectID acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.PaperSpace], OpenMode.ForWrite) as BlockTableRecord; } else { //从数据库获取当前空间的ObjectID acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; } //从(2,5)到(10,7)画一条直线 Line acLine = new Line(new Point3d(2, 5, 0), new Point3d(10, 7, 0)); //添加新对象到块表记录并添加事务 acBlkTblRec.AppendEntity(acLine); acTrans.AddNewlyCreatedDBObject(acLine, true); //保存新直线到数据库 acTrans.Commit(); } } /// <summary> /// 创建一条直线 /// </summary> [CommandMethod("AddLine")] public static void AddLine() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Create a line Line acLine = new Line(new Point3d(5, 5, 0), new Point3d(12, 3, 0)); //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acLine); acTrans.AddNewlyCreatedDBObject(acLine, true); //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 创建一个Polyline对象 /// </summary> [CommandMethod("AddLightweightPolyline")] public static void AddLightweightPolyline() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Create a polyline with two segments(3 points) Polyline acPoly = new Polyline(); acPoly.AddVertexAt(0, new Point2d(2, 4), 0, 0, 0); acPoly.AddVertexAt(1, new Point2d(4, 2), 0, 0, 0); acPoly.AddVertexAt(2, new Point2d(6, 4), 0, 0, 0); //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acPoly); acTrans.AddNewlyCreatedDBObject(acPoly, true); //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 添加一个圆 /// </summary> [CommandMethod("AddCircle")] public static void AddCircle() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建圆,圆心(2,3),半径4.25 Circle acCirc = new Circle(); acCirc.Center = new Point3d(2, 3, 0); acCirc.Radius = 4.25; //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acCirc); acTrans.AddNewlyCreatedDBObject(acCirc, true); //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 添加圆弧 /// </summary> [CommandMethod("AddArc")] public static void AddArc() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //已知圆心、半径、起止角,创建圆弧 Arc acArc = new Arc(new Point3d(6.25, 9.125, 0), 6, 1.117, 3.5605); //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acArc); acTrans.AddNewlyCreatedDBObject(acArc, true); //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 创建样条曲线 /// </summary> [CommandMethod("AddSpline")] public static void AddSpline() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //定义样条曲线的拟合点 Point3dCollection ptColl = new Point3dCollection(); ptColl.Add(new Point3d(0, 0, 0)); ptColl.Add(new Point3d(5, 5, 0)); ptColl.Add(new Point3d(10, 0, 0)); //获取点(0.5,0.5,0)的3D矢量 Vector3d vecTan = new Point3d(0.5, 0.5, 0).GetAsVector(); //创建通过3个点的样条曲线,且起止点的切线方向为(0.5,0.5,0); //注:在公差值设置为0.0时(第5个参数),样条曲线直接通过拟合点 Spline acSpline = new Spline(ptColl, vecTan, vecTan, 4, 0.0); //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acSpline); acTrans.AddNewlyCreatedDBObject(acSpline, true); //保存新对象到数据库 acTrans.Commit(); } } /// <summary> /// 创建一个点对象并修改其形状 /// </summary> [CommandMethod("AddPointAndSetPointStyle")] public static void AddPointAndSetPointStyle() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //在Model空间创建点(4,3,0) DBPoint acPoint = new DBPoint(new Point3d(4, 3, 0)); //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acPoint); acTrans.AddNewlyCreatedDBObject(acPoint, true); //设置图形中所有点的样式 acCurDb.Pdmode = 34; acCurDb.Pdsize = 1; //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 创建一个实体填充对象 /// </summary> [CommandMethod("Add2DSolid")] public static void Add2DSolid() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //在Model空间创建四边形实体(蝴蝶结) Solid ac2DSolidBow = new Solid(new Point3d(0, 0, 0), new Point3d(5, 0, 0), new Point3d(5, 8, 0), new Point3d(0, 8, 0)); //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(ac2DSolidBow); acTrans.AddNewlyCreatedDBObject(ac2DSolidBow, true); //在Model空间创建矩形实体 Solid ac2DSolidSqr = new Solid(new Point3d(10, 0, 0), new Point3d(15, 0, 0), new Point3d(10, 8, 0), new Point3d(15, 8, 0)); //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(ac2DSolidSqr); acTrans.AddNewlyCreatedDBObject(ac2DSolidSqr, true); //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 创建一个简单面域 /// </summary> [CommandMethod("AddRegion")] public static void AddRegion() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block块表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //在内存创建一个圆 using (Circle acCirc = new Circle()) { acCirc.Center = new Point3d(2, 2, 0); acCirc.Radius = 5; //将圆添加到对象数组 DBObjectCollection acDBObjColl = new DBObjectCollection(); acDBObjColl.Add(acCirc); //基于每个闭环计算面域 DBObjectCollection myRegionColl = new DBObjectCollection(); myRegionColl = Autodesk.AutoCAD.DatabaseServices.Region.CreateFromCurves(acDBObjColl); Autodesk.AutoCAD.DatabaseServices.Region acRegion = myRegionColl[0] as Autodesk.AutoCAD.DatabaseServices.Region; //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acRegion); acTrans.AddNewlyCreatedDBObject(acRegion, true); //处置内存中的圆,不添加到数据库 } //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 创建组合面域 /// </summary> [CommandMethod("CreateCompositionRegions")] public static void CreateCompositeRegions() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //在内存建两个圆 Circle acCirc1 = new Circle(); acCirc1.Center = new Point3d(4, 4, 0); acCirc1.Radius = 2; Circle acCirc2 = new Circle(); acCirc2.Center = new Point3d(4, 4, 0); acCirc2.Radius = 1; //将圆添加到对象数组 DBObjectCollection acDBObjColl = new DBObjectCollection(); acDBObjColl.Add(acCirc1); acDBObjColl.Add(acCirc2); //基于每个闭环计算面域 DBObjectCollection myRegionColl = new DBObjectCollection(); myRegionColl = Autodesk.AutoCAD.DatabaseServices.Region. CreateFromCurves(acDBObjColl); Autodesk.AutoCAD.DatabaseServices.Region acRegion1 = myRegionColl[0] as Autodesk.AutoCAD.DatabaseServices.Region; Autodesk.AutoCAD.DatabaseServices.Region acRegion2 = myRegionColl[1] as Autodesk.AutoCAD.DatabaseServices.Region; //从面域2减去面域1 if (acRegion1.Area > acRegion2.Area) { //从较大面域中减去较小面域 acRegion1.BooleanOperation(BooleanOperationType.BoolSubtract, acRegion2); acRegion2.Dispose(); //将最终的面域添加到数据库 acBlkTblRec.AppendEntity(acRegion1); acTrans.AddNewlyCreatedDBObject(acRegion1, true); } else { //从较大面域中减去较小面域 acRegion2.BooleanOperation(BooleanOperationType.BoolSubtract, acRegion1); acRegion1.Dispose(); //将最终的面域添加到数据库 acBlkTblRec.AppendEntity(acRegion2); acTrans.AddNewlyCreatedDBObject(acRegion2, true); } //销毁内存中的两个圆对象 acCirc1.Dispose(); acCirc2.Dispose(); //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 创建Hatch对象 /// </summary> [CommandMethod("AddHatch")] public static void AddHatch() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建一个圆作为填充的封闭边界 Circle acCirc = new Circle(); acCirc.Center = new Point3d(3, 3, 0); acCirc.Radius = 1; //将圆添加到块表记录和事务 acBlkTblRec.AppendEntity(acCirc); acTrans.AddNewlyCreatedDBObject(acCirc, true); //将圆的ObjectId添加到对象数组 ObjectIdCollection acObjIdColl = new ObjectIdCollection(); acObjIdColl.Add(acCirc.ObjectId); //创建填充对象并添加到块表记录 Hatch acHatch = new Hatch(); acBlkTblRec.AppendEntity(acHatch); acTrans.AddNewlyCreatedDBObject(acHatch, true); //设置填充对象的属性 //在调用AppendLoop之前设置填充对象的关联属性 acHatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31"); acHatch.Associative = true; acHatch.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl); acHatch.EvaluateHatch(true); //将新对象保存到数据库 acTrans.Commit(); } } /// <summary> /// 获取PickFirst选择集 /// </summary> [CommandMethod("ChenkForPickfirstSelection", CommandFlags.UsePickSet)] public static void CheckForPickfirstSelection() { //获取当前文档 Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //获取PickFirst选择集 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.SelectImplied(); SelectionSet acSSet; //如果提示状态OK,说明启动命令前选择了对象 if (acSSPrompt.Status == PromptStatus.OK) { acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Number of objects in Pickfirst selection: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects in Pickfirst selection of: 0"); } //清空PickFirst选择集 ObjectId[] idarrayEmpty = new ObjectId[0]; acDocEd.SetImpliedSelection(idarrayEmpty); //请求从图形区域选择对象 acSSPrompt = acDocEd.GetSelection(); //如果提示状态OK,表示已选择对象 if (acSSPrompt.Status == PromptStatus.OK) { acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: 0"); } } /// <summary> /// 提示选择屏幕上的对象并遍历选择集 /// </summary> [CommandMethod("SelectObjectsOnscreen")] public static void SelectObjectOnscreen() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //请求在图形区域选择对象 PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(); //如果提示状态OK,表示已选择对象 if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; //遍历选择集内的对象 foreach (SelectedObject acSSObj in acSSet) { //确认返回的是合法的SelectedObject对象 if (acSSObj != null) { //以写模式打开所选对象 Entity acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as Entity; if (acEnt != null) { //将对象颜色修改为绿色 acEnt.ColorIndex = 3; } } } //保存新对象到数据库 acTrans.Commit(); } } } /// <summary> /// 选择与窗口相交的对象 /// </summary> [CommandMethod("SelectObjectsByCrossingWindow")] public static void SelectObjectsByCrossingWindow() { //获取当前文档编辑器 Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //从(2,2,0)到(10,8,0)创建一个交叉窗口 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.SelectCrossingWindow(new Point3d(2, 2, 0), new Point3d(10, 8, 0)); //如果提示状态OK,表示已选择对象 if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: 0"); } } /// <summary> /// 将所选对象添加到选择集 /// </summary> [CommandMethod("MergeSelectionSets")] public static void MergeSelectionSets() { //获取当前文档编辑器 Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //请求在图形区域选择对象 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.GetSelection(); SelectionSet acSSet1; ObjectIdCollection acObjIdColl = new ObjectIdCollection(); //如果提示状态是OK,表示已选择对象 if (acSSPrompt.Status == PromptStatus.OK) { //获取所选对象 acSSet1 = acSSPrompt.Value; //向ObjectIdCollection中追加选择集1的对象 acObjIdColl = new ObjectIdCollection(acSSet1.GetObjectIds()); } //请求在图形区域选择对象 acSSPrompt = acDocEd.GetSelection(); SelectionSet acSSet2; //如果提示状态OK,表示已选择对象 if (acSSPrompt.Status == PromptStatus.OK) { acSSet2 = acSSPrompt.Value; //检查ObjectIdCollection集合大小,如果为0就用选择集2对其初始化 if (acObjIdColl.Count == 0) { acObjIdColl = new ObjectIdCollection(acSSet2.GetObjectIds()); } else { //遍历选择集2 foreach (ObjectId acObjId in acSSet2.GetObjectIds()) { //将第二个选择集中的每个对象添加到集合内 acObjIdColl.Add(acObjId); } } } Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acObjIdColl.Count.ToString()); } /// <summary> /// 为选择集制定选择条件 /// </summary> [CommandMethod("FilterSelectionSet")] public static void FilterSelectionSet() { //获取当前文档编辑器 Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //创建一个TypedValue数组来定义过滤器条件 TypedValue[] acTypValAr = new TypedValue[1]; acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 0); //将过滤器条件赋值给SelectionFilter对象 SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); //请求用户在图形区域选择对象 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.GetSelection(acSelFtr); //提示状态OK,表示已选择对象 if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: 0"); } } /// <summary> /// 选择满足两个过滤条件的对象 /// </summary> [CommandMethod("FilterBlueCircleOnLayer")] public static void FilterBlueCircleOnLayer0() { //获取当前文档编辑器 Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //创建TypedValue数组定义过滤条件 TypedValue[] acTypValAr = new TypedValue[3]; acTypValAr.SetValue(new TypedValue((int)DxfCode.Color, 5), 0); acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 1); acTypValAr.SetValue(new TypedValue((int)DxfCode.LayerName, "0"), 2); //将过滤条件赋值给SelectionFilter对象 SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); //请求在图形区域选择对象 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.GetSelection(acSelFtr); //如果提示状态OK,表示对象已选 if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: 0"); } } /// <summary> /// 选择半径大于等于5的圆 /// </summary> [CommandMethod("FilterRelational")] public static void FilterRelational() { //获取当前文档编辑器 Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //创建TypedValue数组,定义过滤条件 TypedValue[] acTypValAr = new TypedValue[3]; acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 0); acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, ">="), 1); acTypValAr.SetValue(new TypedValue(40, 5), 2); //将过滤条件赋给SelectionFilter对象 SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); //请求在图形区域选择对象 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.GetSelection(acSelFtr); //如果提示状态OK,表示对象已选 if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: 0"); } } /// <summary> /// 获取单行或多行文字 /// </summary> [CommandMethod("FilterForText")] public static void FilterForText() { //获取当前文档editor Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //创建TypedValue数组,定义过滤条件 TypedValue[] acTypValAr = new TypedValue[4]; acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "<OR"), 0); acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "TEXT"), 1); acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "MTEXT"), 2); acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), 3); //将过滤条件赋给SelectionFilter对象 SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); //请求在图形区域选择对象 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.GetSelection(acSelFtr); //如果提示状态OK,说明已选对象 if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: 0"); } } /// <summary> /// 选择具有通配符的过滤条件 /// </summary> [CommandMethod("FilterMtextWildcard")] public static void FilterMtextWildcard() { //获取当前文档编辑器 Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //创建TypedValue数组,定义过滤条件 TypedValue[] acTypValAr = new TypedValue[2]; acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "MTEXT"), 0); acTypValAr.SetValue(new TypedValue((int)DxfCode.Text, "*The*"), 1); //将过滤条件赋给SelectionFilter对象 SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); //请求在图形区域选择对象 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.GetSelection(acSelFtr); //如果提示状态OK,说明已选对象 if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: 0"); } } /// <summary> /// 选择含有拓展元素的圆 /// </summary> [CommandMethod("FilterXdata")] public static void FilterXdata() { //获取当前文档编辑器 Editor acDocEd = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument.Editor; //创建TypedValue数组,定义过滤条件 TypedValue[] acTypValAr = new TypedValue[2]; acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "Circle"), 0); acTypValAr.SetValue(new TypedValue((int)DxfCode.ExtendedDataRegAppName, "MY_APP"), 1); //将过滤条件赋给SelectionFilter对象 SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); //请求在图形区域选择对象 PromptSelectionResult acSSPrompt; acSSPrompt = acDocEd.GetSelection(acSelFtr); //如果提示状态OK,说明已选对象 if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Number of objects selected: 0"); } } /// <summary> /// 删除所有未引用的图层 /// </summary> [CommandMethod("PurgeUnreferencedLayers")] public static void PurgeUnreferencedLayers() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开图层表 LayerTable acLyrTbl; acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; //创建一个ObjectIdCollection对象来保存每个图层表记录的objectid ObjectIdCollection acObjIdColl = new ObjectIdCollection(); //遍历图层表并将每个图层添加到ObjectIdCollection foreach (ObjectId acObjId in acLyrTbl) { acObjIdColl.Add(acObjId); } //从集合中删除还在使用的图层,返回可以删除的对象集合 //调用Purge方法:传入参数-ObjectIdCollection对象 //返回-更新了的ObjectIdCollection对象,包含可以删除的图层 acCurDb.Purge(acObjIdColl); //遍历返回的ObjectIdCollection对象,并删除未引用的图层 foreach (ObjectId acObjId in acObjIdColl) { SymbolTableRecord acSymTblRec; acSymTblRec = acTrans.GetObject(acObjId, OpenMode.ForWrite) as SymbolTableRecord; try { //删除未引用的图层 acSymTblRec.Erase(true); } catch (Autodesk.AutoCAD.Runtime.Exception Ex) { //不能删除图层 Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Error:\n" + Ex.Message); } } //提交修改,关闭事务 acTrans.Commit(); } } /// <summary> /// 重命名图层 /// </summary> [CommandMethod("RenameLayer")] public static void RenameLayer() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //返回当前数据库的图层表 LayerTable acLyrTbl; acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite) as LayerTable; //克隆图层0(复制其及其属性) LayerTableRecord acLyrTblRec; acLyrTblRec = acTrans.GetObject(acLyrTbl["0"], OpenMode.ForRead).Clone() as LayerTableRecord; //修改克隆得到的图层名称 acLyrTblRec.Name = "MyLayer"; //使用图层MyLayer可用 acLyrTbl.Add(acLyrTblRec); acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true); //提交修改,关闭事务 acTrans.Commit(); } } /// <summary> /// 创建一个多段线并删除它 /// </summary> [CommandMethod("EraseObject")] public static void EraseObject() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开Block表记录Model空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建轻量多段线 Polyline acPoly = new Polyline(); acPoly.AddVertexAt(0, new Point2d(2, 4), 0, 0, 0); acPoly.AddVertexAt(1, new Point2d(4, 2), 0, 0, 0); acPoly.AddVertexAt(2, new Point2d(6, 4), 0, 0, 0); //添加新对象到块表记录和事务 acBlkTblRec.AppendEntity(acPoly); acTrans.AddNewlyCreatedDBObject(acPoly, true); //更新显示并显示一条告警信息 acDoc.Editor.Regen(); Autodesk.AutoCAD.ApplicationServices.Application. ShowAlertDialog("Erase the newly added polyline."); //从图形中删除多段线 acPoly.Erase(true); //提交修改 acTrans.Commit(); } } /// <summary> /// 复制单个对象 /// </summary> [CommandMethod("SingleCopy")] public static void SingleCopy() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开块表记录模型空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建圆,圆心(2,3) 半径4.25 Circle acCirc = new Circle(); acCirc.Center = new Point3d(2, 3, 0); acCirc.Radius = 4.25; //将新对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acCirc); acTrans.AddNewlyCreatedDBObject(acCirc, true); //创建圆的拷贝,修改拷贝的半径 Circle acCircClone = acCirc.Clone() as Circle; acCircClone.Radius = 1; //将拷贝的圆添加到块表记录和事务 acBlkTblRec.AppendEntity(acCircClone); acTrans.AddNewlyCreatedDBObject(acCircClone, true); //保存新对象到数据库 acTrans.Commit(); } } /// <summary> /// 复制多个对象 /// </summary> [CommandMethod("MultipleCopy")] public static void MultipleCopy() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开块表记录模型空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建圆 圆心(0,0,0) 半径5 Circle acCirc1 = new Circle(); acCirc1.Center = new Point3d(0, 0, 0); acCirc1.Radius = 5; //添加对象到块表记录和事务 acBlkTblRec.AppendEntity(acCirc1); acTrans.AddNewlyCreatedDBObject(acCirc1, true); //创建圆 圆心0,0,0 半径7 Circle acCirc2 = new Circle(); acCirc2.Center = new Point3d(0, 0, 0); acCirc2.Radius = 7; //添加对象到块表记录和事务 acBlkTblRec.AppendEntity(acCirc2); acTrans.AddNewlyCreatedDBObject(acCirc2, true); //将所有要复制的对象添加到集合 DBObjectCollection acDBObjectColl = new DBObjectCollection(); acDBObjectColl.Add(acCirc1); acDBObjectColl.Add(acCirc2); foreach (Entity acEnt in acDBObjectColl) { Entity acEntClone; acEntClone = acEnt.Clone() as Entity; acEntClone.ColorIndex = 1; //创建一个变换矩阵,每个副本实体向右移动15个单位 acEntClone.TransformBy(Matrix3d.Displacement(new Vector3d(15, 0, 0))); //将克隆对象添加到块表记录和事务 acBlkTblRec.AppendEntity(acEntClone); acTrans.AddNewlyCreatedDBObject(acEntClone, true); } //保存新对象到数据库 acTrans.Commit(); } } /// <summary> /// 从一个数据库复制对象到另一个数据库 /// </summary> [CommandMethod("CopyObjectsBetweenDatabases",CommandFlags.Session)] public static void CopyObjectsBetweenDatabases() { ObjectIdCollection acObjIdColl = new ObjectIdCollection(); //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //锁定当前文档 using (DocumentLock acLckDocCur = acDoc.LockDocument()) { //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开块表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开块表记录模型空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建圆,圆心(0,0,0),半径5 Circle acCirc1 = new Circle(); acCirc1.Center = new Point3d(0, 0, 0); acCirc1.Radius = 5; //添加到块表记录和事务 acBlkTblRec.AppendEntity(acCirc1); acTrans.AddNewlyCreatedDBObject(acCirc1, true); //创建圆,圆心(0,0,0),半径7 Circle acCirc2 = new Circle(); acCirc2.Center = new Point3d(0, 0, 0); acCirc2.Radius = 7; //添加到块表记录和事务 acBlkTblRec.AppendEntity(acCirc2); acTrans.AddNewlyCreatedDBObject(acCirc2, true); //添加到要复制对象集合内 acObjIdColl = new ObjectIdCollection(); acObjIdColl.Add(acCirc1.ObjectId); acObjIdColl.Add(acCirc2.ObjectId); //保存到数据库 acTrans.Commit(); } } //获取图形模板路径和文件 string sLocalRoot = Autodesk.AutoCAD.ApplicationServices.Application. GetSystemVariable("LOCALROOTPREFIX") as string; string sTemplatePath = sLocalRoot + "Template\\acad.dwt"; //新建一个图形,我们将两个圆复制到这个新图形里 DocumentCollection acDocMgr = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager; Document acNewDoc = acDocMgr.Add(sTemplatePath); Database acDbNewDoc = acNewDoc.Database; //锁定新文档 using (DocumentLock acLckDoc = acNewDoc.LockDocument()) { //启动新文档的事务 using (Transaction acTrans = acDbNewDoc.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTblNewDoc; acBlkTblNewDoc = acTrans.GetObject(acDbNewDoc.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开块表记录模型空间 BlockTableRecord acBlkTblRecNewDoc; acBlkTblRecNewDoc = acTrans.GetObject(acBlkTblNewDoc[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; //克隆对象到新数据库 IdMapping acIdMap = new IdMapping(); acCurDb.WblockCloneObjects(acObjIdColl, acBlkTblRecNewDoc.ObjectId, acIdMap, DuplicateRecordCloning.Ignore, false); //保存复制的对象到数据库 acTrans.Commit(); } } //将新文档设置为当前文档 acDocMgr.MdiActiveDocument = acNewDoc; } /// <summary> /// 偏移多段线 /// </summary> [CommandMethod("OffsetObject")] public static void OffsetObject() { //获取当前文档和数据库 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application. DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; //启动事务 using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //以读模式打开Block表 BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //以写模式打开块表记录模型空间 BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //创建多段线 Polyline acPoly = new Polyline(); acPoly.AddVertexAt(0, new Point2d(1, 1), 0, 0, 0); acPoly.AddVertexAt(1, new Point2d(1, 2), 0, 0, 0); acPoly.AddVertexAt(2, new Point2d(2, 2), 0, 0, 0); acPoly.AddVertexAt(3, new Point2d(3, 2), 0, 0, 0); acPoly.AddVertexAt(4, new Point2d(4, 4), 0, 0, 0); acPoly.AddVertexAt(5, new Point2d(4, 1), 0, 0, 0); //添加新对象到块表记录和事务 acBlkTblRec.AppendEntity(acPoly); acTrans.AddNewlyCreatedDBObject(acPoly, true); //偏移距离0.25 DBObjectCollection acDbObjColl = acPoly.GetOffsetCurves(0.25); //遍历得到的新对象 foreach (Entity acEnt in acDbObjColl) { //添加每个对象 acBlkTblRec.AppendEntity(acEnt); acTrans.AddNewlyCreatedDBObject(acEnt, true); } //保存新对象到数据库 acTrans.Commit(); } } #endregion
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。