CAD 二开中,当要在除当前文档外的其它文档的模型空间或图纸空间中添加图元时,需要先锁定其文档。用户可用要锁定的Document对象的LockDocument方法进行锁定。在调用LockDocument方法后,将返回一个DocumentLock对象。
本例创建一个新的文档然后在里面画一个圆。文档创建后,新文档的数据库会被锁定,然后一个圆会被添加到里面。圆添加后,数据库会被解锁,并且与其关联的文档窗口会被设置成当前文档。
附代码:
using AcTools;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Acdemo
{
public static class Acdemo
{
[CommandMethod("xx", 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;
// 创建一个半径为3圆心在5,5的圆 Create a circle with a radius of 3 at 5,5
Circle acCirc = new Circle();
acCirc.SetDatabaseDefaults();
acCirc.Center = new Point3d(5, 5, 0);
acCirc.Radius = 3;
acCirc.ColorIndex = 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;
}
}
}