控制AutoCAD环境(.NET)

本章介绍开发与AutoCAD一起运行的进程内应用程序的基础知识。它解释了许多概念,以控制和有效地使用AutoCAD环境。

本节中的主题

  • 控制应用程序窗口(.NET)
  • 控制绘图窗口(.NET)
  • 创建、打开、保存和关闭图形(.NET)
  • 锁定和删除文档(.NET)
  • AutoCAD的首选项(.NET)
  • 设置和返回系统变量(.NET)
  • 精确绘图(.NET)
  • 提示用户输入(.NET)
  • 访问命令行(.NET)
  • 扩展AutoCAD用户界面(.NET)
  • 自定义对话框可用于获取用户输入并扩展AutoCAD用户界面的功能。

控制应用程序窗口(.NET)

控制应用程序窗口的能力使开发人员能够灵活地创建有效和智能的应用程序。有时,您的应用程序最小化AutoCAD窗口是合适的,可能是在您的代码在另一个应用程序(如Microsoft® Excel®)中执行工作时。此外,在执行提示用户输入等任务之前,通常需要验证AutoCAD窗口的状态。

使用Application对象上的方法和属性,可以更改Application窗口的位置、大小和可见性。您还可以使用 WindowState 属性来最小化、最大化和检查“应用程序”窗口的当前状态。

应用程序窗口的位置和大小

此示例使用 Location 和 Size 特性将AutoCAD应用程序窗口定位在屏幕的左上角,并将其大小调整为400像素宽x 400像素高。

注意:以下示例要求项目引用PresentationCore(PresentationCore.dll)库。使用”添加引用”对话框并从”. NET”选项卡中选择”PresentationCore”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Drawing;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;

[CommandMethod("PositionApplicationWindow")]
public static void PositionApplicationWindow()
{
//设置cad窗口的位置,左上角为原点
Point ptApp = new Point(0, 0);
Application.MainWindow.SetLocation(ptApp);

// 设置尺寸
Size szApp = new Size(400, 400);
Application.MainWindow.SetSize(szApp);
}

(注:上面代码与原CAD给出的略有不同,用原来的跑不起来)

最小化和最大化应用程序窗口

注意:以下示例要求项目引用PresentationCore(PresentationCore.dll)库。使用”添加引用”对话框并从”. NET”选项卡中选择”PresentationCore”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System.Drawing;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("MinMaxApplicationWindow")]
public static void MinMaxApplicationWindow()
{
//Minimize the Application window
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);

//Maximize the Application window
Application.MainWindow.WindowState = Window.State.Maximized;
System.Windows.Forms.MessageBox.Show("Maximized", "MinMax");
}

查找应用程序窗口的当前状态

示例查询“应用程序”窗口的状态,并在消息框中向用户显示该状态。

1
2
3
4
5
6
7
8
9
10
11
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("CurrentWindowState")]
public static void CurrentWindowState()
{
System.Windows.Forms.MessageBox.Show("The application window is " +
Application.MainWindow.WindowState.ToString(),
"Window State");
}

使应用程序窗口不可见和可见

下面的代码使用 Visible 属性使AutoCAD应用程序窗口不可见,然后再次可见。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("HideWindowState")]
public static void HideWindowState()
{
//Hide the Application window
Application.MainWindow.Visible = false;
System.Windows.Forms.MessageBox.Show("Invisible", "Show/Hide");

//Show the Application window
Application.MainWindow.Visible = true;
System.Windows.Forms.MessageBox.Show("Visible", "Show/Hide");
}

控制绘图窗口(.NET)

与“AutoCAD应用程序”窗口一样,您可以最小化、最大化、重新定位、调整大小和检查任何“Document”窗口的状态。也可以使用视图、视口和缩放方法更改图形在窗口中的显示方式。

AutoCAD .NET API提供了多种显示图形的方法。在跟踪更改的总体效果时,可以控制图形显示快速移动到图形的不同区域。您可以缩放以更改放大率,或平移以在图形区域中重新定位视图,保存命名视图,然后在需要打印或参考特定细节时将其恢复,或通过将屏幕拆分为多个平铺视口来同时显示多个视图。

本节中的主题

  • 文档窗口的位置和大小(.NET)
  • 缩放和平移当前视图(.NET)
  • 使用命名视图(.NET)
  • 使用平铺视口(.NET)
  • 更新文档窗口中的几何图形(.NET)

文档窗口的位置和大小(.NET)

使用 Document 对象修改任何文档窗口的位置和大小。可以使用 WindowState 属性最小化或最大化“文档”窗口,并且可以使用 WindowState 属性查找“文档”窗口的当前状态。

调整活动文档窗口的大小

此示例使用Location和 Size 属性将“文档”窗口的位置和大小设置为400像素宽x 400像素高。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("SizeDocumentWindow")]
public static void SizeDocumentWindow()
{
//Size the Document window
Document acDoc = Application.DocumentManager.MdiActiveDocument;

// Works around what looks to be a refresh problem with the Application window
acDoc.Window.WindowState = Window.State.Normal;

// Set the position of the Document window
System.Drawing.Point ptDoc = new System.Drawing.Point(0, 0);
acDoc.Window.SetLocation(ptDoc);

// Set the size of the Document window
System.Drawing.Size szDoc = new System.Drawing.Size(400, 400);
acDoc.Window.SetSize(szDoc);
}

最小化和最大化活动文档窗口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("MinMaxDocumentWindow")]
public static void MinMaxDocumentWindow()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;

//Minimize the Document window
acDoc.Window.WindowState = Window.State.Minimized;
System.Windows.Forms.MessageBox.Show("Minimized" , "MinMax");

//Maximize the Document window
acDoc.Window.WindowState = Window.State.Maximized;
System.Windows.Forms.MessageBox.Show("Maximized" , "MinMax");
}

查找活动文档窗口的当前状态

1
2
3
4
5
6
7
8
9
10
11
12
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("CurrentDocWindowState")]
public static void CurrentDocWindowState()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;

System.Windows.Forms.MessageBox.Show("The document window is " +
acDoc.Window.WindowState.ToString(), "Window State");
}

缩放和平移当前视图(.NET)

视图是图形窗口中图形的特定放大率、位置和方向。通过更改当前视图的高度、宽度和中心点,可以更改图形的视图。增加或减少视图的宽度或高度会影响图形的显示大小。平移视图是通过调整当前视图的中心来完成的。

本节中的主题

  • 操作当前视图(.NET)
  • 定义到窗口(.NET)
  • 缩放视图(.NET)
  • 中心对象(.NET)
  • 显示图形范围和限制(.NET)

操作当前视图(.NET)

通过使用 Editor 对象的 GetCurrentView 方法,可以访问模型或图纸空间中视口的当前视图。 GetCurrentView 方法返回 ViewTableRecord 对象。使用 ViewTableRecord 对象可以操纵活动视口中视图的放大率、位置和方向。更改 ViewTableRecord 对象后,使用 SetCurrentView 方法更新活动视口的当前视图。

您将用于操作当前视图的一些常见属性包括:

  • CenterPoint-DCS坐标中视图的中心点。
  • Height-DCS坐标中视图的高度。增加高度以缩小;减少高度以放大。
  • 目标-WCS坐标中视图的目标。
  • ViewDirection-在WCS坐标中从目标到视图相机的向量。
  • ViewTwist-以弧度表示的视图扭曲角度。
  • 宽度-DCS坐标中视图的宽度。增加宽度以缩小;减小宽度以放大。

