Professional Documents
Culture Documents
AutoCAD
vi C#
Bin son: congnvc@gmail.com
Bn quyn: http://enesy.vn, congnvc@gmail.com
Lp trnh AutoCAD vi C#
http://enesy.vn
Lp trnh AutoCAD vi C#
C# 5.0 in a nutshell
AutoCAD .NET Developers Guide
VB .NET for AutoCAD 2010
Mt s website cng ng C#, AutoCAD .NET: codeproject.com, codeplex.com,
githup.com, through-the-interface.com
http://enesy.vn
Lp trnh AutoCAD vi C#
Chng m u
http://enesy.vn
Lp trnh AutoCAD vi C#
Sn phm
Ngn ng lp trnh
Giao din lp trnh ng dng1
AutoCAD
C#
.NET API2
Ebook ny s t hiu qu cao nht khi s dng km vi cc video trn knh Youtube ca
EnesyCAD
Ti sao li l C#?
La chn ngn ng lp trnh m rng AutoCAD lun l vn kh kh khn i vi ngi mi
bt u. Vic so snh ngn ng lp trnh no l mnh v ph hp phn ln do ch quan ca mi
ngi, kh m tha lng tt c mi ngi c. Vi ti, ch c 2 nhm ngn ng lp trnh lm ti
quan tm:
1. Nhm cc ngn ng lp trnh khng h tr to CUSTOM OBJECT trong AutoCAD
2. Nhm cn li
Nhm th nht bao gm cc ngn ng: AutoLISP, VBA, VB.NET, C#, Trong khi nhm th 2 ch c
C++.
Nu bn c th lp trnh to ra mt i tng chng hn nh Ci bn, bao gm cc c tnh
nh: S chn, mu sc, loi g, bng ch mt lnh tng t nh khi bn thc hin lnh Line
to ra on thng th Ci bn c gi l CUSTOM OBJECT. Ch khi lp trnh bng C++ vi Object
ARX API bn mi c th to ra c i tng Ci bn nh trn. Bn hy th tr li vi cu hi sau:
1
Giao din lp trnh ng dng cung cp cho ngi lp trnh cc hm tng tc vi C S D Liu, lp trnh
thc hin cc thao tc vi h iu hnh hay phn mm . Hu ht cc hm API c cha trong cc file
DLL
2
Ni mt cch n gin th NET l mt giao din ng gia (ging nh mt thng dich vin) cho 2
components vit bng 2 ngn ng khc nhau c th hiu nhau.
http://enesy.vn
Lp trnh AutoCAD vi C#
Tng t AutoLISP, to giao din ngi dng trong VBA cng khng phi d dng. Tuy nhin so
vi AutoLISP th VBA vn trn 1 bc.
Khng th ph nhn AutoLISP v VBA c mt u im rt r rng l t b hn ch v vic tng
thch phin bn, chng hn nu bn lp trnh 1 on m bng AutoLISP v VBA th rt c th n s
chy c trn hu ht phin bn AutoCAD. Cng cn ni thm l AutoDesk bt u tch ri
VBA khi cc sn phm ca mnh k t nm 2010, c th trong tng lai s khng h tr VBA na.
VB .NET: hi kh so snh gia VB .NET v C# v hu nh ci g C# c th VB.NET cng c, tuy
nhin ti vn loi VB.Net v cc l do sau:
1. Cu trc ca VB .NET rt rm r
2. Cng ng VB .NET khng ln lm (so vi cng ng C#)
C th so snh cu trc ca VB .NET v C# qua v d sau:
V d 1: Khai bo v khi to mt th hin ca lp Circle trong AutoCAD
VB.NET
Dim acCirc As Circle = New Circle()
C#
Circle acCirc = new Circle();
V d 2: Vng lp
VB.NET
If acSSPrompt.Status = PromptStatus.OK Then
acSSet = acSSPrompt.Value
Application.ShowAlertDialog("S lng i tng chn: " & _
acSSet.Count.ToString())
Else
Application.ShowAlertDialog("S lng i tng chn: 0")
End If
C#
if (acSSPrompt.Status == PromptStatus.OK)
{
acSSet = acSSPrompt.Value;
Application.ShowAlertDialog("S lng i tng chn: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("S lng i tng chn: 0");
}
http://enesy.vn
Lp trnh AutoCAD vi C#
http://enesy.vn
Lp trnh AutoCAD vi C#
AutoDesk
AutoCAD
ApplicationServices
Application
Colors
ComponentModel
DatabaseServices
Filters
EditorInput
Geometry
GraphicInterface
GraphicSystem
Internal
Calculator
DatabaseServices
Forms
PreviousInput
PropertyInspector
Reactors
Windows
LayerManager
Plotting Services
Publishing
Runtime
Windows
Data
ToolPalette
http://enesy.vn
Lp trnh AutoCAD vi C#
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;
namespace Enesy.CAD
{
public partial class Commands
{
[CommandMethod("DrawALine")]
public void DrawALine()
{
Point3d startPoint = new Point3d(0, 0, 0);
Point3d endPoint = new Point3d(4, 5, 6);
Line line = new Line(startPoint, endPoint);
}
}
}
thay cho
[CommandMethod("DrawALine")]
V b qua cu lnh:
using Autodesk.AutoCAD.Runtime;
Cu lnh ny l cu lnh nhp khng gian tn, ngha ca cu lnh ny l bn s khng phi nhp
y ng dn n khng gian tn ca mt lp CommandMethod, v chng ta nhp khng
gian tn ny u m ngun bng cu lnh:
using Autodesk.AutoCAD.Runtime;
on code trn cho thy trong khng gian tn Outer.Middle.Inner c 02 lp l: Class1 v Class2.
on m ny cng c th c vit theo cch khc:
namespace Outer
{
namespace Middle
http://enesy.vn
Lp trnh AutoCAD vi C#
{
namespace Inner
{
class Class1 { }
class Class2 { }
}
}
}
Cch vit u tin s dng du chm (.) trong khi cch vit th 2 s dng php lng khng gian
tn (nested). Trong thc t cch vit th nht c s dng ph bin hn.
Vic s dng khng gian tn khng nhng gip vic tm kim d dng m cn trnh c cc xung
t, chng hn nh bn c th to ra 2 lp c tn l Class1, c t chc trong cc namespace
khc nhau nh sau:
namespace Namespace1
{
class Class1 { }
}
namespace Namespace2
{
class Class1 { }
}
http://enesy.vn
Lp trnh AutoCAD vi C#
Bn v AutoCAD .dwg
Document
Cc c tnh (Properties) v phng thc (methods)
Database
Tables
Design spaces
Records
ModelSpace
Layout1 (PaperSpace)
Layout2 (PaperSpace)
SlidingDoor (Block Definition)
Horizontal Dimensions
Vertical Dimensions
Aligned Dimensions
Layers
Linetypes
TextStyles
DimStyles
Cc khi nim tip theo y kh kh nn bn cn phi dnh thi gian suy ngh tm ra logic quan
h ca chng, nh vy bn s nm bt c vn v kh qun.
BlockTable bao gm cc BlockTableRecords. ModelSpace l mt BlockTableRecord, tng t
PaperSpace cng l mt BlockTableRecord. Nu chng ta mun v mt i tng vo
ModelSpace ca bn v AutoCAD, chng ta s thm n vo BlockTableRecord c tn l
ModelSpace
http://enesy.vn
10
Lp trnh AutoCAD vi C#
Bn v AutoCAD .dwg
Document
Cc c tnh (Properties) v phng thc (methods)
Database
Tables
Records
BlockTable
BlockTableRecord, BlockTableRecord
LayerTable
LayerTableRecord, LayerTableRecord
LineTypeTable
LineTypeTableRecord,
LineTypeTableRecord,
TextStyleTable
TextStyleTableRecord,
TextStyleTable Record,
DimStyleTable
DimStyleTableRecord,
DimStyleTable Record,
http://enesy.vn
11
Lp trnh AutoCAD vi C#
Hy tng tng rng bn mun v mt on thng trong ModelSpace. Chng ta bit rng
ModelSpace l mt BlockTableRecord trong BlockTable. V th, chng ta s m BlockTable for
Read ( c) u tin, sau l m BlockTableRecord l ModelSpace for Write ( ghi). on
ny nghe c v hi di dng nhng thc ra l mc ch ca chng ta m ra lm g th s gn
thm mode cho n tng ng l for Read hoc for Write thi.
Vn t ra l ti sao AutoDesk li phn chia ra for Read v for Write lm g? Bn hon ton
c th m mt Database Object hoc Entity di dng for Write bt c lc no, bi v nu n c
m di dng for Write th ng nhin n s for Read c.
Bn thm v OpenMode
AutoCAD .NET API c ba kiu m mt Database Object hoc Entity l: OpenMode.ForRead,
OpenMode.ForWrite v OpenMode.ForNotify.
R rng l bn s phi m mt i tng di dng ForWrite khi cn thit phi thay i hoc thm
mt th g vo, iu ny l khng phi bn ci na. Nu m di dng ForWrite cho mt i
tng Database hoc Entity ch c th s lm tng thi gian thc thi ca code. on m sau
y s lm sng t vn ny (bn khng cn phi quan tm ngha ca tng cu lnh, hy c 1
ln v nm s qua cu trc ca n, sau ny khi nm bt c cc kin thc c bn, hy c li
n v bn s hiu hn ln c th nht, c nh vy. Cn hin gi th ti ch mun so snh thi
gian thc thi ca 2 kiu m i tng l ForeRead v ForWrite thi).
/// <summary>
/// Phng thc ly i tng Circle cui cng c v vo bn v
/// </summary>
/// <returns>ObjectId</returns>
public static ObjectId GetLastCircle1()
{
ObjectId cirId = ObjectId.Null;
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead)
as BlockTable;
BlockTableRecord btr =
tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as
BlockTableRecord;
foreach (ObjectId id in btr)
{
DBObject obj = tr.GetObject(id, OpenMode.ForRead);
if (obj is Circle)
cirId = obj.ObjectId;
}
tr.Commit();
}
return cirId;
}
/// <summary>
/// Phng thc ly i tng Circle cui cng c v vo bn v
/// </summary>
/// <returns>ObjectId</returns>
public static ObjectId GetLastCircle2()
{
http://enesy.vn
12
Lp trnh AutoCAD vi C#
ObjectId cirId = ObjectId.Null;
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(db.BlockTableId,
OpenMode.ForWrite) as BlockTable;
BlockTableRecord btr =
tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as
BlockTableRecord;
foreach (ObjectId id in btr)
{
DBObject obj = tr.GetObject(id, OpenMode.ForWrite);
if (obj is Circle)
cirId = obj.ObjectId;
}
tr.Commit();
}
return cirId;
}
/// <summary>
/// Kim tra thi gian M i tng ForRead
/// </summary>
[CommandMethod("OpenReadForRead")]
public static void OpenReadForRead_Method()
{
Editor ed =
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocum
ent.Editor;
DateTime begin = DateTime.Now;
GetLastCircle1();
TimeSpan elapsed = DateTime.Now.Subtract(begin);
ed.WriteMessage("Tng thi gian OpenReadForRead: {0}\n",
elapsed.TotalMilliseconds);
}
/// <summary>
/// Kim tra thi gian M i tng ForWrite
/// </summary>
[CommandMethod("OpenWriteForRead")]
public static void OpenWriteForRead_Method()
{
Editor ed =
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocum
ent.Editor;
DateTime begin = DateTime.Now;
GetLastCircle2();
TimeSpan elapsed = DateTime.Now.Subtract(begin);
ed.WriteMessage("Tng thi gian OpenWriteForRead: {0}\n",
elapsed.TotalMilliseconds);
}
http://enesy.vn
13
Lp trnh AutoCAD vi C#
Nh vy, thi gian m ForWrite gp 2.4 ln thi gian m ForRead. Vi mt tc v ln trong lp
trnh con s ny s nh hng rt nhiu n thi gian x l.
Quy tc rt ra l: Hy lun m di dng ForRead tr khi bn mun chnh sa, thay i n.
Quay tr li, hy tng tng rng bn mun v mt i tng Line vo ModelSpace. Chng ta
u bit rng ModelSpace l mt BlockTableRecord trong BlockTable. V th, hy m BlockTable
for Read trc (tt nhin, v chng ta cha c chnh sa g n c), tip theo chng ta s m mt
BlockTableRecord l ModelSpace di dng for Write. Ti sao? V chng ta s thm i tng Line
ny vo ModelSpace, iu ny c ngha l chng ta thay i n, do phi m n ra di dng
for Write th mi thay i n c.
Trong AutoCAD .NET API, chng ta ly ra mt th bng cch M (Open) n ra c (Read) hoc
Ghi (Write) trong mt Transaction (giao dch).
Khi nim tip theo l Transaction, y l mt khi nim rt quan trng trong lp trnh AutoCAD
.NET, ngha ca n l Giao dch v nhim v ca n ng vi ngha en l Giao dch.
Li quay tr li vi v d trc, hy tng tng rng chng ta mun v mt i tng Line vo
trong ModelSpace. Chng ta u bit rng ModelSpace l mt BlockTableRecord trong
BlockTable (ti nhc li cu ny kh nhiu ln, hi vng l bn ghi nh n trong u). Bt c
lc no khi chng ta mun c hoc ghi c s d liu ca bn v dwg, chng ta u thc hin di
dng mt giao dch (Transaction), tng t nh giao dch rt tin hoc np tin vo ti khon vy.
Trc khi c hoc ghi chng ta u phi bt u mt Transaction, y l nguyn tc bt di bt
dch trong lp trnh AutoCAD .NET. Sau khi kt thc mi th chng ta phi ng Transaction, nu
chng ta mun cc thay i ny c hiu lc trong C s d liu ca bn v. V vy trnh t thc
hin s c sa li nh sau:
u tin chng ta s bt u mt Transaction, m BlockTable for Read trc tin, tip n chng
ta s m BlockTableRecord l ModelSpace for Write, tip n chng ta s thm i tng Line
vo ModelSpace, thng bo vi Transaction rng chng ta thm i tng Line ny, ng
Transaction. Bn phi nh k nguyn tc ny, ch cn th thi, sau ny khi vit code c chiu theo
nguyn tc ny m trin khai l c.
Trong AutoCAD .NET API, chng ta ly ra mt th bng cch M (Open) n ra c (Read) hoc
Ghi (Write) trong mt Transaction thng qua ObjectID ca i tng m chng ta mun m.
ObjectID l khi nim cui cng m chng ta cn phi nm trc khi i vo cc v d thc t.
Tt c mi i tng Database u c ObjectID, ging nh l s Chng minh th vy. BlockTable
c mt ObjectID, ModelSpace c mt ObjectID, Lines, Circles, Arcs c v vo ModelSpace u
c ObjectID.
Tp hp c s d liu cu thnh nn bn v AutoCAD l Tp hp cc ObjectIDs.
ObjectID ca cc i tng c truy cp thng qua thuc tnh ID ca i tng .
Chng ta truy cp vo cc Bng (Tables ch ng nhm ln vi i tng Table trong bn v
AutoCAD) trong C s d liu bn v AutoCAD bng cch dng ID tng ng ca Database . V
d, nu chng ta mun m BlockTable ca mt Database, chng ta s ly BlockTable bng cch
http://enesy.vn
14
Lp trnh AutoCAD vi C#
m n thng qua thuc tnh BlockTableID ca Database. l LayerTableID, TextStyleTableID v
LineStyleTableID.
No, by gi l lc chng ta tng hp li nhng g ni trn, thng qua mt v d hon chnh
(ch bn ng quan tm n ngha ca tng cu lnh vi, hy ch xem qua thi):
[CommandMethod("DrawALine")]
public void DrawALine()
{
Point3d startPoint = new Point3d(0, 0, 0);
Point3d endPoint = new Point3d(4, 5, 6);
Line line = new Line(startPoint, endPoint);
Database acDb = Application.DocumentManager.MdiActiveDocument.Database;
using (Transaction tr = acDb.TransactionManager.StartTransaction())
{
// M BlockTable for Read
BlockTable blk = acDb.BlockTableId.GetObject(OpenMode.ForRead) as
BlockTable;
// M BlockTableRecord for Write
BlockTableRecord blkrcrd =
blk[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite) as BlockTableRecord;
// Thm i tng Line vo ModelSpace BlockTableRecord
blkrcrd.AppendEntity(line);
// Thm i tng Line vo Transaction
tr.AddNewlyCreatedDBObject(line, true);
// ng Transaction
tr.Commit();
}
}
http://enesy.vn
15
Lp trnh AutoCAD vi C#
Ci t cc phn mm cn thit
lp trnh AutoCAD .NET, bn s phi ci t cc phn mm sau:
To Plugin u tin
Sau khi ci thnh cng cc phn mm cn thit trn, chng ta s tin hnh to ra plugin u
tin. Ch : u ti gi thit rng bn s dng Visual Studio 2012 v lp trnh ng dng cho
AutoCAD2007, vi cc phin bn khc, cc bn xem chi tit video trn knh Youtube r hn.
Bc 1
Khi ng Visual Studio 2012, chn New > Project, xut hin hp thoi New Project
Pha trn cng, la chn .NET Framework 2.0 cho phin bn AutoCAD 2007, vi cc phin bn cn
li chn theo danh sch sau:
khung bn tri, chn Templates l Visual C#, khung Templates gia chn Class Library, cc
thng tin di cng bn t ty . Bm OK tip tc.
Visual studio s to ra mt Project trng vi mt file m ngun C# mu l Class1.cs. Tip theo
chng ta s tham kho n cc th vin .NET ca AutoCAD
http://enesy.vn
16
Lp trnh AutoCAD vi C#
Bc 2
Nhp chut phi vo References > chn Add Reference
Hp thoi Reference Manager xut hin.
Bm chn Browse
Hp thoi Select Files to References xut hin, duyt n th mc ci AutoCAD v chn 2 file l:
Acmgd.dll
Acdbmgd.dll
Bm Add
Bc 3
Copy on m sau Paste vo Class1.cs
using
using
using
using
System;
Autodesk.AutoCAD.Runtime;
Autodesk.AutoCAD.ApplicationServices;
Autodesk.AutoCAD.EditorInput;
namespace FirstExample
http://enesy.vn
17
Lp trnh AutoCAD vi C#
{
public class Class1
{
[CommandMethod("hello")]
public void HelloWorld()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Editor acEd = acDoc.Editor;
acEd.WriteMessage("\nWellcome to EnesyCAD!");
}
}
}
http://enesy.vn
18
Lp trnh AutoCAD vi C#
http://enesy.vn
19