CAD二次开发 快速选择插入其他项目块

需求:选择其他CAD文件,展示选择CAD文件中所有的块定义,然后选择需要插入的块,鼠标有块定义的跟随,点击放置块定义。

实现效果

请添加图片描述

代码

1.定义BlockJig拖拽类

public class BlockJig : EntityJig
{private Point3d _currentPosition;private Point3d _originalPosition;public BlockJig(Entity entity, Point3d originalPosition) : base(entity){_originalPosition = originalPosition;_currentPosition = originalPosition;}protected override SamplerStatus Sampler(JigPrompts prompts){JigPromptPointOptions opts = new JigPromptPointOptions("\n指定放置点:");opts.UseBasePoint = true;opts.BasePoint = _originalPosition;opts.UserInputControls = UserInputControls.Accept3dCoordinates | UserInputControls.NullResponseAccepted;PromptPointResult result = prompts.AcquirePoint(opts);if (result.Status == PromptStatus.OK){_currentPosition = result.Value;return SamplerStatus.OK;}else if (result.Status == PromptStatus.Cancel){return SamplerStatus.Cancel;}return SamplerStatus.NoChange;}protected override bool Update(){try{(Entity as BlockReference).Position = _currentPosition;}catch (Exception ex){MessageBox.Show(ex.Message + ex.StackTrace);}return true;}
}

2.界面

界面使用了handycontrol控件库,大家使用的时候记得先安装handycontrol的NuGet包

<Windowx:Class="CADTools.Views.InsertExternalBlockView"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:hc="https://handyorg.github.io/handycontrol"xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"xmlns:local="clr-namespace:CADTools.Views"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"Title="插入外部图纸中的块"Width="400"Height="450"mc:Ignorable="d"><Window.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml" /><ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" /></ResourceDictionary.MergedDictionaries></ResourceDictionary></Window.Resources><i:Interaction.Triggers><i:EventTrigger EventName="Closed"><i:InvokeCommandAction Command="{Binding ClosedCommand}" /></i:EventTrigger></i:Interaction.Triggers><Grid><Grid.RowDefinitions><RowDefinition Height="40" /><RowDefinition /></Grid.RowDefinitions><StackPanel Margin="10,0" Orientation="Horizontal"><TextBlock VerticalAlignment="Center" Text="CAD图纸位置:" /><TextBoxWidth="200"Height="30"Margin="10,0"Text="{Binding CADPath, UpdateSourceTrigger=PropertyChanged}" /><ButtonCommand="{Binding SelectCommand}"Content="选择"Style="{StaticResource ButtonPrimary}" /></StackPanel><ListBoxGrid.Row="1"Margin="10"ItemsSource="{Binding Items, UpdateSourceTrigger=PropertyChanged}"><ListBox.ItemsPanel><ItemsPanelTemplate><WrapPanel Orientation="Horizontal" /></ItemsPanelTemplate></ListBox.ItemsPanel><ListBox.ItemTemplate><DataTemplate><Grid Margin="10"><Grid.RowDefinitions><RowDefinition /><RowDefinition Height="30" /></Grid.RowDefinitions><ButtonWidth="110"Height="110"HorizontalAlignment="Center"VerticalAlignment="Center"Command="{Binding DataContext.BlockClikCommand, RelativeSource={RelativeSource AncestorType=Window, AncestorLevel=1, Mode=FindAncestor}}"CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem, AncestorLevel=1, Mode=FindAncestor}, Path=DataContext}"><Button.Background><ImageBrush ImageSource="{Binding Image}" /></Button.Background></Button><TextBlockGrid.Row="1"HorizontalAlignment="Center"VerticalAlignment="Center"Text="{Binding BlockName, UpdateSourceTrigger=PropertyChanged}" /></Grid></DataTemplate></ListBox.ItemTemplate></ListBox></Grid>
</Window>

3.定义ViewModel类