VBA代码交叉引用

AutoCAD .NET API不提供直接操作图形当前视图的方法,如ActiveX Automation库中的方法。例如,如果要缩放到图形中对象的范围或图形的界限,则必须操作当前视图的 Width 、 Height 和 CenterPoint 特性。若要获取图形的限制范围,请使用Database对象的 Extmin 、 Extmax 、 Limmin 和 Limmax 特性。

用于操作当前视图的函数

此示例代码是后面的示例使用的通用过程。“缩放”过程接受四个参数来完成缩放到边界、平移或居中绘图视图以及按给定因子缩放绘图视图。缩放过程要求以WCS坐标提供所有坐标值。

Zoom过程的参数为:

  • 最小点-用于定义要显示区域左下角的三维点。
  • 最大点-用于定义要显示区域的右上角的三维点。
  • 中心点-用于定义视图中心的三维点。
  • 比例因子-用于指定增加或减少视图大小的比例的真实的数字。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

static void Zoom(Point3d pMin, Point3d pMax, Point3d pCenter, double dFactor)
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

int nCurVport = System.Convert.ToInt32(Application.GetSystemVariable("CVPORT"));

// Get the extents of the current space when no points
// or only a center point is provided
// Check to see if Model space is current
if (acCurDb.TileMode == true)
{
if (pMin.Equals(new Point3d()) == true &&
pMax.Equals(new Point3d()) == true)
{
pMin = acCurDb.Extmin;
pMax = acCurDb.Extmax;
}
}
else
{
// Check to see if Paper space is current
if (nCurVport == 1)
{
// Get the extents of Paper space
if (pMin.Equals(new Point3d()) == true &&
pMax.Equals(new Point3d()) == true)
{
pMin = acCurDb.Pextmin;
pMax = acCurDb.Pextmax;
}
}
else
{
// Get the extents of Model space
if (pMin.Equals(new Point3d()) == true &&
pMax.Equals(new Point3d()) == true)
{
pMin = acCurDb.Extmin;
pMax = acCurDb.Extmax;
}
}
}

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Get the current view
using (ViewTableRecord acView = acDoc.Editor.GetCurrentView())
{
Extents3d eExtents;

// Translate WCS coordinates to 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 a center point is specified, define the min and max
// point of the extents
// for Center and Scale modes
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);
}

// Create an extents object using a line
using (Line acLine = new Line(pMin, pMax))
{
eExtents = new Extents3d(acLine.Bounds.Value.MinPoint,
acLine.Bounds.Value.MaxPoint);
}

// Calculate the ratio between the width and height of the current view
double dViewRatio;
dViewRatio = (acView.Width / acView.Height);

// Tranform the extents of the view
matWCS2DCS = matWCS2DCS.Inverse();
eExtents.TransformBy(matWCS2DCS);

double dWidth;
double dHeight;
Point2d pNewCentPt;

// Check to see if a center point was provided (Center and Scale modes)
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 // Working in Window, Extents and Limits mode
{
// Calculate the new width and height of the current view
dWidth = eExtents.MaxPoint.X - eExtents.MinPoint.X;
dHeight = eExtents.MaxPoint.Y - eExtents.MinPoint.Y;

// Get the center of the view
pNewCentPt = new Point2d(((eExtents.MaxPoint.X + eExtents.MinPoint.X) * 0.5),
((eExtents.MaxPoint.Y + eExtents.MinPoint.Y) * 0.5));
}

// Check to see if the new width fits in current window
if (dWidth > (dHeight * dViewRatio)) dHeight = dWidth / dViewRatio;

// Resize and scale the view
if (dFactor != 0)
{
acView.Height = dHeight * dFactor;
acView.Width = dWidth * dFactor;
}

// Set the center of the view
acView.CenterPoint = pNewCentPt;

// Set the current view
acDoc.Editor.SetCurrentView(acView);
}

// Commit the changes
acTrans.Commit();
}
}

定义到窗口(.NET)

在AutoCAD中,可以使用ZOOM命令的“窗口”选项定义应显示在图形窗口中的图形区域。定义要显示的区域时,将调整当前视图的 Width 和 Height 属性,以匹配由指定的两个点定义的区域。基于指定的点,视图的 CenterPoint 属性也会移动。

缩放到由两点定义的区域

此示例代码演示如何使用“操作当前视图”主题中定义的Zoom过程缩放到定义的区域。Zoom过程传递坐标(1.3,7.8,0)和(13.7,-2.6,0)作为前两个参数,以定义要显示的区域。

不需要新的中心点,因此新的Point 3d对象被传递给该过程。最后一个参数用于缩放新视图。缩放视图可用于在显示区域和图形窗口边缘之间创建间隙。

1
2
3
4
5
6
7
8
9
[CommandMethod("ZoomWindow")]
static public void ZoomWindow()
{
// Zoom to a window boundary defined by 1.3,7.8 and 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);
}

缩放视图(.NET)

如果需要增大或减小图形窗口中图像的放大率,则可以更改当前视图的 Width 和 Height 属性。当重新创建视图时,请确保以相同的因子更改 Width 和 Height 属性。缩放当前视图时计算的比例因子通常基于以下情况之一:

  • 相对于图形界限
  • 相对于当前视图
  • 相对于图纸空间单位

使用指定比例放大活动图形

此示例代码演示如何使用“操作当前视图”主题中定义的Zoom过程将当前视图缩小50%。

当缩放过程总共传递四个值时,前两个是未使用的新3D点。传递的第三个值是用于缩放视图的中心点,传递的最后一个值是用于缩放视图的比例因子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[CommandMethod("ZoomScale")]
static public void ZoomScale()
{
// Get the current document
Document acDoc = Application.DocumentManager.MdiActiveDocument;

// Get the current view
using (ViewTableRecord acView = acDoc.Editor.GetCurrentView())
{
// Get the center of the current view
Point3d pCenter = new Point3d(acView.CenterPoint.X,
acView.CenterPoint.Y, 0);

// Set the scale factor to use
double dScale = 0.5;

// Scale the view using the center of the current view
Zoom(new Point3d(), new Point3d(), pCenter, 1 / dScale);
}
}

中心对象(.NET)

通过使用 CenterPoint 特性更改视图的中心点,可以在图形窗口中重新定位图像。当视图的中心点更改而视图的大小未更改时,视图将平行于屏幕平移。

将活动图形放大到指定中心

此示例代码演示了如何使用在“操作当前视图”主题下定义的Zoom过程更改当前视图的中心点。

当“缩放”过程总共传递四个值时,前两个值被定义为新的3D点,并被该过程忽略。第三个值是定义视图新中心点的点(5,5,0),最后一个值为1,以保持当前视图的大小。

1
2
3
4
5
6
[CommandMethod("ZoomCenter")]
static public void ZoomCenter()
{
// Center the view at 5,5,0
Zoom(new Point3d(), new Point3d(), new Point3d(5, 5, 0), 1);
}

显示图形范围和限制(.NET)

图形的范围或界限用于定义最外面的对象出现的边界或由当前空间的界限定义的区域。

计算当前空间的范围

可以使用以下属性从 Database 对象访问当前空间的范围:

  • Extmin和Extmax-返回模型空间的范围。
  • Pextmin和Pextmax-返回当前图纸空间布局的范围。

获得当前空间的范围后,可以计算当前视图的 Width 和 Height 属性的新值。使用以下公式计算视图的新宽度:

