明经CAD社区

 找回密码
 注册

QQ登录

只需一步,快速开始

搜索
查看: 6026|回复: 10

[翔麟专集] [原创]翔麟专集——实现类似CAD中的Block创建块义命令程序

  [复制链接]
发表于 2009-9-19 10:44 | 显示全部楼层 |阅读模式



  1. [CommandMethod("CreateBlock")]
  2. public void CreateBlock()
  3. {
  4.     Database db = HostApplicationServices.WorkingDatabase;
  5.     Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
  6.     using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
  7.     {
  8.         ObjectId blockId = ObjectId.Null;                   //用于返回所创建的块的对象Id
  9.         BlockTableRecord record = new BlockTableRecord();   //创建一个BlockTableRecord类的对象,表示所要创建的块
  10.         record.Name = "MyBlock";                            //设置块名  
  11.         record.Origin = new Point3d(0, 0, 0);               //设置块的基点
  12.         using (Transaction trans = db.TransactionManager.StartTransaction())
  13.         {
  14.             BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);//以写的方式打开块表
  15.             if (!bt.Has(record.Name))
  16.             {
  17.                 //选择对象
  18.                 PromptSelectionResult res = ed.GetSelection();
  19.                 if (res.Status == PromptStatus.OK)
  20.                 {
  21.                     foreach (ObjectId id in res.Value.GetObjectIds())
  22.                     {
  23.                         Entity ent = trans.GetObject(id, OpenMode.ForWrite) as Entity;
  24.                         Entity NewEnt = (Entity)ent.Clone();
  25.                         record.AppendEntity(NewEnt);
  26.                     }
  27.                 }
  28.                 bt.Add(record);                             //在块表中加入块
  29.                 trans.AddNewlyCreatedDBObject(record, true);//通知事务处理
  30.             }
  31.             else
  32.             {
  33.                 ed.WriteMessage("此图块名已存在,请检查!");
  34.             }
  35.             trans.Commit();
  36.         }
  37.     }
  38. }

以下是Vs2008-CAD2010程序源文件:

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

x

评分

参与人数 1威望 +1 明经币 +2 金钱 +5 贡献 +10 激情 +10 收起 理由
雪山飞狐_lzh + 1 + 2 + 5 + 10 + 10 【好评】好程序

查看全部评分

发表于 2009-10-1 19:03 | 显示全部楼层

很好.这个功能.我已经有了.看晚了点了.

发表于 2010-11-17 10:32 | 显示全部楼层
Cool!!
发表于 2010-12-9 20:22 | 显示全部楼层
前几天还在为此功能郁闷呢,不过现在狐哥的帮助下已解决了...
发表于 2010-12-15 19:39 | 显示全部楼层
很不错。但有一个问题就是。创建块后,能不能把用来创建块的对像也一起转换成块呢。因为平时我们选择对象创建块后。选择的那些对象就会同时转换成块了。
发表于 2010-12-24 15:03 | 显示全部楼层
回复 lubing 的帖子

把这几句
foreach (ObjectId id in res.Value.GetObjectIds())
                    {
                        Entity ent = trans.GetObject(id, OpenMode.ForWrite) as Entity;
                        Entity NewEnt = (Entity)ent.Clone();
                        record.AppendEntity(NewEnt);
                    }
换成
record.AssumeOwnershipOf( new ObjectIdCollection(res.Value.GetObjectIds()));
发表于 2010-12-30 13:25 | 显示全部楼层
学习了,不错
发表于 2011-1-2 21:18 | 显示全部楼层
这个不能指定插入点
发表于 2018-7-18 09:05 | 显示全部楼层
2012版测试无法通过,需要改为下面代码:using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;

namespace CollectionCreation
{
    public class Commands
    {
        [CommandMethod("CB")]
        public void CreateBlock()
        {
            Document doc =
              Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            Transaction tr =
              db.TransactionManager.StartTransaction();
            using (tr)
            {
                // Get the block table from the drawing

                BlockTable bt =
                  (BlockTable)tr.GetObject(
                    db.BlockTableId,
                    OpenMode.ForRead
                  );

                // Check the block name, to see whether it's
                // already in use

                PromptStringOptions pso =
                  new PromptStringOptions(
                    "\nEnter new block name: "
                  );
                pso.AllowSpaces = true;

                // A variable for the block's name

                string blkName = "";

                do
                {
                    PromptResult pr = ed.GetString(pso);

                    // Just return if the user cancelled
                    // (will abort the transaction as we drop out of the using
                    // statement's scope)

                    if (pr.Status != PromptStatus.OK)
                        return;

                    try
                    {
                        // Validate the provided symbol table name

                        SymbolUtilityServices.ValidateSymbolName(
                          pr.StringResult,
                          false
                        );

                        // Only set the block name if it isn't in use

                        if (bt.Has(pr.StringResult))
                            ed.WriteMessage(
                              "\nA block with this name already exists."
                            );
                        else
                            blkName = pr.StringResult;
                    }
                    catch
                    {
                        // An exception has been thrown, indicating the
                        // name is invalid

                        ed.WriteMessage(
                          "\nInvalid block name."
                        );
                    }

                } while (blkName == "");

                // Create our new block table record...

                BlockTableRecord btr = new BlockTableRecord();

                // ... and set its properties

                btr.Name = blkName;

                // Add the new block to the block table

                bt.UpgradeOpen();
                ObjectId btrId = bt.Add(btr);
                tr.AddNewlyCreatedDBObject(btr, true);

                // Add some lines to the block to form a square
                // (the entities belong directly to the block)

                DBObjectCollection ents = SquareOfLines(5);
                foreach (Entity ent in ents)
                {
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                }

                // Add a block reference to the model space

                BlockTableRecord ms =
                  (BlockTableRecord)tr.GetObject(
                    bt[BlockTableRecord.ModelSpace],
                    OpenMode.ForWrite
                  );

                BlockReference br =
                  new BlockReference(Point3d.Origin, btrId);

                ms.AppendEntity(br);
                tr.AddNewlyCreatedDBObject(br, true);

                // Commit the transaction

                tr.Commit();

                // Report what we've done

                ed.WriteMessage(
                  "\nCreated block named \"{0}\" containing {1} entities.",
                  blkName, ents.Count
                );
            }
        }

        private DBObjectCollection SquareOfLines(double size)
        {
            // A function to generate a set of entities for our block

            DBObjectCollection ents = new DBObjectCollection();
            Point3d[] pts =
          { new Point3d(-size, -size, 0),
            new Point3d(size, -size, 0),
            new Point3d(size, size, 0),
            new Point3d(-size, size, 0)
          };
            int max = pts.GetUpperBound(0);

            for (int i = 0; i <= max; i++)
            {
                int j = (i == max ? 0 : i + 1);
                Line ln = new Line(pts[i], pts[j]);
                ents.Add(ln);
            }
            return ents;
        }
    }
}

发表于 2019-10-8 15:04 | 显示全部楼层
这个是VBA吗
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|CAD论坛|CAD教程|CAD下载|联系我们|关于明经|明经通道 ( 粤ICP备05003914号 )  
©2000-2023 明经通道 版权所有 本站代码,在未取得本站及作者授权的情况下,不得用于商业用途

GMT+8, 2024-3-29 15:55 , Processed in 0.206125 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表