AutoCAD C#

[AutoCAD C#]오토캐드에서 블럭(Block)을 선택, 레이어 변경하기

데브프로그라 2024. 2. 25. 18:37
반응형

AutoCAD에서 블럭(Block)들을 선택하여, 블럭의 레이어(Layer)를 변경할 수 있습니다.

Visual Studio와 AutoCAD .Net Wizard가 설치되어 있으시면 프로젝트 생성 후 새로운 클래스를 만들어 작성해 주시면 쉽게 활용할 수 있습니다.

 

다음의 코드는 ChBlkLayer 라는 명령어를 정의하고, 레이어를 "PIPE"로 변경합니다. 만약 " PIPE "라는 이름의 레이어가 존재하지 않으면 새로 생성합니다.

 

AutoCAD에서 이 코드를 사용하려면 다음 단계로 실행해 보세요.
1. Visual Studio에서 새 C# 프로젝트를 만듭니다.
    참조에 accoremgd.dll, acdbmgd.dll, AcDbMgd.dll, AcMgd.dll을 추가합니다.
2. 아래의 코드를 복사하여 프로젝트에 붙여넣습니다.
     빌드하여 .dll 파일을 생성합니다.
3. AutoCAD에서 NETLOAD 명령을 실행하여 .dll 파일을 로드합니다.
4.ChBlkLayer명령을 실행합니다.
5. AutoCAD에서 원하는 도면블럭(들)을 선택하여 명령을 실행하면 선택한 블럭들은 레이어(Layer)가 변경됩니다.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

namespace BlockProperties
{
    public class BlockPropertiesCommands
    {
        [CommandMethod(" ChBlkLayer ")]
        public void ChangeBlockProperties()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            string strNewBLockName = "Target";

            string strNewLayer = "pipe";


            // Select blocks
            PromptSelectionOptions selOpts = new PromptSelectionOptions();
            selOpts.MessageForAdding = "\n블럭(Block) 객체선택: ";

            PromptSelectionResult selRes = ed.GetSelection(selOpts);
            if (selRes.Status != PromptStatus.OK) return;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                SelectionSet selSet = selRes.Value;
                ObjectId[] objIds = selSet.GetObjectIds();

                foreach (ObjectId objId in objIds)
                {
                    BlockReference blkRef = trans.GetObject(objId, OpenMode.ForWrite) as BlockReference;
                    if (blkRef != null)
                    {
                        ed.WriteMessage("\n레이어(Layer): {0} =>변경 레이어:{1}", blkRef.Layer.ToString(), strNewLayer);

                        //레이어가 존재하지 않으면 레이어를 만든다.
                        if (!LayerExists(db, strNewLayer))
                        {
                            CreateLayer(db, newLayerName);
                        }
                        blkRef.Layer = newLayerName;
                    }
                }
                trans.Commit();
            }
        }

 

        //레이어(Layer)가 존재하는지 파악한다.
        private bool LayerExists(Database db, string layerName)
        {
            LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead);
            return lt.Has(layerName);
        }

       // 레이어(Layer)를 생성한다.
        private ObjectId CreateLayer(Database db, string layerName)
        {
            LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForWrite);
            if (!lt.Has(layerName))
            {
                LayerTableRecord ltr = new LayerTableRecord();
                ltr.Name = layerName;

               Color acColor = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 2);
                ltr.Color = acColor;
                ObjectId ltId = lt.Add(ltr);
                db.TransactionManager.AddNewlyCreatedDBObject(ltr, true);
                return ltId;
            }
            return ObjectId.Null;
        }
    }
}

(레이어가 변경된 블럭 모습)

결과:

블럭(Block) 객체선택: 반대 구석 지정: 9개를 찾음
블럭(Block) 객체선택:
레이어(Layer): 0 =>변경 레이어:Pipe
레이어(Layer): 0 =>변경 레이어:Pipe
레이어(Layer): 0 =>변경 레이어:Pipe
레이어(Layer): 0 =>변경 레이어:Pipe
레이어(Layer): 0 =>변경 레이어:Pipe
레이어(Layer): 0 =>변경 레이어:Pipe
레이어(Layer): 0 =>변경 레이어:Pipe
레이어(Layer): 0 =>변경 레이어:Pipe
레이어(Layer): 0 =>변경 레이어:Pipe

반응형

/* 코드복사 버튼 */ pre { position: relative; overflow: visible; } pre .copy-button { opacity: 0; position: absolute; right: 8px; top: 4px; padding: 6px 18px; color: rgb(255, 255, 255); background: rgba(255, 223, 0, 0.6); border-radius: 5px; transition: opacity .3s ease-in-out; } pre:hover .copy-button { opacity: 1; } pre .copy-button:hover { color: #eee; transition: all ease-in-out 0.3s; } pre .copy-button:active { color: #33f; transition: all ease-in-out 0.1s; } .copy-message:before { content: attr(copy-message); position: absolute; left: -95px; top: 0px; padding: 6px 18px; color: #fff; background: rgba(255, 223, 0, 0.6); border-radius: 5px; } /* 코드복사 버튼 END */