1
dWidth = MaxPoint.X - MinPoint.X

使用以下公式计算视图的新高度:

1
dHeight = MaxPoint.Y - MinPoint.Y

在计算出视图的宽度和高度之后,就可以计算出视图的中心点。可以使用以下公式获得视图的中心点:

1
2
dCenterX = (MaxPoint.X + MinPoint.X) * 0.5
dCenterY = (MaxPoint.Y + MinPoint.Y) * 0.5

计算当前空间的界限

要根据当前空间的限制更改图形的显示,请使用 Database 对象的 Limmin 和 Limmax 以及 Plimmin 和 Plimmax 特性。返回定义当前空间界限的点后,可以使用前面提到的公式计算新视图的宽度、高度和中心点。

放大到当前空间的范围和界限

此示例代码演示如何使用“操作当前视图”主题中定义的Zoom过程显示当前空间的限制范围。

当缩放过程总共传递四个值时,传递的前两个值应该是定义要显示区域的最小点和最大点的点。第三个值定义为新的三维点,程序将忽略它,而最后一个值用于调整图形图像的大小,使其不会完全填充整个图形窗口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[CommandMethod("ZoomExtents")]
static public void ZoomExtents()
{
// Zoom to the extents of the current space
Zoom(new Point3d(), new Point3d(), new Point3d(), 1.01075);
}

[CommandMethod("ZoomLimits")]
static public void ZoomLimits()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Zoom to the limits of Model space
Zoom(new Point3d(acCurDb.Limmin.X, acCurDb.Limmin.Y, 0),
new Point3d(acCurDb.Limmax.X, acCurDb.Limmax.Y, 0),
new Point3d(), 1);
}

使用命名视图(.NET)

您可以命名并保存要重用的视图。当您不再需要该视图时,可以将其删除。

命名视图存储在视图表中,该表是图形数据库中的命名符号表之一。使用 Add 方法创建命名视图,以向View表添加新视图。将新命名视图添加到“视图”(View)表格中时,将创建默认的模型空间视图。

在创建视图时为视图命名。视图的名称最多可包含255个字符,并包含字母、数字和特殊字符美元符号($)、连字符(-)和下划线(_)。

一个命名视图可以从View表中删除,只需使用您想要删除的 ViewTableRecord 对象的 Erase 方法。

添加命名视图并将其设置为当前视图

下面的示例将命名视图添加到图形中并将其置为当前视图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("CreateNamedView")]
public static void CreateNamedView()
{
// Get the current database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the View table for read
ViewTable acViewTbl;
acViewTbl = acTrans.GetObject(acCurDb.ViewTableId,
OpenMode.ForRead) as ViewTable;

// Check to see if the named view 'View1' exists
if (acViewTbl.Has("View1") == false)
{
// Open the View table for write
acTrans.GetObject(acCurDb.ViewTableId, OpenMode.ForWrite);

// Create a new View table record and name the view 'View1'
using (ViewTableRecord acViewTblRec = new ViewTableRecord())
{
acViewTblRec.Name = "View1";

// Add the new View table record to the View table and the transaction
acViewTbl.Add(acViewTblRec);
acTrans.AddNewlyCreatedDBObject(acViewTblRec, true);

// Set 'View1' current
acDoc.Editor.SetCurrentView(acViewTblRec);
}

// Commit the changes
acTrans.Commit();
}

// Dispose of the transaction
}
}

命名视图

下面的示例从图形中删除命名视图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("EraseNamedView")]
public static void EraseNamedView()
{
// Get the current database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the View table for read
ViewTable acViewTbl;
acViewTbl = acTrans.GetObject(acCurDb.ViewTableId,
OpenMode.ForRead) as ViewTable;

// Check to see if the named view 'View1' exists
if (acViewTbl.Has("View1") == true)
{
// Open the View table for write
acTrans.GetObject(acCurDb.ViewTableId, OpenMode.ForWrite);

// Get the named view
ViewTableRecord acViewTblRec;
acViewTblRec = acTrans.GetObject(acViewTbl["View1"],
OpenMode.ForWrite) as ViewTableRecord;

// Remove the named view from the View table
acViewTblRec.Erase();

// Commit the changes
acTrans.Commit();
}

// Dispose of the transaction
}
}

使用平铺视口(.NET)

AutoCAD通常使用填充整个图形区域的单个平铺视口开始新图形。可以拆分“模型”选项卡的绘图区域,以同时显示多个视口。例如,如果使完整视图和局部视图都保持可见,则可以看到局部修改对整个图形的影响。在每个平铺视口中,可以执行以下操作:

  • 缩放、设置捕捉、栅格和UCS图标模式,以及恢复各个视口中的命名视图
  • 执行命令时从一个视口绘制到另一个视口
  • 命名视口配置,以便可以重复使用

可以在各种配置中显示平铺视口。视口的显示方式取决于需要查看的视图的数量和大小。模型空间中的平铺视口存储在Viewport表中

平铺视口存储在“视口”表中。Viewports表中的每条记录都表示一个视口,与其他表记录不同,可能有多个同名的Viewport表记录。具有相同名称的每个记录用于控制显示哪些视口。

例如,名为“Active”的视口表记录表示当前显示在“模型”选项卡上的平铺视口。

本节中的主题

  • 识别和操纵活动视口(.NET)
  • 使平铺视口成为当前视口(.NET)

识别和操纵活动视口(.NET)

活动视口在“视口”(Viewports)表格中由名为“*Active”的记录表示,这不是唯一的名称,因为“模型”(Model)选项卡上当前显示的所有平铺视口都名为“**Active”。显示的每个平铺视口都指定了一个编号。活动视口的编号可以通过以下方式获得:

  • 检索CVPORT系统变量的值
  • 使用编辑器对象的 ActiveViewportId 属性获取活动视口的对象ID,然后打开Viewport对象以访问其Number属性

拥有活动视口后,可以控制其显示属性,启用视口的绘图辅助工具(如栅格和捕捉)以及视口本身的大小。平铺视口由两个角点定义:左下角和右上角。 LowerLeftCorner 和 UpperRightCorner 属性表示视口在显示器上的图形位置。

单个平铺视口配置的左下角为(0,0),右上角为(1,1)。无论“模型”选项卡上平铺视口的数量如何,绘图窗口的左下角始终由点(0,0)表示,右上角由(1,1)表示。当显示多个平铺视口时,左下角和右上角将有所不同,但一个视口的左下角为(0,0),另一个视口的右上角为(1,1)

这些属性定义如下(以四向拆分为例):

img

在本例中:

  • 视口1-LowerLeftCorner =(0,.5),UpperRightCorner =(.5,1)
  • 视口2-LowerLeftCorner =(.5,.5),UpperRightCorner =(1,1)
  • 视口3-LowerLeftCorner =(0,0),UpperRightCorner =(.5,.5)
  • 视口4-LowerLeftCorner =(.5,0),UpperRightCorner =(1,.5)

创建具有两个水平窗口的新平铺视口配置

