CAD开发 选择实体并拖动
using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
namespace DragExample
{
public class DragCommands
{
[CommandMethod("DragSelection")]
public void DragSelection()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// 提示用户选择实体
PromptSelectionOptions pso = new PromptSelectionOptions();
pso.MessageForAdding = "选择要拖拽的实体: ";
PromptSelectionResult psr = ed.GetSelection(pso);
if (psr.Status != PromptStatus.OK)
return;
SelectionSet ss = psr.Value;
if (ss.Count == 0)
{
ed.WriteMessage("\n未选择任何实体。");
return;
}
// 获取基点
PromptPointOptions ppo = new PromptPointOptions("\n指定基点: ");
PromptPointResult pprBase = ed.GetPoint(ppo);
if (pprBase.Status != PromptStatus.OK)
return;
Point3d basePoint = pprBase.Value;
// 定义拖拽回调,用于计算变换矩阵
DragCallback dragCallback = (Point3d pt, ref Matrix3d mat) =>
{
if (basePoint.Equals(pt))
return SamplerStatus.NoChange;
mat = Matrix3d.Displacement(basePoint.GetVectorTo(pt));
return SamplerStatus.OK;
};
// 开始拖拽操作
PromptPointResult ppr = ed.Drag(ss, "\n指定第二点: ", dragCallback);
if (ppr.Status == PromptStatus.OK)
{
// 获取最终点并应用变换
Point3d secondPoint = ppr.Value;
Matrix3d finalMat = Matrix3d.Displacement(basePoint.GetVectorTo(secondPoint));
using (Transaction tr = db.TransactionManager.StartTransaction())
{
ObjectId[] ids = ss.GetObjectIds();
foreach (ObjectId id in ids)
{
Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite);
ent.TransformBy(finalMat);
}
tr.Commit();
}
ed.WriteMessage($"\n成功拖拽了 {ss.Count} 个实体。");
}
else
{
ed.WriteMessage("\n拖拽操作已取消。");
}
}
}
}
posted on 2025-11-15 04:50 sswsswssw1996 阅读(0) 评论(0) 收藏 举报
浙公网安备 33010602011771号