运行环境Visual Studio 2022 c# cad2016

一、代码说明
SelectLayer方法是一个自定义的AutoCAD命令方法,通过[CommandMethod("SelectLayer")]进行标记。- 方法首先获取当前活动文档,并检查是否有效。
 - 创建一个名为"SelectLayer"的PaletteSet,并设置其样式以显示自动隐藏和关闭按钮。
 - 初始化一个ComboBox,并遍历
GetLayerList()方法返回的所有图层记录,将图层名添加到ComboBox的Items集合中。 - 创建一个OK按钮,绑定Click事件处理程序,在点击时读取ComboBox中选定项的文本内容,并显示所选图层名称的警告消息。
 - 将ComboBox和OK按钮放入数组中,并将这个数组添加到PaletteSet的控件集中。
 - 最后,使PaletteSet可见。
 
GetLayerList()方法:
- 该方法负责从数据库中获取所有图层表记录。
 - 使用事务安全地打开数据库,并读取LayerTable对象。
 - 遍历LayerTable中的每个ObjectId,将其转换为LayerTableRecord对象并添加到列表中。
 - 提交事务并返回包含所有图层记录的列表。
 
二、完整代码
internal class layername
{
    [CommandMethod("SelectLayer")]
    public void SelectLayer()
    {
        Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
        if (doc != null)
        {
            PaletteSet ps = new PaletteSet("Select Layer");
            ps.Style = PaletteSetStyles.ShowAutoHideButton | PaletteSetStyles.ShowCloseButton;
            ps.Size = new System.Drawing.Size(200, 100);
            System.Windows.Forms.ComboBox comboBox = new System.Windows.Forms.ComboBox();
            foreach (LayerTableRecord layer in GetLayerList())
            {
                comboBox.Items.Add(layer.Name);
            }
            System.Windows.Forms.Button okButton = new System.Windows.Forms.Button();
            okButton.Text = "OK";
            okButton.Click += (sender, e) =>
            {
                string selectedLayer = comboBox.SelectedItem.ToString();
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Selected Layer: " + selectedLayer);
            };
            System.Windows.Forms.Panel panel = new System.Windows.Forms.Panel();
            panel.Controls.Add(comboBox);
            panel.Controls.Add(okButton);
            ps.Add("Select Layer", panel);
            ps.Visible = true;
        }
    }
    private IEnumerable<LayerTableRecord> GetLayerList()
    {
        List<LayerTableRecord> layers = new List<LayerTableRecord>();
        using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
        {
            LayerTable layerTable = (LayerTable)tr.GetObject(HostApplicationServices.WorkingDatabase.LayerTableId, OpenMode.ForRead);
            foreach (ObjectId id in layerTable)
            {
                LayerTableRecord layer = (LayerTableRecord)tr.GetObject(id, OpenMode.ForRead);
                layers.Add(layer);
            }
            tr.Commit();
        }
        return layers;
    }
} 
//感谢大家的点赞,收藏,转发,关注



