以下示例创建两个水平视口作为命名视口配置,并重新定义活动显示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("CreateModelViewport")]
public static void CreateModelViewport()
{
// Get the current database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Viewport table for read
ViewportTable acVportTbl;
acVportTbl = acTrans.GetObject(acCurDb.ViewportTableId,
OpenMode.ForRead) as ViewportTable;

// Check to see if the named view 'TEST_VIEWPORT' exists
if (acVportTbl.Has("TEST_VIEWPORT") == false)
{
// Open the View table for write
acTrans.GetObject(acCurDb.ViewportTableId, OpenMode.ForWrite);

// Add the new viewport to the Viewport table and the transaction
using (ViewportTableRecord acVportTblRecLwr = new ViewportTableRecord())
{
acVportTbl.Add(acVportTblRecLwr);
acTrans.AddNewlyCreatedDBObject(acVportTblRecLwr, true);

// Name the new viewport 'TEST_VIEWPORT' and assign it to be
// the lower half of the drawing window
acVportTblRecLwr.Name = "TEST_VIEWPORT";
acVportTblRecLwr.LowerLeftCorner = new Point2d(0, 0);
acVportTblRecLwr.UpperRightCorner = new Point2d(1, 0.5);

// Add the new viewport to the Viewport table and the transaction
using (ViewportTableRecord acVportTblRecUpr = new ViewportTableRecord())
{
acVportTbl.Add(acVportTblRecUpr);
acTrans.AddNewlyCreatedDBObject(acVportTblRecUpr, true);

// Name the new viewport 'TEST_VIEWPORT' and assign it to be
// the upper half of the drawing window
acVportTblRecUpr.Name = "TEST_VIEWPORT";
acVportTblRecUpr.LowerLeftCorner = new Point2d(0, 0.5);
acVportTblRecUpr.UpperRightCorner = new Point2d(1, 1);

// To assign the new viewports as the active viewports, the
// viewports named '*Active' need to be removed and recreated
// based on 'TEST_VIEWPORT'.

// Step through each object in the symbol table
foreach (ObjectId acObjId in acVportTbl)
{
// Open the object for read
ViewportTableRecord acVportTblRec;
acVportTblRec = acTrans.GetObject(acObjId,
OpenMode.ForRead) as ViewportTableRecord;

// See if it is one of the active viewports, and if so erase it
if (acVportTblRec.Name == "*Active")
{
acTrans.GetObject(acObjId, OpenMode.ForWrite);
acVportTblRec.Erase();
}
}

// Clone the new viewports as the active viewports
foreach (ObjectId acObjId in acVportTbl)
{
// Open the object for read
ViewportTableRecord acVportTblRec;
acVportTblRec = acTrans.GetObject(acObjId,
OpenMode.ForRead) as ViewportTableRecord;

// See if it is one of the active viewports, and if so erase it
if (acVportTblRec.Name == "TEST_VIEWPORT")
{
ViewportTableRecord acVportTblRecClone;
acVportTblRecClone = acVportTblRec.Clone() as ViewportTableRecord;

// Add the new viewport to the Viewport table and the transaction
acVportTbl.Add(acVportTblRecClone);
acVportTblRecClone.Name = "*Active";
acTrans.AddNewlyCreatedDBObject(acVportTblRecClone, true);
}
}

// Update the display with the new tiled viewports arrangement
acDoc.Editor.UpdateTiledViewportsFromDatabase();
}
}

// Commit the changes
acTrans.Commit();
}

// Dispose of the transaction
}
}

使平铺视口成为当前视口(.NET)

在当前视口中输入点并选择对象。若要将视口置为当前视口,请使用CVPORT系统变量,并按要置为当前视口的编号指定视口。

可以在现有视口中搜索以查找特定视口。为此,请使用 Name 属性标识名称为“*Active”的视口表记录。

拆分视口,然后在窗口中缩放

此示例将活动视口拆分为两个水平窗口。然后循环访问图形中的所有平铺视口,并显示每个视口的视口名称以及左下角和右上角。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("SplitAndIterateModelViewports")]
public static void SplitAndIterateModelViewports()
{
// Get the current database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Viewport table for write
ViewportTable acVportTbl;
acVportTbl = acTrans.GetObject(acCurDb.ViewportTableId,
OpenMode.ForWrite) as ViewportTable;

// Open the active viewport for write
ViewportTableRecord acVportTblRec;
acVportTblRec = acTrans.GetObject(acDoc.Editor.ActiveViewportId,
OpenMode.ForWrite) as ViewportTableRecord;

using (ViewportTableRecord acVportTblRecNew = new ViewportTableRecord())
{
// Add the new viewport to the Viewport table and the transaction
acVportTbl.Add(acVportTblRecNew);
acTrans.AddNewlyCreatedDBObject(acVportTblRecNew, true);

// Assign the name '*Active' to the new Viewport
acVportTblRecNew.Name = "*Active";

// Use the existing lower left corner for the new viewport
acVportTblRecNew.LowerLeftCorner = acVportTblRec.LowerLeftCorner;

// Get half the X of the existing upper corner
acVportTblRecNew.UpperRightCorner = new Point2d(acVportTblRec.UpperRightCorner.X,
acVportTblRec.LowerLeftCorner.Y +
((acVportTblRec.UpperRightCorner.Y -
acVportTblRec.LowerLeftCorner.Y) / 2));

// Recalculate the corner of the active viewport
acVportTblRec.LowerLeftCorner = new Point2d(acVportTblRec.LowerLeftCorner.X,
acVportTblRecNew.UpperRightCorner.Y);

// Update the display with the new tiled viewports arrangement
acDoc.Editor.UpdateTiledViewportsFromDatabase();

// Step through each object in the symbol table
foreach (ObjectId acObjId in acVportTbl)
{
// Open the object for read
ViewportTableRecord acVportTblRecCur;
acVportTblRecCur = acTrans.GetObject(acObjId,
OpenMode.ForRead) as ViewportTableRecord;

if (acVportTblRecCur.Name == "*Active")
{
Application.SetSystemVariable("CVPORT", acVportTblRecCur.Number);

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);
}
}
}

// Commit the changes and dispose of the transaction
acTrans.Commit();
}
}

更新文档窗口中的几何图形(.NET)

通过AutoCAD .NET API执行的许多操作都会修改绘图区域中显示的内容。并非所有这些操作都会立即更新图形的显示。这是为了让您可以对图形进行多次更改,而无需等待在每次操作后更新显示。相反,您可以将您的操作捆绑在一起,并在完成后进行一次调用来更新显示。

更新显示的方法是 UpdateScreen ( Application 和 Editor 对象)和 Regen ( Editor 对象)。

UpdateScreen 方法重绘应用程序或文档窗口。 Regen 方法在绘图窗口中重新生成图形对象,并重新计算所有对象的屏幕坐标和视图分辨率。它还可以重新索引图形数据库,以获得最佳显示和对象选择性能。

1
2
3
4
5
6
// Redraw the drawing
Application.UpdateScreen();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();

// Regenerate the drawing
Application.DocumentManager.MdiActiveDocument.Editor.Regen();

创建、打开、保存和关闭图形(.NET)

DocumentCollection 、 DocumentCollectionExtension 、 Document 和 Database 对象提供对AutoCAD®文件方法的访问。

VBA/ActiveX 交叉引用

VBA/ActiveX 类 .NET API类
Documents collection DocumentCollection 和 DocumentCollectionExtension
Document Document 和 Database
Document.Saved System.Convert.ToInt16(Application.GetSystemVariable(“DBMOD”))

本节中的主题

  • 创建和打开图形(.NET)
  • 保存并关闭图形(.NET)
  • 未打开文档时工作(.NET)

创建和打开图形(.NET)

