当前位置:网站首页>C# 与CAD二次开发,20220721随笔代码
C# 与CAD二次开发,20220721随笔代码
2022-07-21 18:40:00 【laocooon】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry; // 几何学
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Interop;
[assembly: ExtensionApplication(typeof(InitAndopt.InitClass))] // 加载后的入口
[assembly: CommandClass(typeof(InitAndopt.InitClass))] //执行指令
[assembly: CommandClass(typeof(InitAndopt.OptimizeClass))] // 只执行OptimizeClass中的定义的命令
[assembly: CommandClass(typeof(标注.MyCommands))] //执行指令
[assembly: CommandClass(typeof(新建图层.MyCommands))] //执行指令
[assembly: CommandClass(typeof(选择集.MyCommands))] //执行指令
[assembly: CommandClass(typeof(复制圆.MyCommands))] //执行指令
[assembly: CommandClass(typeof(事件.MyCommands))] //执行指令
[assembly: CommandClass(typeof(块.MyCommands))] //执行指令
namespace 块
{
public class MyCommands
{
[CommandMethod("blockCreate02")]
public void BlockCreate02()
{
//AddEntityByDB aedb = new AddEntityByDB();
Database db = HostApplicationServices.WorkingDatabase;
String blockName = "door";
List<Entity> list = new List<Entity>();
//创建图形,设置门框的左边线
Point3d pt1 = Point3d.Origin;
Point3d pt2 = new Point3d(0, 1, 0);
Point3d pt3 = new Point3d(1, 0, 0);
Line leftLine = new Line(pt1, pt2);
Line rightLine = new Line(pt1, pt3);
Arc arc = new Arc(new Point3d(0, 0, 0), 1, 0, Math.PI / 2.0);
list.Add(leftLine);
list.Add(rightLine);
list.Add(arc);
//调⽤抽取的公共代码块
AddBlockThroughDB(db, blockName, list);
System.Diagnostics.Debug.WriteLine("建立一个块 door");
}
/**
* 以事务的⽅式,创建块对象
*
*/
public void AddBlockThroughDB(Database db, String blockName, List<Entity> ents)
{
Transaction trans = db.TransactionManager.StartTransaction();
BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForWrite);
if (!bt.Has(blockName))
{
BlockTableRecord btr = new BlockTableRecord();
btr.Name = blockName;
for (int ii = 0; ii < ents.Count; ii++)
{
Entity ent = ents[ii];
btr.AppendEntity(ent);
}
bt.Add(btr);
trans.AddNewlyCreatedDBObject(btr, true);
trans.Commit();
}
}
[CommandMethod("InsertDoor")]
public void InsertDoor()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
BlockTableRecord space =(BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace],OpenMode.ForWrite);
//判断名为“door”的块是否存在
if (!bt["door"].IsNull)
{
BlockReference br = new BlockReference(Point3d.Origin, bt["door"]);
br.ScaleFactors = new Scale3d(2.0);//设置尺⼨为原来2倍
space.AppendEntity(br);
BlockTableRecord record =trans.GetObject(bt["door"], OpenMode.ForRead) as BlockTableRecord;
if (record.HasAttributeDefinitions)
{
Dictionary<string,string> vals = new Dictionary<string, string>();
vals.Add("⼚家", "喜临门");
vals.Add("价格", "2000");
int i = 0;
foreach (ObjectId id in record)
{
AttributeDefinition definition = id.GetObject(OpenMode.ForRead) as AttributeDefinition;
if (definition != null)
{
// 建立一个新的属性对象
AttributeReference attr = new AttributeReference();
attr.SetAttributeFromBlock(definition,br.BlockTransform);
attr.Rotation = br.Rotation;
attr.Position =new Point3d(br.Position.X, br.Position.Y+i*0.5, 0);
attr.AdjustAlignment(db);
// 判断是否包含了指定的属性名称
if (vals.ContainsKey(definition.Tag.ToUpper()))
{
attr.TextString = vals[definition.Tag.ToUpper()];
i++;
}
br.AttributeCollection.AppendAttribute(attr);
trans.AddNewlyCreatedDBObject(attr, true);
}
}
}
trans.AddNewlyCreatedDBObject(br, true);
trans.Commit();
}
else
{
return;
}
}
System.Diagnostics.Debug.WriteLine("插入一个 door 大小是 块的 2倍");
}
[CommandMethod("makeAttDoor")]
public void makeAttDoor()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
BlockTableRecord btr = new BlockTableRecord();
btr.Name = "DOOR";
Line line = new Line(new Point3d(0, 0, 0), new Point3d(0, 1, 0));
Arc arc = new Arc(new Point3d(0, 0, 0), 1, 0, Math.PI / 2.0);
btr.AppendEntity(line);
btr.AppendEntity(arc);
//属性添加
AttributeDefinition cjAd = new AttributeDefinition(Point3d.Origin, "喜临门", "⼚家", "请输⼊⼚家", ObjectId.Null);
AttributeDefinition jgAd = new AttributeDefinition(Point3d.Origin + new Vector3d(0, 0.25, 0), "2000", "价格", "请输⼊价格", ObjectId.Null);
cjAd.Height = 0.15; jgAd.Height = 0.15;
btr.AppendEntity(cjAd);
btr.AppendEntity(jgAd);
bt.Add(btr);
trans.AddNewlyCreatedDBObject(btr, true);
trans.Commit();
}
System.Diagnostics.Debug.WriteLine("建立一个属性块 DOOR");
}
}
}
namespace 事件
{
public class MyCommands
{
bool bMove;
Point3d startPoint;
Database db = HostApplicationServices.WorkingDatabase;
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
[CommandMethod("AddEvents")]
public void AddEvents()
{
db.ObjectOpenedForModify += ObjectOpenedForModify;
db.ObjectModified += ObjectModified;
doc.CommandWillStart += CommandWillStart;
doc.CommandEnded += CommandEnded;
}
[CommandMethod("RemoveEvents")]
public void RemoveEvents()
{
db.ObjectOpenedForModify -= ObjectOpenedForModify;
db.ObjectModified -= ObjectModified;
doc.CommandWillStart -= CommandWillStart;
doc.CommandEnded -= CommandEnded;
}
void CommandWillStart(object sender, CommandEventArgs e)
{
System.Diagnostics.Debug.WriteLine("\n"+ e.GlobalCommandName + "\n");
if (e.GlobalCommandName == "MOVE")
{
bMove = true;
}
}
void CommandEnded(object sender, CommandEventArgs e)
{
if (bMove == true)
bMove = false;
}
void ObjectOpenedForModify(object sender, ObjectEventArgs e)
{
if (bMove == false)
return;
Circle circle = e.DBObject as Circle;
if (circle != null)
{
startPoint = circle.Center;
System.Diagnostics.Debug.WriteLine("\nstartPoint=" + startPoint.ToString()+"\n");
}
}
void ObjectModified(object sender, ObjectEventArgs e)
{
// 非移动,则直接退出
//断开事件
RemoveEvents();
AddEvents();
//连接事件
}
}
}
namespace 复制圆
{
public class MyCommands
{
[CommandMethod("CloneCircle")]
public static void CloneCircle()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acDb = acDoc.Database;
using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acDb.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkRec;
acBlkRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection();
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;
foreach (SelectedObject acSSObj in acSSet)
{
if (acSSObj != null)
{
Circle acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as Circle;
if (acEnt != null)
{
PromptPointResult ppr;
PromptPointOptions ppo = new PromptPointOptions("");
ppo.Message = "\n 请选择复制圆的圆心:";
ppr = acDoc.Editor.GetPoint(ppo);
Point3d ptCloneCenter = ppr.Value;
if (ppr.Status == PromptStatus.Cancel) return;
Circle acEntClone = acEnt.Clone() as Circle;
acEntClone.Center = ptCloneCenter;
acBlkRec.AppendEntity(acEntClone);
acTrans.AddNewlyCreatedDBObject(acEntClone, true);
}
}
}
}
acTrans.Commit();
}
}
}
}
namespace 选择集
{
public class MyCommands
{
[CommandMethod("SSS")]
public static void SSS()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
using (Transaction tr = doc.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
var circles=btr.Cast<ObjectId>().Where(_=>_.ObjectClass.DxfName.Equals("CIRCLE")).GetEnumerator();
int i = 10;
while (circles.MoveNext())
{
Circle c = ((Circle)circles.Current.GetObject(OpenMode.ForWrite));
c.Radius = 5;
c.ColorIndex = 2;
if (i % 5 == 0)
{
c.Center = new Point3d(i * 2, 0, c.Center.Z);
}
else if (i % 5 == 1)
{
c.Center = new Point3d(i * 2, i * 2, c.Center.Z);
}
else if (i % 5 == 2)
{
c.Center = new Point3d(-i * 2, i * 2, c.Center.Z);
}
else if (i % 5 == 3)
{
c.Center = new Point3d(-i * 2, -i * 2, c.Center.Z);
}
else
{
c.Center = new Point3d(0, -i * 2, c.Center.Z);
}
i++;
}
tr.Commit();
}
}
[CommandMethod("SelectObjectsOnscreen")]
public static void SelectObjectsOnscreen()
{
//获取当前文档和数据库
Document acDoc = 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 = 2; //黄色
}
}
}
}
//提交事务
acTrans.Commit();
}
}
}
}
namespace 新建图层
{
public class MyCommands
{
[CommandMethod("AddMyLayer")]
public void AddMyLayer()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
//启动事务
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
//以读的方式打开图层表
LayerTable acLayTbl;
acLayTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
string sLayName = "MyLayer";
if (acLayTbl.Has(sLayName) == false)
{
LayerTableRecord acLayRec = new LayerTableRecord
{
//赋予图层颜色和名称
Color = Color.FromColorIndex(ColorMethod.ByAci, 2),
Name = sLayName
};
//写的方式打开图层表
acLayTbl.UpgradeOpen();
acLayTbl.Add(acLayRec);
acTrans.AddNewlyCreatedDBObject(acLayRec, true);
}
if (acLayTbl.Has(sLayName) == true)
{
acCurDb.Clayer = acLayTbl[sLayName];
acTrans.Commit();
}
}
}
}
}
namespace 标注
{
public class MyCommands
{
[CommandMethod("DDemo")]
public void DimDemo()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\n 执行DDemo。\n");
System.Diagnostics.Debug.WriteLine("\n执行DDemo。\n");
Database db = HostApplicationServices.WorkingDatabase;
AlignedDimension aDim = new AlignedDimension();
Point3d p1 = new Point3d(10, 10, 0);
Point3d p2 = new Point3d(20, 15, 0);
Line line = new Line(p1, p2);
aDim.XLine1Point = p1;
aDim.XLine2Point = p2;
aDim.DimLinePoint = new Point3d(10, 20, 0);
using (Transaction trans = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
btr.AppendEntity(aDim);
btr.AppendEntity(line);
trans.AddNewlyCreatedDBObject(aDim, true);
trans.AddNewlyCreatedDBObject(line, true);
trans.Commit();
}
}
}
}
namespace InitAndopt
{
public class InitClass : IExtensionApplication
{
[CommandMethod("cmd1")]
public void Cmd1()
{
var dm = Application.DocumentManager;
//foreach (Document doc in dm)
//{
// Application.ShowAlertDialog(doc.Name);
//}
// var newDoc = dm.Add("");
var wd = Application.MainWindow;
//wd.WindowState =Window.State.Minimized;
wd.Text = "测试中";
wd.Location = new System.Drawing.Point(0,0);
// wd.Icon
var mb = Application.MenuBar as AcadMenuBar;
var pm = mb.Item(1); // 编辑
// pm.AddMenuItem( pm.Count,"添加直线1", "FirstLine ");
var ctxMenu = new ContextMenuExtension();
ctxMenu.Title = "自定义菜单";
var newMenuItem = new MenuItem("创立新文档");
newMenuItem.Click += (o, e) => { Application.ShowAlertDialog("发生响应~!"); };
ctxMenu.MenuItems.Add(newMenuItem);
Application.AddDefaultContextMenuExtension(ctxMenu);
var ctxMenu1 = new ContextMenuExtension();
ctxMenu1.Title = "自定义菜单";
var newMenuItem1 = new MenuItem("创立新文档");
newMenuItem1.Click += (o, e) => { Application.ShowAlertDialog("发生响应~!"); };
ctxMenu1.MenuItems.Add(newMenuItem1);
Application.AddObjectContextMenuExtension(RXObject.GetClass(typeof(Line)),ctxMenu1);
//建立了之后 退出程序时 卸载掉
}
public void Initialize()
{
System.Diagnostics.Debug.WriteLine("程序开始初始化。");
System.Diagnostics.Debug.WriteLine(Application.Version.ToString());
// throw new NotImplementedException(); // 没写代码的异常
// 注册按钮
//Cmd1();
Application.BeginQuit += (o, e) => {
// Application.ShowAlertDialog("BeginQuit");
};
Application.BeginDoubleClick += (o, e) => {
Application.ShowAlertDialog("BeginDoubleClick");
};
}
public void Terminate()
{
System.Diagnostics.Debug.WriteLine("程序结束,你可以在内做一些程序的清理工作,如关闭CAD文档");
// throw new NotImplementedException();
}
}
public class OptimizeClass
{
[CommandMethod("helloWord")]
public void SayHello()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\n Hello AutoCAD!");
System.Diagnostics.Debug.WriteLine("输出一行 Hello AutoCAD!");
}
// 1
// 加一条长度为1000的直线
[CommandMethod("FirstLine")]
public void FirstLine()
{
//获取当前活动图形数据库
Database db = HostApplicationServices.WorkingDatabase;
Point3d startPoint = new Point3d(0, 1000, 0);
Point3d endPoint = new Point3d(1000, 1000, 0);
Line line = new Line(startPoint, endPoint);
using (Transaction trans = db.TransactionManager.StartTransaction())
{
//以读的方式打开块表
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
//以写的方式打开模型空间块表记录
BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
//将图形对象信息添加到块表记录中,并返回ObjectId对象
btr.AppendEntity(line);
//把对象添加到事务处理中
trans.AddNewlyCreatedDBObject(line, true);
trans.Commit();//提交事务
}
System.Diagnostics.Debug.WriteLine("FirstLine 已经执行");
}
// 2
// 橡皮筋划线
[CommandMethod("DrawLine")]
public void DrawLine()
{
// 获取当前数据库,启动事务管理器
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acDb = acDoc.Database;
PromptPointResult ppr;
PromptPointOptions ppo = new PromptPointOptions("");
//提示起点
ppo.Message = "\n输入直线的起点:";
ppr = acDoc.Editor.GetPoint(ppo);
Point3d ptStar = ppr.Value;
//如果按ESC键或取消命令,就退出
if (ppr.Status == PromptStatus.Cancel) return;
//提示终点
ppo.Message = "\n输入直线的终点:";
ppo.UseBasePoint = true;
ppo.BasePoint = ptStar;
ppr = acDoc.Editor.GetPoint(ppo);
Point3d ptEnd = ppr.Value;
if (ppr.Status == PromptStatus.Cancel) return;
using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
{
BlockTable acBT;
BlockTableRecord acBTR;
acBT = acTrans.GetObject(acDb.BlockTableId, OpenMode.ForRead) as BlockTable;
//以写的模式打开模型空间
acBTR = acTrans.GetObject(acBT[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
//创建直线
Line acLine = new Line(ptStar, ptEnd);
//添加直线
acBTR.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);
//提交修改,关闭事务
acTrans.Commit();
}
System.Diagnostics.Debug.WriteLine("DrawLine 已经执行");
}
// 3
// 利用多段线绘制矩形
[CommandMethod("DrawRec")]
public static void DrawRec()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acDb = acDoc.Database;
PromptPointResult ppr; // 提示点结果
PromptPointOptions ppo = new PromptPointOptions(""); // 提示点选项
ppo.Message = "\n输入矩形的第一个点\n";
ppr = acDoc.Editor.GetPoint(ppo);
Point3d pt1 = ppr.Value;
if (ppr.Status == PromptStatus.Cancel) return;
ppo.Message = "\n输入矩形的第二个点\n";
ppo.UseBasePoint = true;
ppo.BasePoint = pt1;
ppr = acDoc.Editor.GetPoint(ppo);
Point3d pt2 = ppr.Value;
if (ppr.Status == PromptStatus.Cancel) return;
Point3d pt3 = new Point3d(pt2.X, pt1.Y, 0);
Point3d pt4 = new Point3d(pt1.X, pt2.Y, 0);
using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
{
BlockTable acBtl = acTrans.GetObject(acDb.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBtrec = acTrans.GetObject(acBtl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
//建立矩形
Point3dCollection Rec = new Point3dCollection();
Rec.Add(pt1); Rec.Add(pt3); Rec.Add(pt2); Rec.Add(pt4);
Polyline3d acRec = new Polyline3d(Poly3dType.SimplePoly, Rec, true);
acBtrec.AppendEntity(acRec);
acTrans.AddNewlyCreatedDBObject(acRec, true);
acTrans.Commit();
}
}
}
}
边栏推荐
- Realization of bank card number recognition with OpenCV
- Kotlin 打印错误信息 将错误信息上传到服务器
- How to efficiently backup local data to Tencent cloud
- 本地数据如何高效灾备上腾讯云
- Section 23 of Chapter 2: document operation: Reading
- Les Crawlers du réseau rampent sur le rideau d'excitation de la station B et génèrent des nuages de mots (résumé détaillé des notes)
- 直播预告│智汇云舟“数字孪生智慧园区解决方案”专场
- Let me show you eight fallacies in software design
- Section 19 of Chapter 2: encoding and decoding
- 如何快速开发一个简单实用的MES系统?
猜你喜欢
The difference between rhcsa hard link and soft link, the interpretation of first-class directory, redirection, creating files and directories, deleting files and directories, the use of CP command, t
Section 21 of Chapter 2: operators two
【OpenCV 例程300篇】234. 特征提取之主成分分析(PCA)
Don't be ridiculous. Don't you know what abilities to improve if you want to enter a big factory? (collect quickly)
别闹了,想进大厂还不知道提升哪些方面的能力吗?(赶快收藏)
Flutter教程之sqlite_wrapper新的 Dart 和 Flutter 库,用于 SQLite
时间复杂度吐血总结
Section 25 of Chapter 2: file operation: with and copy
世界上最大的开源基金会 Apache 是如何运作的?
解决API开发痛点,Apipost和Apifox哪个更好?
随机推荐
Speech by Lu Shouqun, honorary chairman of copu, at the 17th open source China open source World Summit Forum
互联网寒冬,3个月如何从功能测试进阶自动化测试?【附学习指南】
找到字符串中所有字母异位词
day02
In the cold winter of the Internet, how can we advance from functional testing to automated testing in three months? [attached learning guide]
Information generation of College Students' back to school list - Tencent cloud scene connector National College Innovation Competition
高校学生返校名单信息生成- 腾讯云场景连接器全国高校创新赛
RHCSA 压缩也解压缩、tar归档命令、文件的上传与下载、sehll中的变量、命令别名、命令历史
COPU名誉主席陆首群在第十七届开源中国开源世界高峰论坛上的致辞
【OpenCV 例程300篇】234. 特征提取之主成分分析(PCA)
Is it safe to open an account on flush? ETF trading rules and fees
Let me show you eight fallacies in software design
Vinco Ventures任命Ted Farnsworth为联合首席执行官
第二章第二十一节:运算符.2
Basic concept of MySQL database and deployment of MySQL version 8.0 (I)
父元素visibility:hidden;子元素设置visibility:visible,子元素显示吗
成品直播源码推荐,设置系统日期时间和时区
在线XML转CSV工具
網絡爬蟲爬取b站勵志彈幕並生成詞雲(精心筆記總結)
The office mode of traditional enterprises is changing. Why do enterprises need digital office?