使用其他 Autocad .NET 库(而不是 Interop 库)可以做到这一点。但幸运的是,一个不排斥另一个。
您需要引用包含以下命名空间的库:
using Autodesk.Autocad.ApplicationServices
using Autodesk.Autocad.EditorInput
using Autodesk.Autocad.DatabaseServices
(您可以从 Autodesk 免费下载 Object Arx 库):
您需要从 AutoCAD Document 访问 Editor。
根据您显示的代码,您可能正在使用AcadDocument 文档。
因此,要将AcadDocument 转换为Document,请执行以下操作:
//These are extension methods and must be in a static class
//Will only work if Doc is saved at least once (has full name) - if document is new, the name will be
public static Document GetAsAppServicesDoc(this IAcadDocument Doc)
{
return Application.DocumentManager.OfType<Document>().First(D => D.Name == Doc.FullOrNewName());
}
public static string FullOrNewName(this IAcadDocument Doc)
{
if (Doc.FullName == "")
return Doc.Name;
else
return Doc.FullName;
}
获得Document 后,获取Editor 和GetSelection(Options, Filter)
选项包含属性SingleOnly 和SinglePickInSpace。将其设置为 true 可以满足您的需求。 (尝试两者,看看哪个效果更好)
//Seleciton options, with single selection
PromptSelectionOptions Options = new PromptSelectionOptions();
Options.SingleOnly = true;
Options.SinglePickInSpace = true;
//This is the filter for blockreferences
SelectionFilter Filter = new SelectionFilter(new TypedValue[] { new TypedValue(0, "INSERT") });
//calls the user selection
PromptSelectionResult Selection = Document.Editor.GetSelection(Options, Filter);
if (Selection.Status == PromptStatus.OK)
{
using (Transaction Trans = Document.Database.TransactionManager.StartTransaction())
{
//This line returns the selected items
AcadBlockReference SelectedRef = (AcadBlockReference)(Trans.GetObject(Selection.Value.OfType<SelectedObject>().First().ObjectId, OpenMode.ForRead).AcadObject);
}
}