要创建新图形或打开现有图形,请使用 DocumentCollectionExtension 对象的方法。 Add 方法基于图形模板创建新的图形文件,并将该图形添加到 DocumentCollectionExtension 。 Open 方法打开现有的图形文件。

创建新图形

此示例使用 Add 方法基于acad.dwt图形样板文件创建新图形。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("NewDrawing", CommandFlags.Session)]
public static void NewDrawing()
{
// Specify the template to use, if the template is not found
// the default settings are used.
string strTemplatePath = "acad.dwt";

DocumentCollection acDocMgr = Application.DocumentManager;
Document acDoc = acDocMgr.Add(strTemplatePath);

acDocMgr.MdiActiveDocument = acDoc;
}

打开现有图形

此示例使用 Open 方法打开现有图形。在打开图形之前,代码会先检查文件是否存在,然后再尝试打开它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("OpenDrawing", CommandFlags.Session)]
public static void OpenDrawing()
{
string strFileName = "C:\\campus.dwg";
DocumentCollection acDocMgr = Application.DocumentManager;

if (File.Exists(strFileName))
{
acDocMgr.Open(strFileName, false);
}
else
{
acDocMgr.MdiActiveDocument.Editor.WriteMessage("File " + strFileName +
" does not exist.");
}
}

保存并关闭图形(.NET)

使用 Database 对象的 SaveAs 方法保存 Database 对象的内容。使用 SaveAs 方法时,通过为 bBakAndRename 参数提供 True ,可以指定是否应重命名数据库以及是否应将磁盘上图形的备份重命名为备份文件。通过检查DWGTITLED系统变量的值,可以确定数据库是否使用默认名称Drawing1、Drawing2等。如果DWGTITLED为0,则图形尚未重命名。

有时,您需要检查活动图形是否有任何未保存的更改。最好在退出AutoCAD任务或开始新图形之前执行此操作。若要检查图形文件是否已更改,需要检查DBMOD系统变量的值。

关闭图形

Document 对象的 CloseAndDiscard 或 CloseAndSave 方法用于关闭打开的图形并放弃或保存所做的任何更改。可以使用 DocumentCollectionExtension 的 CloseAll 方法关闭AutoCAD中所有打开的图形。

保存活动图形

如果当前未保存激活图形或使用其当前名称,则本示例将激活图形保存到“c:\MyDrawing.dwg“。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("SaveActiveDrawing")]
public static void SaveActiveDrawing()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;
string strDWGName = acDoc.Name;

object obj = Application.GetSystemVariable("DWGTITLED");

// Check to see if the drawing has been named
if (System.Convert.ToInt16(obj) == 0)
{
// If the drawing is using a default name (Drawing1, Drawing2, etc)
// then provide a new name
strDWGName = "c:\\MyDrawing.dwg";
}

// Save the active drawing
acDoc.Database.SaveAs(strDWGName, true, DwgVersion.Current,
acDoc.Database.SecurityParameters);
}

确定图形是否有未保存的更改

此示例检查是否有未保存的更改,并与用户确认是否可以保存图形(如果不可以,则跳到结尾)。如果确定,请使用 SaveAs 方法保存当前图形,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("DrawingSaved")]
public static void DrawingSaved()
{
object obj = Application.GetSystemVariable("DBMOD");

// Check the value of DBMOD, if 0 then the drawing has no unsaved changes
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 = Application.DocumentManager.MdiActiveDocument;
acDoc.Database.SaveAs(acDoc.Name, true, DwgVersion.Current,
acDoc.Database.SecurityParameters);
}
}
}

未打开文档时工作(.NET)

AutoCAD总是在打开新文档或现有文档的情况下启动。但是,在当前运行期间可以关闭所有文件。

如果关闭AutoCAD用户界面中的所有文档,您会注意到应用程序窗口发生了一些变化。快速访问工具栏和应用程序菜单提供有限的选项。这些有限的选项与创建和打开图形、显示图纸集管理器以及恢复图形有关。如果显示菜单栏,则还会显示简化的“文件”、“视图”、“窗口”和“帮助”菜单。你也会注意到没有命令行。

在零文档状态下工作时,您可以执行以下操作:

  • 您可以创建新文档或打开现有文档
  • 您可以自定义应用程序菜单和菜单栏的零文档状态
  • 您可以关闭AutoCAD

若要在AutoCAD进入零文档状态时对其作出反应,应使用 DocumentDestroyed 事件。 DocumentDestroyed 事件在打开的文档关闭时触发。最后一张单据关闭时的单据计数为1。使用 DocumentManager 的 Count 属性确定触发 DocumentDestroyed 事件时打开的文档数。

自定义应用程序菜单

此示例代码使用 DocumentDestroyed 事件监视最后一个图形何时关闭以及何时进入零文档状态。进入零文档状态后, Opening 事件将在应用程序菜单中注册。单击应用程序菜单时,会触发 Opening 事件。在 Opening 事件期间,一个新的菜单项被添加到应用程序菜单中。新菜单项显示一个消息框。

注意:您必须将AdWindows.dll引用到项目中,才能使用以下示例代码。AdWindows.dll包含用于自定义应用程序菜单的命名空间,可以在AutoCAD的安装文件夹或ObjectARX SDK的一部分中找到。还需要引用 WindowsBase ,该引用位于“添加引用”对话框的“AutoCAD .NET”选项卡上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using Autodesk.Windows;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;

// Create the command handler for the custom application menu item
public class MyCommandHandler : System.Windows.Input.ICommand
{
public bool CanExecute(object parameter)
{
return true;
}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)
{
Application.ShowAlertDialog("MyMenuItem has been clicked");
}
}

class Chapter4
{
//Global var for ZeroDocState
ApplicationMenuItem acApMenuItem = null;

[CommandMethod("AddZeroDocEvent")]
public void AddZeroDocEvent()
{
// Get the DocumentCollection and register the DocumentDestroyed event
DocumentCollection acDocMgr = Application.DocumentManager;
acDocMgr.DocumentDestroyed +=
new DocumentDestroyedEventHandler(docDestroyed);
}

public void docDestroyed(object obj,
DocumentDestroyedEventArgs acDocDesEvtArgs)
{
// Determine if the menu item already exists and the number of documents open
if (Application.DocumentManager.Count == 1 && acApMenuItem == null)
{
// Add the event handler to watch for when the application menu is opened
// AdWindows.dll must be referenced to the project
ComponentManager.ApplicationMenu.Opening +=
new EventHandler<EventArgs>(ApplicationMenu_Opening);
}
}

void ApplicationMenu_Opening(object sender, EventArgs e)
{
// Check to see if the custom menu item was added previously
if (acApMenuItem == null)
{
// Get the application menu component
ApplicationMenu acApMenu = ComponentManager.ApplicationMenu;

// Create a new application menu item
acApMenuItem = new ApplicationMenuItem();
acApMenuItem.Text = "MyMenuItem";
acApMenuItem.CommandHandler = new MyCommandHandler();

// Append the new menu item
acApMenu.MenuContent.Items.Add(acApMenuItem);

// Remove the application menu Opening event handler
ComponentManager.ApplicationMenu.Opening -=
new EventHandler<EventArgs>(ApplicationMenu_Opening);
}
}
}

锁定和删除文档(.NET)

修改对象或访问AutoCAD的请求可以在任何上下文中发生,也可以来自任何数量的应用程序。为了防止与其他请求发生冲突,您有责任在修改文档之前锁定文档。在某些上下文中未能锁定文档将导致修改数据库期间发生锁定冲突。您希望在应用程序出现以下情况时锁定文档:

  • 从无模式对话框与AutoCAD交互
  • 访问当前文档以外的加载文档
  • 用作COM服务器
  • 使用会话命令标志注册命令