public class InsertExternalBlockViewModel : BaseNotify
{#region UIprivate string cadPath;public string CADPath{get { return cadPath; }set { cadPath = value; this.RaisePropertyChanged(); }}private ObservableCollection<BlockModel> items = new ObservableCollection<BlockModel>();public ObservableCollection<BlockModel> Items{get { return items; }set { items = value; this.RaisePropertyChanged(); }}#endregion#region Method/// <summary>/// 选择按钮/// </summary>public DelegateCommand SelectCommand { get; set; }/// <summary>/// 图片点击按钮/// </summary>public DelegateCommand BlockClikCommand { get; set; }/// <summary>/// 关闭按钮/// </summary>public DelegateCommand ClosedCommand { get; set; }private void ClosedExecute(object obj){_loadDB?.Dispose();}private void BlockCilkExecute(object obj){BlockModel model = obj as BlockModel;if (model == null) return;Document doc = Application.DocumentManager.MdiActiveDocument;WindowMethod.SetFocus(doc.Window.Handle);Database db = doc.Database;Editor ed = doc.Editor;DocumentLock l = doc.LockDocument();using (Transaction trans = _loadDB.TransactionManager.StartTransaction()){try{BlockTable bt = trans.GetObject(_loadDB.BlockTableId, OpenMode.ForRead) as BlockTable;ObjectIdCollection ids = new ObjectIdCollection{bt[model.BlockName]};//复制临时数据库中的块到当前数据库的块表中_loadDB.WblockCloneObjects(ids, db.BlockTableId, new IdMapping(), DuplicateRecordCloning.Ignore, false);trans.Commit();}catch (Exception ex){MessageBox.Show(ex.Message + ex.StackTrace);}}using (Transaction trans2 = db.TransactionManager.StartTransaction()){BlockTable bt = trans2.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;ObjectId targetID = bt[model.BlockName];BlockReference blockRef = new BlockReference(new Point3d(0, 0, 0), targetID);BlockJig blockJig = new BlockJig(blockRef, new Point3d(0, 0, 0));PromptPointResult jigResult = ed.Drag(blockJig) as PromptPointResult;if (jigResult.Status == PromptStatus.OK){blockRef = new BlockReference(jigResult.Value, targetID);BlockTableRecord currentSpace = trans2.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;var nwID = currentSpace.AppendEntity(blockRef);trans2.AddNewlyCreatedDBObject(blockRef, true);trans2.Commit();}}l.Dispose();}private void SelectExecute(object obj){System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();dialog.Multiselect = false;dialog.Title = "选择CAD文件";dialog.Filter = "CAD 文件 (*.dwg)|*.dwg";if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)return;if (string.IsNullOrEmpty(dialog.FileName)) return;CADPath = dialog.FileName;Items = new ObservableCollection<BlockModel>();_loadDB = new Database(false, true);try{_loadDB.ReadDwgFile(dialog.FileName, FileOpenMode.OpenForReadAndReadShare, true, null);_loadDB.CloseInput(true);using (Transaction trans = _loadDB.TransactionManager.StartTransaction()){BlockTable bt = trans.GetObject(_loadDB.BlockTableId, OpenMode.ForRead) as BlockTable;ObjectIdCollection ids = new ObjectIdCollection();foreach (ObjectId btrId in bt){BlockTableRecord btr = trans.GetObject(btrId, OpenMode.ForRead) as BlockTableRecord;if (!btr.IsLayout && !btr.IsAnonymous){BlockModel model = new BlockModel();model.Id = btrId;model.BlockName = btr.Name;model.Image = GetBlockImage(btr, 110, 110, Autodesk.AutoCAD.Colors.Color.FromRgb(0, 0, 0));Items.Add(model);}}}}catch (Exception ex){MessageBox.Show(ex.Message, ex.StackTrace);}}/// <summary>/// 得到块定义的图片/// </summary>/// <param name="blockRecord"></param>/// <param name="width"></param>/// <param name="height"></param>/// <param name="backgroundColor"></param>/// <returns></returns>/// <exception cref="NullReferenceException"></exception>private BitmapSource GetBlockImage(BlockTableRecord blockRecord, int width, int height, Autodesk.AutoCAD.Colors.Color backgroundColor){if (blockRecord == null)throw new NullReferenceException(nameof(blockRecord));var image = Utils.GetBlockImage(blockRecord.Id, width, height, backgroundColor);if (image == IntPtr.Zero) return null;BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(image, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());return bitmapSource;}#endregion#region privateprivate Database _loadDB;#endregionpublic InsertExternalBlockViewModel(){SelectCommand = new DelegateCommand(){ExecuteCommand = SelectExecute};BlockClikCommand = new DelegateCommand(){ExecuteCommand = BlockCilkExecute};ClosedCommand = new DelegateCommand(){ExecuteCommand = ClosedExecute};}}public class BlockModel
{public string BlockName { get; set; }public BitmapSource Image { get; set; }public ObjectId Id { get; set; }public BlockModel() { }
}

4.定义CAD命令类

using Autodesk.AutoCAD.Runtime;
using CADTools.Commands.插入外部块;
using CADTools.ViewModels;
using CADTools.Views;
[assembly: CommandClass(typeof(InsertExternalBlockCmd))]namespace CADTools.Commands.插入外部块
{public class InsertExternalBlockCmd{[CommandMethod("InsertExternalBlock")]public void InsertExternalBlock(){InsertExternalBlockViewModel vm = new InsertExternalBlockViewModel();InsertExternalBlockView win = new InsertExternalBlockView();win.DataContext = vm;win.Show();}}
}

补充WindowMethod类

/// <summary>
/// 界面辅助方法
/// </summary>
public class WindowMethod
{[DllImport("user32.dll", EntryPoint = "SetFocus")]public static extern int SetFocus(IntPtr hWnd);// 定义ShowWindow函数和常量public static int SW_SHOWMINIMIZED = 2; // 参数,用于最小化窗口[DllImport("user32.dll")]public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);[DllImport("user32.dll")]public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);[DllImport("user32.dll")]public static extern bool SetForegroundWindow(IntPtr hWnd);public static int SW_RESTORE = 9; // 参数用于恢复最小化的窗口}

总结

代码中还存在不完善的地方,只是搭了一个简单的框架,可以自行扩展。没有设置块覆盖等问题,可以自己添加的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/625947.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

开源项目|使用go语言搭建高效的环信 IM Rest接口(附源码)

项目背景 环信 Server SDK 是对环信 IM REST API 的封装&#xff0c; 可以节省服务器端开发者对接环信 API 的时间&#xff0c;只需要配置自己的 App Key 相关信息即可使用。 环信目前提供java和PHP版本的Server SDK&#xff0c;此项目使用go语言对环信 IM REST API 进行封装…

plsql developer 一键格式化sql/美化sql

PL/SQL 格式化工具 以 Oracle SQL Developer 为例&#xff0c;使用一键格式化的步骤如下&#xff1a; 打开 Oracle SQL Developer。在“文件”菜单中&#xff0c;选择“打开文件”&#xff0c;然后选择你的 PL/SQL 文件。打开文件后&#xff0c;你可以通过右键菜单选择“格式…

论文解读:(CoCoOP)Conditional Prompt Learning for Vision-Language Models

文章汇总 存在的问题 CoOp的一个关键问题:学习到的上下文不能推广到同一数据集中更广泛的未见类&#xff0c;这表明CoOp过拟合了训练期间观察到的基本类。 动机 为了解决弱泛化问题&#xff0c;我们引入了一个新的概念:条件提示学习。关键思想是使提示取决于每个输入实例(图…

RAG (Retrieval Augmented Generation) 结合 LlamaIndex、Elasticsearch 和 Mistral

作者&#xff1a;Srikanth Manvi 在这篇文章中&#xff0c;我们将讨论如何使用 RAG 技术&#xff08;检索增强生成&#xff09;和 Elasticsearch 作为向量数据库来实现问答体验。我们将使用 LlamaIndex 和本地运行的 Mistral LLM。 在开始之前&#xff0c;我们将先了解一些术…

【SpringBoot实战篇】登录认证

&#x1f340;&#x1f338;明确需求--接口文档--思路分析--开发--测试&#x1f338;&#x1f340;&#x1f495; 1 明确需求 2 接口文档 登录 3 思路分析 UserServic、UserMapper在注册的时候已经实现 现在我们重点看UserController 控制器 4 开发&#xff08;实现&#xff0…

nginx 卸载和安装超详细教程

一、前言 由于现在nginx有版本漏洞&#xff0c;所以很多安装过nginx的需要卸载重新安装&#xff0c;没安装过的&#xff0c;切记不要乱安装版本。 OK以上版本切记不能再用了&#xff01; 废话不多说&#xff0c;直接上干货。 二、卸载 1、停止Nginx进程 命令行停止&#xf…

鸿蒙语言TypeScript学习第18天:【泛型】

1、TypeScript 泛型 泛型&#xff08;Generics&#xff09;是一种编程语言特性&#xff0c;允许在定义函数、类、接口等时使用占位符来表示类型&#xff0c;而不是具体的类型。 泛型是一种在编写可重用、灵活且类型安全的代码时非常有用的功能。 使用泛型的主要目的是为了处…

ubuntu+安装Google Protobuf 库

本文参考文章如下 https://blog.csdn.net/wzw1609119742/article/details/119712422#t18https://blog.csdn.net/j8267643/article/details/134133091https://blog.csdn.net/jax_fanyang/article/details/135937002?spm1001.2014.3001.5502 现在论坛上据大部分的教程都是下面…

树莓派使用总结

手上拿到了一块Raspberry Pi 4B板子。研究一下怎么用。 安装系统 直接到官网【Raspberry Pi 】下载在线安装助手 安装好后&#xff0c;打开软件&#xff0c;选择好板子型号、系统、TF卡&#xff0c;一路下一步就行。 树莓派接口 直接查看官方的资料【Raspberry Pi hardwar…

(C++) 稀疏表Sparse Table

目录 一、介绍 1.1 倍增 1.2 稀疏表ST 二、原理 三、代码实现 3.1 创建稀疏表 3.2 初始化数值 3.3 ST查询 一、介绍 1.1 倍增 倍增的思想是在数据空间特别大的时候&#xff0c;快速进行查找搜索而使用的。例如想要在一个数据量为n的递增数组中查找到等于x的下标&#x…

【6个好玩的linux终端程序】----做一个有趣的IT男

【6个好玩的linux终端程序】----做一个有趣的IT男 一、ASCIIquarium--水族馆二、cmatrix--矩阵代码三、cowsay --会说话的小牛四、sl --火车动画五、fortune--随机名言警句六、bastet-俄罗斯方块 &#x1f496;The Begin&#x1f496;点点关注&#xff0c;收藏不迷路&#x1f4…

Jackson 2.x 系列【25】Spring Boot 集成之起步依赖、自动配置

有道无术&#xff0c;术尚可求&#xff0c;有术无道&#xff0c;止于术。 本系列Jackson 版本 2.17.0 本系列Spring Boot 版本 3.2.4 源码地址&#xff1a;https://gitee.com/pearl-organization/study-jaskson-demo 文章目录 1. 前言2. 起步依赖3. 自动配置3.1 JacksonPrope…