当前位置:网站首页>C # and CAD secondary development, 20220721 essay code
C # and CAD secondary development, 20220721 essay code
2022-07-22 10:08: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; // geometry
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Interop;
[assembly: ExtensionApplication(typeof(InitAndopt.InitClass))] // Loaded entry
[assembly: CommandClass(typeof(InitAndopt.InitClass))] // Execution instruction
[assembly: CommandClass(typeof(InitAndopt.OptimizeClass))] // Only execute OptimizeClass Commands defined in
[assembly: CommandClass(typeof( mark .MyCommands))] // Execution instruction
[assembly: CommandClass(typeof( New layer .MyCommands))] // Execution instruction
[assembly: CommandClass(typeof( Selection set .MyCommands))] // Execution instruction
[assembly: CommandClass(typeof( Copy circle .MyCommands))] // Execution instruction
[assembly: CommandClass(typeof( event .MyCommands))] // Execution instruction
[assembly: CommandClass(typeof( block .MyCommands))] // Execution instruction
namespace block
{
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>();
// Create graphics , Set the left line of the door frame
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);
// transfer ⽤ Extracted common code block
AddBlockThroughDB(db, blockName, list);
System.Diagnostics.Debug.WriteLine(" Build a block door");
}
/**
* With transactional ⽅ type , Create block objects
*
*/
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);
// It's called “door” Whether the block of exists
if (!bt["door"].IsNull)
{
BlockReference br = new BlockReference(Point3d.Origin, bt["door"]);
br.ScaleFactors = new Scale3d(2.0);// Set the ruler ⼨ For the original 2 times
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("⼚ home ", " Xilinmen ");
vals.Add(" Price ", "2000");
int i = 0;
foreach (ObjectId id in record)
{
AttributeDefinition definition = id.GetObject(OpenMode.ForRead) as AttributeDefinition;
if (definition != null)
{
// Create a new attribute object
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);
// Determine whether the specified attribute name is included
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(" Insert a door Size is The block 2 times ");
}
[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);
// Attribute addition
AttributeDefinition cjAd = new AttributeDefinition(Point3d.Origin, " Xilinmen ", "⼚ home ", " Please lose ⼊⼚ home ", ObjectId.Null);
AttributeDefinition jgAd = new AttributeDefinition(Point3d.Origin + new Vector3d(0, 0.25, 0), "2000", " Price ", " Please lose ⼊ Price ", 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(" Create an attribute block DOOR");
}
}
}
namespace event
{
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)
{
// Non Mobile , You just quit
// Disconnect events
RemoveEvents();
AddEvents();
// Connection event
}
}
}
namespace Copy circle
{
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 Please select the center of the copy circle :";
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 Selection set
{
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()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
// Start transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Request to select objects in the drawing area
PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection();
// If the prompt status OK, Indicates that an object has been selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;
// Traverse the objects in the selection set
foreach (SelectedObject acSSObj in acSSet)
{
// Make sure the returned is legal SelectedObject object
if (acSSObj != null)
{
// Open the selected object in write mode
Entity acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as Entity;
if (acEnt != null)
{
// Change the object color to yellow
acEnt.ColorIndex = 2; // yellow
}
}
}
}
// Commit transaction
acTrans.Commit();
}
}
}
}
namespace New layer
{
public class MyCommands
{
[CommandMethod("AddMyLayer")]
public void AddMyLayer()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
// Start transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the layer table by reading
LayerTable acLayTbl;
acLayTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
string sLayName = "MyLayer";
if (acLayTbl.Has(sLayName) == false)
{
LayerTableRecord acLayRec = new LayerTableRecord
{
// Give the layer a color and name
Color = Color.FromColorIndex(ColorMethod.ByAci, 2),
Name = sLayName
};
// Open the layer table by writing
acLayTbl.UpgradeOpen();
acLayTbl.Add(acLayRec);
acTrans.AddNewlyCreatedDBObject(acLayRec, true);
}
if (acLayTbl.Has(sLayName) == true)
{
acCurDb.Clayer = acLayTbl[sLayName];
acTrans.Commit();
}
}
}
}
}
namespace mark
{
public class MyCommands
{
[CommandMethod("DDemo")]
public void DimDemo()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\n perform DDemo.\n");
System.Diagnostics.Debug.WriteLine("\n perform 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 = " In the test ";
wd.Location = new System.Drawing.Point(0,0);
// wd.Icon
var mb = Application.MenuBar as AcadMenuBar;
var pm = mb.Item(1); // edit
// pm.AddMenuItem( pm.Count," Add lines 1", "FirstLine ");
var ctxMenu = new ContextMenuExtension();
ctxMenu.Title = " Custom menu ";
var newMenuItem = new MenuItem(" Create a new document ");
newMenuItem.Click += (o, e) => { Application.ShowAlertDialog(" There is a response ~!"); };
ctxMenu.MenuItems.Add(newMenuItem);
Application.AddDefaultContextMenuExtension(ctxMenu);
var ctxMenu1 = new ContextMenuExtension();
ctxMenu1.Title = " Custom menu ";
var newMenuItem1 = new MenuItem(" Create a new document ");
newMenuItem1.Click += (o, e) => { Application.ShowAlertDialog(" There is a response ~!"); };
ctxMenu1.MenuItems.Add(newMenuItem1);
Application.AddObjectContextMenuExtension(RXObject.GetClass(typeof(Line)),ctxMenu1);
// After it was set up When you exit the program Unload
}
public void Initialize()
{
System.Diagnostics.Debug.WriteLine(" Program initialization started .");
System.Diagnostics.Debug.WriteLine(Application.Version.ToString());
// throw new NotImplementedException(); // Exceptions without code
// Registration button
//Cmd1();
Application.BeginQuit += (o, e) => {
// Application.ShowAlertDialog("BeginQuit");
};
Application.BeginDoubleClick += (o, e) => {
Application.ShowAlertDialog("BeginDoubleClick");
};
}
public void Terminate()
{
System.Diagnostics.Debug.WriteLine(" Program end , You can do some program cleaning inside , If closed CAD file ");
// 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(" Output one line Hello AutoCAD!");
}
// 1
// Add a length of 1000 The straight line of
[CommandMethod("FirstLine")]
public void FirstLine()
{
// Get the currently active drawing database
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())
{
// Open block table in read mode
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
// Open the model space block table record in writing
BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
// Add drawing object information to the block table record , And back to ObjectId object
btr.AppendEntity(line);
// Add objects to transactions
trans.AddNewlyCreatedDBObject(line, true);
trans.Commit();// Commit transaction
}
System.Diagnostics.Debug.WriteLine("FirstLine Has been performed ");
}
// 2
// Rubber band marking
[CommandMethod("DrawLine")]
public void DrawLine()
{
// Get the current database , Start the transaction manager
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acDb = acDoc.Database;
PromptPointResult ppr;
PromptPointOptions ppo = new PromptPointOptions("");
// Prompt the starting point
ppo.Message = "\n Enter the starting point of the line :";
ppr = acDoc.Editor.GetPoint(ppo);
Point3d ptStar = ppr.Value;
// If the ESC Key or cancel command , Quit
if (ppr.Status == PromptStatus.Cancel) return;
// Prompt the end
ppo.Message = "\n Enter the end point of the line :";
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;
// Open model space in write mode
acBTR = acTrans.GetObject(acBT[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
// Create lines
Line acLine = new Line(ptStar, ptEnd);
// Add lines
acBTR.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);
// Commit changes , Closing transaction
acTrans.Commit();
}
System.Diagnostics.Debug.WriteLine("DrawLine Has been performed ");
}
// 3
// Draw a rectangle with polylines
[CommandMethod("DrawRec")]
public static void DrawRec()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acDb = acDoc.Database;
PromptPointResult ppr; // Prompt the results
PromptPointOptions ppo = new PromptPointOptions(""); // Tip options
ppo.Message = "\n Enter the first point of the rectangle \n";
ppr = acDoc.Editor.GetPoint(ppo);
Point3d pt1 = ppr.Value;
if (ppr.Status == PromptStatus.Cancel) return;
ppo.Message = "\n Enter the second point of the rectangle \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;
// Create rectangle
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();
}
}
}
}
边栏推荐
- 狂神redis笔记07
- 从 Google 离职,前Go 语言负责人跳槽小公司
- DaVinci resolve 18, a video editing and color matching software, was officially released
- What is cloud rendering? How fast is the rendering speed? Yiwen tells you
- Set implementation class
- Différences entre les liens durs et les liens souples de rhcsa, interprétation des répertoires de premier niveau, redirection, création de fichiers et de répertoires, suppression de fichiers et de rép
- Section 3 of Chapter 3: parameter classification
- Autojs learning - achieve drawer effect
- Kotlin prints error messages and uploads the error messages to the server
- EasyCVR平台级联时,出现报错提示端口不可达是什么原因?
猜你喜欢
#夏日挑战赛#【FFH】NFC碰一碰拉起任何应用,无需企业认证!
[300 opencv routines] 234 Principal component analysis (PCA) for feature extraction
leetcode:1838. 最高频元素的频数【排序 + 前缀和 + 二分 + 思维】
網絡爬蟲爬取b站勵志彈幕並生成詞雲(精心筆記總結)
Section 24 of Chapter 2: document operation: Writing
Autojs learning - achieve drawer effect
AutoJs学习-实现抽屉效果
从 Google 离职,前Go 语言负责人跳槽小公司
After leaving Google, the former head of go language changed to a small company
tsconfig.json在配置文件中找不到任何输入,怎么办?
随机推荐
"Everything is interconnected, enabling thousands of industries", the 2022 open atom global open source summit openatom openharmony sub forum is about to open
Deploy the jar package of Ruiji takeout project on the remote server and successfully run on the PC and mobile terminal
Realization of bank card number recognition with OpenCV
RHCSA 压缩也解压缩、tar归档命令、文件的上传与下载、sehll中的变量、命令别名、命令历史
Use epoll to manage or golang multiprocess in case of a large number of connections
Différences entre les liens durs et les liens souples de rhcsa, interprétation des répertoires de premier niveau, redirection, création de fichiers et de répertoires, suppression de fichiers et de rép
Caring for the world: Hyatt announces the latest progress of its environmental, social and governance commitments and initiatives
Don't be ridiculous. Don't you know what abilities to improve if you want to enter a big factory? (collect quickly)
Lavel document reading notes -how to deploy lavel 8 project on cPanel shared hosting
To solve the pain points of API development, which is better, API post or API box?
直播预告│智汇云舟“数字孪生智慧园区解决方案”专场
将瑞吉外卖项目jar包部署在远程服务器并成功运行在pc和移动端
贝加莱使用教程1-创建X20工程和点亮LED灯
EasyCVR平台级联时,出现报错提示端口不可达是什么原因?
EMQX v4.4.5 发布:新增排他订阅及 MQTT 5.0 发布属性支持
Share a go auxiliary command line
短视频直播源码,uniapp跳转页面携带id
当MCU死机了,先把硬件抓过来~
AutoJs学习-实现抽屉效果
#夏日挑战赛#【FFH】NFC碰一碰拉起任何应用,无需企业认证!