例如,当将实体添加到当前文档以外的文档中的模型或图纸空间时,需要锁定该文档。您使用要锁定的 Database 对象的 LockDocument 方法。当调用 LockDocument 方法时,返回一个 DocumentLock 对象。

修改锁定的数据库后,需要解锁数据库。要解锁数据库,请调用 DocumentLock 对象的 Dispose 方法。您还可以将Using语句与 DocumentLock 对象一起使用,一旦Using语句结束,数据库将被解锁。

注意:在不使用会话命令标志的命令上下文中工作时,在修改当前文档之前,不需要锁定该文档的数据库。

在修改对象之前锁定数据库

此示例创建一个新文档,然后在其中绘制一个圆。创建文档后,将锁定新文档的数据库,然后向其中添加一个圆。添加圆后,将解锁数据库,并将关联的文档窗口设置为当前。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("LockDoc", CommandFlags.Session)]
public static void LockDoc()
{
// Create a new drawing
DocumentCollection acDocMgr = Application.DocumentManager;
Document acNewDoc = acDocMgr.Add("acad.dwt");
Database acDbNewDoc = acNewDoc.Database;

// Lock the new document
using (DocumentLock acLckDoc = acNewDoc.LockDocument())
{
// Start a transaction in the new database
using (Transaction acTrans = acDbNewDoc.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acDbNewDoc.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle with a radius of 3 at 5,5
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(5, 5, 0);
acCirc.Radius = 3;

// Add the new object to Model space and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);
}

// Save the new object to the database
acTrans.Commit();
}

// Unlock the document
}

// Set the new document current
acDocMgr.MdiActiveDocument = acNewDoc;
}

AutoCAD的首选项(.NET)

AutoCAD .NET API不包含任何类或方法来访问通过“AutoCAD选项”对话框访问的选项。通过ActiveX® Automation库可以访问这些选项。使用从Application对象的 Preferences 属性返回的COM对象。

拥有Preferences COM对象后,就可以访问与选项相关的九个对象,每个对象代表“选项”对话框中的一个选项卡。通过这些对象可以访问“选项”对话框中存储在注册表中的所有选项。通过使用这些对象上的特性,可以自定义许多AutoCAD设置。这些对象是

  • PreferencesDisplay
  • PreferencesDrafting
  • PreferencesFiles
  • PreferencesOpenSave
  • PreferencesOutput
  • PreferencesProfiles
  • PreferencesSelection
  • PreferencesSystem
  • PreferencesUser

访问首选项对象

下面的示例演示如何通过COM互操作访问Preferences对象。

1
AcadPreferences acPrefComObj = (AcadPreferences)Application.Preferences;

引用首选项对象后,可以使用“显示”、“绘图”、“文件”、“打开保存”、“输出”、“配置”、“选择”、“系统”和“用户”属性访问任何特定的首选项对象。

把十字准线设置为全屏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Interop;

[CommandMethod("PrefsSetCursor")]
public static void PrefsSetCursor()
{
// This example sets the crosshairs for the drawing window
// to full screen.

// Access the Preferences object
AcadPreferences acPrefComObj = (AcadPreferences)Application.Preferences;

// Use the CursorSize property to set the size of the crosshairs
acPrefComObj.Display.CursorSize = 100;
}

隐藏滚动条

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Interop;

[CommandMethod("PrefsSetDisplay")]
public static void PrefsSetDisplay()
{
// This example disables the scroll bars

// Access the Preferences object
AcadPreferences acPrefComObj = (AcadPreferences)Application.Preferences;

// Disable the scroll bars
acPrefComObj.Display.DisplayScrollBars = false;
}

本节中的主题

  • 数据库首选项(.NET)

数据库首选项(.NET)

沿着应用程序级首选项,还有一些基于图形的首选项,可通过存储在图形文件中的“选项”对话框访问。要访问这些存储的设置,请使用 Database 对象的相应属性或使用 Application 对象的 GetSystemVariable 和 SetSystemVariable 方法。

VBA/ActiveX 交叉引用

VBA/ActiveX 类 .NET API类
DatabasePreferences Database and drawing based system variables 基于数据库和图形的系统变量

设置和返回系统变量(.NET)

Application对象提供了用于设置和检索AutoCAD系统变量的 SetSystemVariable 和 GetSystemVariable 方法。例如,要将整数指定给MAXSORT系统变量,请使用以下代码:

1
2
3
4
5
// Get the current value from a system variable
int nMaxSort = System.Convert.ToInt32(Application.GetSystemVariable("MAXSORT"));

// Set system variable to new value
Application.SetSystemVariable("MAXSORT", 100);

精确绘图(.NET)

使用AutoCAD,您可以创建具有精确几何图形的图形,而无需执行繁琐的计算。通常,您可以在不知道坐标的情况下指定精确的点。无需离开图形屏幕,即可对图形执行计算并显示各种类型的状态信息。

本节中的主题

  • 调整捕捉和网格对齐(.NET)
  • 使用正交模式(.NET)
  • 计算点和值(.NET)
  • 计算面积(.NET)

调整捕捉和网格对齐(.NET)

网格是测量距离的视觉指导,而捕捉模式用于限制光标移动。除了设置栅格和捕捉模式的间距外,还可以调整旋转和使用的捕捉类型。

如果需要沿特定路线或角度沿着绘制,可以旋转捕捉角度。捕捉角度旋转的中心点是捕捉基点。

注意:更改活动视口的捕捉和栅格设置后,应使用Editor对象的 UpdateTiledViewportsFromDatabase 方法更新绘图区域的显示。

捕捉和栅格不会影响通过AutoCAD .NET API指定的点,但会影响用户在绘图区域中指定的点(如果请求用户使用 GetPoint 或 GetEntity 等方法输入输入)。

更改网格和捕捉设置

此示例将捕捉基点更改为(1,1),捕捉旋转角度更改为30度。打开网格并调整间距,以便更改可见。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("ChangeGridAndSnap")]
public static void ChangeGridAndSnap()
{
// Get the current database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the active viewport
ViewportTableRecord acVportTblRec;
acVportTblRec = acTrans.GetObject(acDoc.Editor.ActiveViewportId,
OpenMode.ForWrite) as ViewportTableRecord;

// Turn on the grid for the active viewport
acVportTblRec.GridEnabled = true;

// Adjust the spacing of the grid to 1, 1
acVportTblRec.GridIncrements = new Point2d(1, 1);

// Turn on the snap mode for the active viewport
acVportTblRec.SnapEnabled = true;

// Adjust the snap spacing to 0.5, 0.5
acVportTblRec.SnapIncrements = new Point2d(0.5, 0.5);

// Change the snap base point to 1, 1
acVportTblRec.SnapBase = new Point2d(1, 1);

// Change the snap rotation angle to 30 degrees (0.524 radians)
acVportTblRec.SnapAngle = 0.524;

// Update the display of the tiled viewport
acDoc.Editor.UpdateTiledViewportsFromDatabase();

// Commit the changes and dispose of the transaction
acTrans.Commit();
}
}

使用正交模式(.NET)

绘制直线或移动对象时,可以使用“正交”模式将光标限制在水平轴或垂直轴上。正交对齐取决于当前捕捉角度和UCS。正交模式适用于需要指定第二个点的活动,例如使用 GetDistance 或 GetAngle 方法时。使用“正交”不仅可以建立垂直或水平对齐,还可以强制平行或创建规则偏移。

通过允许AutoCAD施加正交约束,可以更快地绘制。例如,可以在开始绘制之前通过启用“正交”模式来创建一系列垂直线。由于直线被约束到水平轴和垂直轴,因此您可以更快地绘制,因为知道直线是垂直的。

img

以下语句打开“正交”模式。与网格和捕捉设置不同,“正交”模式在 Database 对象中而不是活动视口中维护。

1
Application.DocumentManager.MdiActiveDocument.Database.Orthomode = true;

计算点和值(.NET)

通过使用编辑器对象以及几何和几何图形命名空间提供的方法,可以快速解决数学问题或在图形中定位点。一些可用的方法是:

  • 使用 GetDistanceTo 和 DistanceTo 方法获取两个二维或三维点之间的距离
  • 使用带有返回值的 Angle 属性的 GetVectorTo 方法,使用两个2D点获取与X轴的角度
  • 使用 StringToAngle 方法将字符串形式的角度转换为真实的(双精度)值
  • 使用 AngleToString 方法将角度从真实的(双精度)值转换为字符串
  • 使用 StringToDistance 方法将距离从字符串转换为真实的(双精度)值
  • 使用 GetDistance 方法查找用户输入的两点之间的距离

注意:AutoCAD .NET API不包含基于距离和角度(极坐标点)计算点的方法以及在不同坐标系之间转换坐标的方法。如果您需要这些实用程序,则需要利用ActiveX Automation库中的 PolarPoint 和 TranslateCoordinates 方法。

从X轴获取角度
此示例计算两点之间的向量并确定与X轴的角度。

1
2
3
4
5
6
7
8
9
10
11
12
13
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AngleFromXAxis")]
public static void AngleFromXAxis()
{
Point2d pt1 = new Point2d(2, 5);
Point2d pt2 = new Point2d(5, 2);

Application.ShowAlertDialog("Angle from XAxis: " +
pt1.GetVectorTo(pt2).Angle.ToString());
}

计算极点
此示例基于基点、角度和距离计算点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

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);

Application.ShowAlertDialog("\nPolarPoint: " +
"\nX = " + pt1.X +
"\nY = " + pt1.Y);

Point3d pt2 = PolarPoints(new Point3d(5, 2, 0), 0.785398, 12);

Application.ShowAlertDialog("\nPolarPoint: " +
"\nX = " + pt2.X +
"\nY = " + pt2.Y +
"\nZ = " + pt2.Z);
}

使用GetDistance方法查找两点之间的距离

此示例使用 GetDistance 方法获取两个点并显示计算的距离。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetDistanceBetweenTwoPoints")]
public static void GetDistanceBetweenTwoPoints()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;

PromptDoubleResult pDblRes;
pDblRes = acDoc.Editor.GetDistance("\nPick two points: ");

Application.ShowAlertDialog("\nDistance between points: " +
pDblRes.Value.ToString());
}

计算面积(.NET)

您可以使用 Area 属性查找弧、圆、椭圆、轻量曲面、多边形、面域、图案填充、平面闭合样条或任何其他从基本类型Curve派生的图元的面积。

如果需要计算多个对象的组合面积,则可以在添加一系列面域时保留累计面积,或对一系列面域使用布尔方法以获得表示所需面积的单个面域。从这个区域中,您可以使用 Area 属性来获取其面积。计算的面积根据查询的对象类型而不同。

本节中的主题

  • 计算定义的区域(.NET)

计算定义的区域(.NET)

如果要计算的面积是基于用户指定的点,则可以考虑在内存中创建一个对象(如轻量级对象),然后在丢弃对象之前查询该对象的面积。以下步骤说明了如何实现此操作:

  1. 在一个循环中使用 GetPoint 方法从用户那里获得点数。
  2. 从用户提供的点创建一个轻量级的图形。创建新的多段线对象。指定顶点的数量以及它们应该位于的点。
  3. 使用 Area 属性获取新创建的曲面的面积。
  4. 使用其 Dispose 方法处置该多段线。

计算由用户输入的点定义的面积

此示例提示用户输入五个点。然后,将根据输入的点创建一个顶点。此时将关闭按钮,按钮的区域将显示在消息框中。由于未向块中添加缓存,因此需要在命令结束前将其释放。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("CalculateDefinedArea")]
public static void CalculateDefinedArea()
{
// Prompt the user for 5 points
Document acDoc = Application.DocumentManager.MdiActiveDocument;

PromptPointResult pPtRes;
Point2dCollection colPt = new Point2dCollection();
PromptPointOptions pPtOpts = new PromptPointOptions("");

// Prompt for the first point
pPtOpts.Message = "\nSpecify first point: ";
pPtRes = acDoc.Editor.GetPoint(pPtOpts);
colPt.Add(new Point2d(pPtRes.Value.X, pPtRes.Value.Y));

// Exit if the user presses ESC or cancels the command
if (pPtRes.Status == PromptStatus.Cancel) return;

int nCounter = 1;

while (nCounter <= 4)
{
// Prompt for the next points
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;
}

// Use the previous point as the base point
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;

// Increment the counter
nCounter = nCounter + 1;
}

// Create a polyline with 5 points
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);

// Close the polyline
acPoly.Closed = true;

// Query the area of the polyline
Application.ShowAlertDialog("Area of polyline: " +
acPoly.Area.ToString());

// Dispose of the polyline
}
}

提示用户输入(.NET)

作为 Document 对象的子对象的 Editor 对象定义用户输入方法。用户输入方法在AutoCAD命令行或动态输入工具提示中显示提示,并请求各种类型的输入。这种类型的用户输入对于屏幕坐标、实体选择和短字符串或数值的交互式输入最有用。如果应用程序需要输入大量选项或值,则Windows窗体可能比单个提示更合适。

每个用户输入法都在命令行上显示一个可选提示,并返回一个特定于所请求输入类型的值。例如, GetString 返回一个 PromptResult ,它允许您确定 GetString 方法的状态并检索用户输入的字符串。每个用户输入方法都有一个特定的返回值。

输入方法接受一个字符串作为显示的提示信息或一个控制用户输入的特定对象类型。这些对象类型允许您控制诸如 NULL 输入(按Enter键)、基点、零或负数的输入以及任意文本值的输入等操作。

若要强制提示符单独显示在一行中,请在使用VB.NET时在提示符字符串的开头使用回车/换行常量 (vbCrLf) 或换行常量(vbLf),或在C#中使用字符串“\n”。

本节中的主题

  • GetString方法(.NET)
  • GetPoint方法(.NET)
  • GetKeywords方法(.NET)
  • 控制用户输入(.NET)

GetString方法(.NET)

GetString 方法在命令提示符下提示用户输入字符串。 PromptStringOptions 对象允许您控制输入的内容以及提示消息的显示方式。 PromptStringOptions 对象的 AllowSpaces 属性控制在提示符下是否允许空格。如果设置为false,按空格键将终止输入。

在命令行中从用户处获取字符串值

下面的示例显示Enter Your Name提示,并要求通过按Enter键终止用户的输入(输入字符串中允许有空格)。输入的字符串将显示在消息框中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetStringFromUser")]
public static void GetStringFromUser()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;

PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: ");
pStrOpts.AllowSpaces = true;
PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts);

Application.ShowAlertDialog("The name entered was: " +
pStrRes.StringResult);
}

GetPoint方法(.NET)

GetPoint 方法提示用户在命令提示下指定点。 PromptPointOptions 对象允许您控制输入的内容以及提示消息的显示方式。 PromptPointOptions 对象的 UseBasePoint 和 BasePoint 属性控制是否从基点绘制rubber-band线。除了指定点之外,还可以使用 PromptPointOptions 对象的 Keywords 特性定义可以在命令提示下输入的关键字。

获取用户选择的点

下面的示例提示用户输入两个点,然后使用这两个点作为起点和终点绘制一条直线。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetPointsFromUser")]
public static void GetPointsFromUser()
{
// Get the current database and start the Transaction Manager
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

PromptPointResult pPtRes;
PromptPointOptions pPtOpts = new PromptPointOptions("");

// Prompt for the start point
pPtOpts.Message = "\nEnter the start point of the line: ";
pPtRes = acDoc.Editor.GetPoint(pPtOpts);
Point3d ptStart = pPtRes.Value;

// Exit if the user presses ESC or cancels the command
if (pPtRes.Status == PromptStatus.Cancel) return;

// Prompt for the end point
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;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
BlockTableRecord acBlkTblRec;

// Open Model space for write
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Define the new line
using (Line acLine = new Line(ptStart, ptEnd))
{
// Add the line to the drawing
acBlkTblRec.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);
}

// Zoom to the extents or limits of the drawing
acDoc.SendStringToExecute("._zoom _all ", true, false, false);

// Commit the changes and dispose of the transaction
acTrans.Commit();
}
}

GetKeywords方法(.NET)

GetKeywords 方法在命令提示符下提示用户输入关键字。 PromptKeywordOptions 对象允许您控制输入的内容以及提示消息的显示方式。 PromptKeywordOptions 对象的 Keywords 属性允许您定义可以在命令提示符下输入的关键字。

注意:下划线字符(“_”)具有特殊含义,不能用作关键字或关键字的一部分。

在命令行中从用户处获取关键字

下面的示例通过将属性 AllowNone 设置为false来强制用户输入关键字,这将禁止 NULL 输入(按Enter键)。 Keywords 属性用于添加允许的有效关键字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetKeywordFromUser")]
public static void GetKeywordFromUser()
{
Document acDoc = 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 = false;

PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

Application.ShowAlertDialog("Entered keyword: " +
pKeyRes.StringResult);
}

更用户友好的关键字提示符是在用户按Enter( NULL input)时提供默认值的提示符。请注意对以下示例的微小修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetKeywordFromUser2")]
public static void GetKeywordFromUser2()
{
Document acDoc = 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.Keywords.Default = "Arc";
pKeyOpts.AllowNone = true;

PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

Application.ShowAlertDialog("Entered keyword: " +
pKeyRes.StringResult);
}

控制用户输入(.NET)

在收集用户的输入时,您需要确保限制他们可以输入的信息类型,以便获得所需的响应。各种提示选项对象不仅用于定义在命令提示下显示的提示,还用于限制用户可以提供的输入。使用某些输入法,您不仅可以根据所使用的方法类型获得返回值,还可以获得关键字。

例如,您可以使用 GetPoint 方法让用户指定一个点或使用关键字进行响应。这就是LINE、CIRCLE和PLINE等命令的工作方式。

获取整数值或关键字

下面的示例提示用户输入正的非零整数值或关键字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetIntegerOrKeywordFromUser")]
public static void GetIntegerOrKeywordFromUser()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;

PromptIntegerOptions pIntOpts = new PromptIntegerOptions("");
pIntOpts.Message = "\nEnter the size or ";

// Restrict input to positive and non-negative values
pIntOpts.AllowZero = false;
pIntOpts.AllowNegative = false;

// Define the valid keywords and allow Enter
pIntOpts.Keywords.Add("Big");
pIntOpts.Keywords.Add("Small");
pIntOpts.Keywords.Add("Regular");
pIntOpts.Keywords.Default = "Regular";
pIntOpts.AllowNone = true;

// Get the value entered by the user
PromptIntegerResult pIntRes = acDoc.Editor.GetInteger(pIntOpts);

if (pIntRes.Status == PromptStatus.Keyword)
{
Application.ShowAlertDialog("Entered keyword: " +
pIntRes.StringResult);
}
else
{
Application.ShowAlertDialog("Entered value: " +
pIntRes.Value.ToString());
}
}

访问命令行(.NET)

您可以使用 SendStringToExecute 方法将命令直接发送到命令行。 SendStringToExecute 方法向命令行发送一个字符串。该字符串必须包含命令的参数,这些参数按照所执行命令的提示序列的预期顺序列出。

字符串中的空格或相当于回车的ASCII等效项相当于按键盘上的Enter键。与AutoLISP环境不同,调用不带参数的 SendStringToExecute 方法是无效的。

使用 SendStringToExecute 执行的命令是异步的,并且在.NET命令结束之前不会调用。如果你需要立即(同步)执行一个命令,你应该:

  • 使用COM自动化库的 SendCommand 方法,可以使用.NET COM Interop访问该库
  • P/Invoke为本地AutoCAD命令和使用ObjectARX或.NET API定义的命令调用非托管 acedCommand 或 acedCmd 方法
  • P/Invoke为通过AutoLISP定义的命令启用非托管 acedInvoke 方法

向命令行发送命令

下面的示例创建一个圆心为(2,2,0)、半径为4的圆。然后将图形缩放到图形中的所有几何图形。请注意,字符串末尾有一个空格,表示最后一次按Enter键以开始执行命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("SendACommandToAutoCAD")]
public static void SendACommandToAutoCAD()
{
Document acDoc = Application.DocumentManager.MdiActiveDocument;

// Draws a circle and zooms to the extents or
// limits of the drawing
acDoc.SendStringToExecute("._circle 2,2,0 4 ", true, false, false);
acDoc.SendStringToExecute("._zoom _all ", true, false, false);
}

扩展AutoCAD用户界面(.NET)

自定义对话框可用于获取用户输入并扩展AutoCAD用户界面的功能。

AutoCAD托管.NET类允许应用程序访问许多AutoCAD UI资源,并合并新的对话框或表单。 Autodesk.AutoCAD.Windows 命名空间中的某些类提供对AutoCAD要素对话框(如线型和颜色)的访问。这些类提供了一个显示表单的 ShowDialog 方法。当使用这些类时,应用程序自动获得对话框大小和位置设置的持久性。

Autodesk.AutoCAD.Windows 命名空间还公开了用于访问AutoCAD用户界面的某些可扩展元素(包括选项板和选项板集、托盘项目和状态栏)的界面。与工具选项板相关的类和接口位于 Autodesk.AutoCAD.Windows.ToolPalette 命名空间中。可以通过 Autodesk.AutoCAD.Windows.Visuals 类访问AutoCAD图标以及拾取点和拾取集位图。

AutoCAD托管的.NET API中的自定义对话框或表单直接从 System.Windows.Forms 命名空间扩展类。但是,这样的应用程序不应该调用 Form.ShowDialog 方法,而是使用 Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog 和 ShowModelessDialog 方法来显示它们的自定义表单。在AutoCAD扩展应用程序中使用 Form.ShowDialog 可能会导致意外行为。

注:翻译自ObjectARX: Managed .NET Developer’s Guide,且只保留了C#部分的代码