autocad.net

AutoCAD.net

System.InvalidProgramException异常错误

autocad.net通过组件方式访问autocad,所以需要和autocad通信,不能单独exe启动 参考:https://forums.autodesk.com/t5/forums/forumtopicprintpage/board-id/152/message-id/53529/print-single-message/false/page/1

表空间

  • Block Table(块表)
  • Layer Table(层表)
  • TextStyle Table(文字样式表)
  • DimStyle Table(尺寸样式表)
  • Linetype Table(线型表)
  • UCS Table(用户坐标系表)
  • View Table(视图表)
  • Viewport Table(视口表)
  • RegApp Table(应用程序注册表)
  • DrawOrderTable (绘图层级)

对应的访问方式:BlockTable、LayerTable、TextStyleTable、DimStyleTable…

autocad纤程

autocad使用纤程(用户模式下的线程,一个线程可包含多个纤程),纤程转换线程:

PVOID ConvertThreadToFiber(PVOID pvParam);

autocad调试,线程和纤程交互需要添加,否则只能调试纤程代码不能调试线程

Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("NEXTFIBERWORLD", 0); 

添加上面配置后autocad才能附加调试 调试过程中vs频繁崩溃 VS 2015 设置

Turn on “Use Managed Compatibility Mode” via Tools –> Options –> Debugging.
Turn on “Enable native code debugging”(托管兼容模式) from Project –> Properties –> Debug.
Turn off "Xaml ui Debug"

System.InvalidOperationException: 已在“VisualTreeChanged”事件期间更改可视化树。

Tools -> Options -> Debugging -> General -> Uncheck: Enable UI Debugging Tools for XAML

加载字体(**形未定义)

  • 建议不要使用vs2017,开发是问题比较多,而且vs2017出现了平凡退出的情况
  • 打开调试本地代码,才能加载字体调试,否则只能独立运行加载字体,或者平凡出现** 形未定义(加载字符集错误)

edit.getpoint()阻塞用户交互

autocad用户交互,阻塞当前代码执行,不阻塞消息事件,所以和自定义界面交互,可能出现循环阻塞在同一行代码的情况,需要把函数定义成命令(相同命令重复执行阻塞,只能内部条件避免

	[CommandMethod("命令名称", CommandFlags.Session)]

避免autocad提示gedit 3内部异常 或者发送取消命令(autocad 2014)

	Doc.Editor.IsQuiescent判断是否有命令
	Doc.SendStringToExecute("\x03", false, false, false);   取消,无空格,其他命令需要(非同步执行,C++ autocad com组件可以实现同步执行)
	Doc.SendStringToExecute(" ", false, false, false);   一个空格空输入

	Application.SetSystemVariable("FILEDIA", 0);命令隐藏
	Application.SetSystemVariable("FILEDIA", 1);命令打开

Cad purge清理为引用数据

	public void ClearUnrefedBlocks()
	{
	    Document doc = Application.DocumentManager.MdiActiveDocument;
	    Editor ed = doc.Editor;
	    Database db = doc.Database;
	    using (Transaction trans = db.TransactionManager.StartTransaction())
	    {
	        BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite)
	            as BlockTable;
	        foreach (ObjectId oid in bt)
	        {
	            BlockTableRecord btr = trans.GetObject(oid, OpenMode.ForWrite)
	                as BlockTableRecord;
	            if (btr.GetBlockReferenceIds(false, false).Count == 0
	                && !btr.IsLayout)
	            {
	                btr.Erase();
	            }
	        }
	        trans.Commit();
	    }
	}

代理对象

autocad支持自定义对象和以C++Com模式实现的ObjectARX对象(代理对象) 代理对象通过Object Enabler创建

  • Object Enabler 可使图形中的自定义对象的行为比代理图形更加智能

数据操作

修改数据line转polyline(添加LockDocument、UpgradeOpen、DowngradeOpen避免异常)

	using (Transaction trans = DwgConvert.Doc.Database.TransactionManager.StartTransaction())
	{
		using (DocumentLock m_DocumentLock = Doc.LockDocument())
		{
			entity.UpgradeOpen();//打开
			Autodesk.AutoCAD.DatabaseServices.Line ln = entity as Autodesk.AutoCAD.DatabaseServices.Line;
		    Polyline pl = new Polyline();
		    pl.AddVertexAt(0, new Point2d(ln.StartPoint.X,ln.StartPoint.Y),0,0,0);
		    pl.AddVertexAt(1, new Point2d(ln.EndPoint.X,ln.EndPoint.Y), 0, 0, 0);
		    pl.Layer = ln.Layer;
	        pl.ConstantWidth = proIntRes.Value;
	        modelSpace.AppendEntity(pl);
	        entity.Database.TransactionManager.AddNewlyCreatedDBObject(pl,true);
	        ln.Erase();//删除数据
		    entity.DowngradeOpen();
	    }
	    trans.Commit();
	}

其他数据修改操作封装

//插入图块(非外部文件)
public static void InsertBlock(this BlockTableRecord blokRec, Autodesk.AutoCAD.Geometry.Point3d pt)
        {
            using (Database sourceDb = new Database(true, false))
            {
                Autodesk.AutoCAD.DatabaseServices.Polyline pl = new Autodesk.AutoCAD.DatabaseServices.Polyline(4);
                pl.AddVertexAt(0, new Autodesk.AutoCAD.Geometry.Point2d(50,-50), 0, 0, 0);
                pl.AddVertexAt(1, new Autodesk.AutoCAD.Geometry.Point2d(-50,-50), 0, 0, 0);
                pl.AddVertexAt(2, new Autodesk.AutoCAD.Geometry.Point2d(0,100), 0, 0, 0);
                pl.AddVertexAt(3, new Autodesk.AutoCAD.Geometry.Point2d(50, -50), 0, 0, 0);
                using (Transaction trans = sourceDb.TransactionManager.StartTransaction())
                {
                    BlockTable bt = trans.GetObject(sourceDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    btr.AppendEntity(pl);
                    trans.AddNewlyCreatedDBObject(pl, true);
                    trans.Commit();
                }

                ObjectId blockId = blokRec.Database.Insert("camera", sourceDb, false);
                BlockReference blockRef = new BlockReference(pt, blockId); // 通过块定义添加块参照
                blokRec.AppendEntity(blockRef); //把块参照添加到块表记录
                blockRef.Database.TransactionManager.AddNewlyCreatedDBObject(blockRef, true);
                //return blockRef;
            }
        }
//获取图层名称
        public static ObjectId GetLayerObjectId(this Database db, string layerName)
        {
            LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead);
            //if (!lt.Has(layerName))
            //{
            //    LayerTableRecord ltr = new LayerTableRecord();
            //    ltr.Name = layerName;
            //    lt.UpgradeOpen();
            //    lt.Add(ltr);

            //    db.TransactionManager.AddNewlyCreatedDBObject(ltr, true);
            //    lt.DowngradeOpen();
            //}
            if (lt.Has(layerName))
                return lt[layerName];
            else
                return ObjectId.Null;
        }
        //设置图层名称
        public static void SetLayer(this Database db, string layerName)
        {
            LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead);
            if (lt.Has(layerName))
            {
                db.Clayer = lt[layerName];
            }
        }
        //添加Block属性
        public static void AddAttsToBlocks(this BlockReference block, AttributeDefinition atts)
        {
            Database db = block.Database;//获取数据库对象
            BlockTableRecord btr = db.TransactionManager.GetObject(block.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            btr.UpgradeOpen();
            btr.AppendEntity(atts);
            db.TransactionManager.AddNewlyCreatedDBObject(atts, true);
            //db.TransactionManager.Dispose();
            btr.DowngradeOpen();
        }
        //添加Block属性
        public static void AddAttributeDefinitionToBlocks(this ObjectId blockId, AttributeDefinition atts)
        {
            Database db = blockId.Database;//获取数据库对象
            BlockTableRecord btr = blockId.GetObject(OpenMode.ForWrite) as BlockTableRecord;
            btr.AppendEntity(atts);
            db.TransactionManager.AddNewlyCreatedDBObject(atts, true);
            db.TransactionManager.Dispose();
            btr.DowngradeOpen();
        }
        //修改Block属性
        public static void UpdateAttributesInBlock(this BlockReference blockRef, Dictionary<string, string> attNameValues)
        {
            foreach (ObjectId id in blockRef.AttributeCollection)
            {
                AttributeReference attref = id.GetObject(OpenMode.ForRead) as AttributeReference;
                if (attNameValues.ContainsKey(attref.Tag.ToUpper()))
                {
                    attref.UpgradeOpen();
                    //设置属性值
                    attref.TextString = attNameValues[attref.Tag.ToUpper()].ToString();
                    attref.DowngradeOpen();
                }
            }
        }
        //查询属性
        public static string GetValueAttributesInBlock(this BlockReference blockRef, string attNameValue)
        {
            foreach (ObjectId id in blockRef.AttributeCollection)
            {
                AttributeReference attref = id.GetObject(OpenMode.ForRead) as AttributeReference;
                if (attNameValue.ToUpper() == attref.Tag.ToUpper())
                {
                    //设置属性值
                    return attref.TextString;
                }
            }
            return "";
        }
        //添加属性
        public static void AddAttributeToBlockTableRecord(this BlockTableRecord blokRec, BlockReference blockRef, Dictionary<string,string> atts)
        {
            if (!blokRec.HasAttributeDefinitions)//添加属性定义
            {
                AttributeDefinition aDef = new AttributeDefinition() { Tag=""};
                blokRec.ObjectId.AddAttributeDefinitionToBlocks(aDef);
            }
            foreach (KeyValuePair<string, string> attribute in atts)
            {
                if (blockRef.GetValueAttributesInBlock(attribute.Key) == "")
                {
                    AttributeReference attRef = new AttributeReference() { Tag = attribute.Key, TextString = attribute.Value };
                    if (attribute.Key == "图例编码" || attribute.Key == "类型编号" || attribute.Key == "图例分类")
                        attRef.Visible = false;
                    blockRef.AttributeCollection.AppendAttribute(attRef);
                    blockRef.Database.TransactionManager.AddNewlyCreatedDBObject(attRef, true);
                    attRef.Dispose();
                }
                else
                {
                    blockRef.UpdateAttributesInBlock(new Dictionary<string, string>() { { attribute.Key, attribute.Value } });
                }
            }
        }
        public static BlockReference ReferenceOuterFileBlock(this BlockTableRecord blokRec, Autodesk.AutoCAD.Geometry.Point3d pt,string file,string name)
        {
            ObjectId refid = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.AttachXref(file, name);
            //ObjectId refid = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.OverlayXref(file, name);// 通过外部文件获取图块定义的ObjectId
            BlockReference blockRef = new BlockReference(pt, refid); // 通过块定义添加块参照
            blokRec.AppendEntity(blockRef); //把块参照添加到块表记录
            blockRef.Database.TransactionManager.AddNewlyCreatedDBObject(blockRef, true); // 通过事务添加块参照到数据库
            return blockRef;
        }
        public static BlockReference ImportOuterFileBlock(this BlockTableRecord blokRec, Autodesk.AutoCAD.Geometry.Point3d pt,string file,string name)
        {
            //Database sourceDb = new Database(false, true);
            //sourceDb.ReadDwgFile(file, FileShare.Read, true, "");
            //ObjectIdCollection blockIds = new ObjectIdCollection();
            //using (Transaction ts = database.TransactionManager.StartTransaction())
            //{
            //    BlockTable bt = (BlockTable)ts.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false);
            //    foreach (ObjectId btrId in bt)
            //    {
            //        BlockTableRecord btr = (BlockTableRecord)ts.GetObject(btrId, OpenMode.ForRead, false);
            //        if (!btr.IsAnonymous && !btr.IsLayout)
            //            blockIds.Add(btrId);
            //        btr.Dispose();
            //    }
            //    IdMapping mapping = new IdMapping();
            //    sourceDb.WblockCloneObjects(blockIds, database.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
            //}
            //sourceDb.Dispose();
            if (!File.Exists(file)) throw new Exception(string.Format("\n文件找不到({0})",file));
            using (Database sourceDb = new Database(false, false))
            {
                sourceDb.ReadDwgFile(file, FileShare.Read, true, "");
                sourceDb.CloseInput(true);
                ObjectId blockId = blokRec.Database.Insert(name, sourceDb, false);
                BlockReference blockRef = new BlockReference(pt, blockId); // 通过块定义添加块参照
                blokRec.AppendEntity(blockRef); //把块参照添加到块表记录
                blockRef.Database.TransactionManager.AddNewlyCreatedDBObject(blockRef, true);
                return blockRef;
            }
        }
        public static void AddDataToEntity(this Entity entity,Dictionary<string,string> dict)
        {//绑定数据
            if (entity.ExtensionDictionary == ObjectId.Null)
            {
                entity.CreateExtensionDictionary();
            }
            DBDictionary xDict = entity.Database.TransactionManager.GetObject(entity.ExtensionDictionary, OpenMode.ForRead) as DBDictionary;
            foreach (KeyValuePair<string, string> pair in dict)
            {
                if (!xDict.Contains(pair.Key))
                {
                    xDict.UpgradeOpen();

                    Xrecord xRec = new Xrecord();
                    ResultBuffer rb = new ResultBuffer();
                    rb.Add(new TypedValue((int)DxfCode.Text, pair.Value));
                    xRec.Data = rb;
                    xDict.SetAt(pair.Key, xRec);
                    xDict.DowngradeOpen();

                    entity.Database.TransactionManager.AddNewlyCreatedDBObject(xRec, true);
                }
            }
        }
        public static string GetEntityData(this Entity entity,string key)
        {//获取数据
            using (Transaction tr = entity.Database.TransactionManager.StartTransaction())
            {
                if (entity.ExtensionDictionary != ObjectId.Null)
                {
                    DBDictionary xDict = tr.GetObject(entity.ExtensionDictionary, OpenMode.ForRead) as DBDictionary;
                    if (xDict.Contains(key))
                    {
                        ObjectId xRecId = xDict.GetAt(key);
                        Xrecord xRec = tr.GetObject(xRecId, OpenMode.ForRead) as Xrecord;
                        if (xRec != null)
                            return xRec.Data.AsArray()[0].Value.ToString();
                        else
                            return "";
                    }
                }
                return "";
            }
        }
        public static void ScaleModel(this BlockReference entity, string text)
        {//图例缩放
            //Extents3d extend = entity.GeometryExtentsBestFit(Autodesk.AutoCAD.Geometry.Matrix3d.Rotation(entity.Rotation,new Autodesk.AutoCAD.Geometry.Vector3d(0,0,1),entity.Position));
            //double dMaxX = extend.MaxPoint.X, dMaxY = extend.MaxPoint.Y, dMinX = extend.MinPoint.X, dMinY = extend.MinPoint.Y;

            List<Point> ptls = new List<Point>();
            Block.RecurBlockReference(entity, new Point(),0, ref ptls);//解析数据
            if (ptls.Count == 0) return;
            double dMaxX = ptls.Max(o => o.X), dMaxY = ptls.Max(o => o.Y), dMinX = ptls.Min(o => o.X), dMinY = ptls.Min(o => o.Y);

            string[] size = text.Split(new string[] { "mm", "*" }, StringSplitOptions.RemoveEmptyEntries);
            if (size.Length < 2) return;
            double sizelong, sizewidth;
            double.TryParse(size[0], out sizelong);
            double.TryParse(size[1], out sizewidth);
            Autodesk.AutoCAD.Geometry.Scale3d scale = new Autodesk.AutoCAD.Geometry.Scale3d(sizelong == 0 ? 1 : sizelong / (dMaxX - dMinX), sizewidth == 0 ? 1 : sizewidth / (dMaxY - dMinY), 1);
            entity.UpgradeOpen();
            entity.ScaleFactors = entity.ScaleFactors.PostMultiplyBy(scale);
            entity.DowngradeOpen();
        }
    [CommandMethod("DrawOrderTest")] //绘图层级次序
	static public void DrawOrderTest()
	{
	    Document doc = Application.DocumentManager.MdiActiveDocument;
	    Database db = doc.Database;
	
	    Editor ed = doc.Editor;
	    string message = "\nSelect a entity to move to bottom";
	    PromptEntityOptions options = new PromptEntityOptions(message);
	    PromptEntityResult acSSPrompt = ed.GetEntity(options);
	    if (acSSPrompt.Status != PromptStatus.OK)
	        return;
	    using (Transaction tr = db.TransactionManager.StartTransaction())
	    {
	        Entity ent = tr.GetObject(acSSPrompt.ObjectId,
	                                        OpenMode.ForRead) as Entity;
	        //get the block
	        BlockTableRecord block = tr.GetObject(ent.BlockId,
	                               OpenMode.ForRead) as BlockTableRecord;
	        //get the draw oder table of the block
	        DrawOrderTable drawOrder =
	                                 tr.GetObject(block.DrawOrderTableId,
	                                OpenMode.ForWrite) as DrawOrderTable;
	        ObjectIdCollection ids = new ObjectIdCollection();
	        ids.Add(acSSPrompt.ObjectId);
	        //move the selected entity so that entity is
	        //drawn in the beginning of the draw order.
	        drawOrder.MoveToBottom(ids);
	        tr.Commit();
	    }
}

文件操作

public static void NewDoc(string fileName)
        {
            if (File.Exists(fileName))
            {
                OpenDoc(fileName);
            }
            else
            {
                string strTemplatePath = "acadiso.dwt";
                DocumentCollection acDocMgr = Application.DocumentManager;
                Document acDoc = acDocMgr.Add(strTemplatePath);
                acDocMgr.MdiActiveDocument = acDoc;
                acDoc.Database.SaveAs(fileName, true, DwgVersion.Current, Doc.Database.SecurityParameters);
            }
        }
        public static void OpenDoc(string fileName)
        {
            DocumentCollection acDocMgr = Application.DocumentManager;
            foreach(Document doc in acDocMgr)
            {
                if (doc.Database.Filename == fileName)
                {//文件是否打开
                    acDocMgr.MdiActiveDocument = doc;
                    return;
                }
            }

            if (File.Exists(fileName))
                acDocMgr.Open(fileName, false);
            else
                PutMessage("File " + fileName + " does not exist.");
        }
        public static void SaveDoc(string fileName)
        {
            Doc.Database.SaveAs(fileName, true, DwgVersion.Current,Doc.Database.SecurityParameters);
        }

autocad命令

base命令(修改图块基点) THUMBSAVE 保存缩略图 解组 ungroup 导出图像后再导出块对象 pu(-pu)资源清理,减小dwg文件大小(最好先剪贴或者拷贝后操作) laydel 删除图层 XR外部参照管理 attmode 0属性文字不显示 pe选择多个直线转换多段线,x多段线转直线 cui 菜单管理 cuiload 菜单重加载(修改cui文件后需要调用cuiload卸载后加载刷新菜单栏)

菜单自定义

cui命令加载或者cuiload重新加载cuix文件 工具栏

//工具栏
                Toolbar fdTb = cs.MenuGroup.Toolbars.FindToolbarWithName("XXXX");
                if (fdTb != null)
                    fdTb.ToolbarItems.Clear();
                else
                    fdTb = new Toolbar("XXXX", cs.MenuGroup);

                ToolbarButton tlBtn1 = new ToolbarButton(mMar1.ElementID, "XXXX", fdTb, 0);
                ToolbarButton tlBtn2 = new ToolbarButton(mMar2.ElementID, "XXXX", fdTb, 0);
                ToolbarButton tlBtn3 = new ToolbarButton(mMar3.ElementID, "XXXXX", fdTb, 1);
                fdTb.ToolbarItems.Add(tlBtn1);
                fdTb.ToolbarItems.Add(tlBtn2);
                fdTb.ToolbarItems.Add(tlBtn3);
                fdTb.ToolbarVisible = ToolbarVisible.show;

菜单栏

PopMenu pmParent = cs.MenuGroup.PopMenus.FindPopWithName(customName);
                if (pmParent == null)
                    pmParent = new PopMenu(customName, new StringCollection() { "POP14" }, "PMU_191_D624B", cs.MenuGroup);
                //清除菜单
                pmParent.PopMenuItems.Clear();
                new PopMenuItem(new MenuMacro(maGroup, "xxx", "xxxxx", ""), "xxx", pmParent, -1);
                new PopMenuItem(new MenuMacro(maGroup, "xxxx", "xxxx", ""), "xxxx", pmParent, -1);
                new PopMenuItem(pmParent, 2);
                MenuMacro mMar1 = new MenuMacro(maGroup, "xxxx", "SWJX_ScaleModel", "");
                mMar1.macro.SmallImage = LoginInfo.instance().AppPath+ "/Resources/尺寸.bmp";
                new PopMenuItem(mMar1, "xxx", pmParent, -1);
                new PopMenuItem(new MenuMacro(maGroup, "xxxxx", "xxxxxx", ""), "xxxx", pmParent, -1);
                MenuMacro mMar2 = new MenuMacro(maGroup, "xxxxx", "xxxx", "");
                mMar2.macro.SmallImage = LoginInfo.instance().AppPath + "/Resources/xx.bmp";
                new PopMenuItem(mMar2, "xxxx", pmParent, -1);
                MenuMacro mMar3 = new MenuMacro(maGroup, "xxxxx", "xxxxxx", "");
                mMar3.macro.SmallImage = LoginInfo.instance().AppPath + "/Resources/x.bmp";
                new PopMenuItem(mMar3, "xxxxx", pmParent, -1);
#if DEBUG
                new PopMenuItem(new MenuMacro(maGroup, "xxxx", "xxxxxx", ""), "xxxx", pmParent, -1);
#endif
                new PopMenuItem(new MenuMacro(maGroup, "xxxxx", "xxxxx", ""), "xxxxxx", pmParent, -1);
#if DEBUG
                new PopMenuItem(pmParent, 9);
#else
                new PopMenuItem(pmParent, 8);
#endif
                new PopMenuItem(new MenuMacro(maGroup, "xxxxx", "xxxxx", ""), "xxxxx", pmParent, -1);
#if DEBUG
                new PopMenuItem(pmParent, 11);
#else
                new PopMenuItem(pmParent, 10);
#endif
                new PopMenuItem(new MenuMacro(maGroup, "xxxxx", "SWJX_InsertCamera", ""), "xxxxxx", pmParent, -1);
                cs.MenuGroup.PopMenus.Add(pmParent);

功能区、选项卡、面板

				RibbonTabSource myRibbonTab = null;
                foreach (RibbonTabSource ribTab in cs.MenuGroup.RibbonRoot.RibbonTabSources)
                {//选项卡
                ...
                }
				Autodesk.AutoCAD.Customization.RibbonPanelSource panelSrc3 = null;
                foreach (Autodesk.AutoCAD.Customization.RibbonPanelSource ribPanel in 			cs.MenuGroup.RibbonRoot.RibbonPanelSources)
                {//面板
                ...
                }

添加到工作区

//添加到工作区
                foreach (Workspace wk in cs.Workspaces)
                {
	                foreach(WorkspacePopMenu pm in wk.WorkspacePopMenus)
	                {//菜单
	                ...
	                }
	                if (!bFound)
                    {//找不到添加,使用cui命令检查cuix是否有多余的错误资源(影响绑定关系,最好每次调试清理一次)
                        wk.WorkspacePopMenus.Add(new WorkspacePopMenu(wk, pmParent) { Display = 1 });
                    }
	                foreach (WorkspaceToolbar tbl in wk.WorkspaceToolbars)
	                {//工具栏
	                ...
	                }
	                if (!bFound)
                    {//找不到添加,使用cui命令检查cuix是否有多余的错误资源(影响绑定关系,最好每次调试清理一次)
                        wk.WorkspaceToolbars.Add(new WorkspaceToolbar(wk, fdTb) { Display=1});
                    }
	                foreach (WSRibbonTabSourceReference pm in wk.WorkspaceRibbonRoot.WorkspaceTabs)
	                {//面板
	                }
	                if (!bFound)
                    {//找不到添加,使用cui命令检查cuix是否有多余的错误资源(影响绑定关系,最好每次调试清理一次)
    	wk.WorkspaceRibbonRoot.WorkspaceTabs.Add(WSRibbonTabSourceReference.Create(myRibbonTab));
                    }
                	...
               	}
                 if (cs.IsModified) cs.Save();
                 Application.ReloadAllMenus();

进度条

private static ProgressMeter s_Pmeter = new ProgressMeter();

动态修改数据

tr.Commit();//提交后修改绘制
tr.TransactionManager.QueueForGraphicsFlush();

cad颜色设置

  • 1-255 255中基本颜色
  • 0 表示 ByBlock
  • 256 表示 ByLayer

内存中绘图

int Width = 512,WallThickness = 60;
            Autodesk.AutoCAD.GraphicsSystem.Manager gsm = doc.GraphicsManager;
            using (Transaction tran = doc.Database.TransactionManager.StartTransaction())
            {
                ViewportTableRecord vTbRec = (ViewportTableRecord)tran.GetObject(doc.Editor.ActiveViewportId, OpenMode.ForRead);
                using (Autodesk.AutoCAD.GraphicsSystem.View view = new Autodesk.AutoCAD.GraphicsSystem.View())
                {
                    using (Autodesk.AutoCAD.GraphicsSystem.Device dev = gsm.CreateAutoCADOffScreenDevice())
                    {
                        dev.DeviceRenderType = Autodesk.AutoCAD.GraphicsSystem.RendererType.Default;
                        dev.BackgroundColor = System.Drawing.Color.Black;
                        dev.Add(view);
                        dev.Update();

                        using (Autodesk.AutoCAD.GraphicsSystem.Model model = gsm.CreateAutoCADModel())
                        {
                            view.VisualStyle = new Autodesk.AutoCAD.GraphicsInterface.VisualStyle(vst);
                            view.Mode = Autodesk.AutoCAD.GraphicsSystem.RenderMode.FlatShaded;
                            using (Transaction tr = doc.Database.TransactionManager.StartTransaction())
                            {
                                Point Max = new Point() { X = double.NaN, Y = double.NaN }, Min = new Point() { X= double.NaN,Y= double.NaN};
                                LayerTable layTbl = tr.GetObject(doc.Database.LayerTableId, OpenMode.ForRead) as LayerTable;
                                BlockTable bt = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                                foreach (ObjectId btId in bt)
                                {
                                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btId, OpenMode.ForRead);
                                    foreach (ObjectId btrId in btr)
                                    {
                                        BlockTableRecord modelSpace = tr.GetObject(btId, OpenMode.ForRead) as BlockTableRecord;
                                        //删除未被引用的块
                                        if (modelSpace.GetBlockReferenceIds(false, false).Count == 0 && !modelSpace.IsLayout)
                                            continue;

                                        DBObject obj = tr.GetObject(btrId, OpenMode.ForRead);
                                        if ((obj is Autodesk.AutoCAD.DatabaseServices.Line || obj is Polyline || obj is Polyline3d) 
                                            && (obj as Entity).Layer == LayerName.instance()[(int)LayerTag.Wall])
                                        {
                                            Entity entity = (obj as Entity);
                                            //entity.UpgradeOpen();
                                            //entity.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.White);
                                            //entity.DowngradeOpen();

                                            //获取数据的最大边界
                                            if (double.IsNaN(Max.X) || Max.X < entity.GeometricExtents.MaxPoint.X)
                                                Max.X = entity.GeometricExtents.MaxPoint.X;
                                            if (double.IsNaN(Min.X)|| Min.X > entity.GeometricExtents.MinPoint.X)
                                                Min.X = entity.GeometricExtents.MinPoint.X;
                                            if (double.IsNaN(Max.Y) || Max.Y < entity.GeometricExtents.MaxPoint.Y)
                                                Max.Y = entity.GeometricExtents.MaxPoint.Y;
                                            if (double.IsNaN(Min.Y) || Min.Y > entity.GeometricExtents.MinPoint.Y)
                                                Min.Y = entity.GeometricExtents.MinPoint.Y;
                                            //if (obj is Polyline && (obj as Polyline).ConstantWidth > WallThickness)
                                            //    WallThickness = (int)(obj as Polyline).ConstantWidth/2;
                                            view.Add(obj, model);
                                        }
                                    }
                                }
                                tr.Commit();
                                //Max.Z = Doc.Database.Extmax.Z;
                                //Min.Z = Doc.Database.Extmin.Z;
                                Max.X += WallThickness; Max.Y += WallThickness; Min.X -= WallThickness; Min.Y -= WallThickness;
                                if (double.IsNaN(Max.X) || double.IsNaN(Min.X) || double.IsNaN(Max.Y) || double.IsNaN(Min.Y))
                                {
                                    dev.OnSize(new System.Drawing.Size(Width, (int)(Width * (doc.Database.Extmax.Y - doc.Database.Extmin.Y) / (doc.Database.Extmax.X - doc.Database.Extmin.X))));
                                    view.ZoomExtents(doc.Database.Extmax, doc.Database.Extmin);
                                    view.SetView(vTbRec.Target, vTbRec.Target.Subtract(new Vector3d(0, 0, 1)), Vector3d.ZAxis, doc.Database.Extmax.X - doc.Database.Extmin.X, doc.Database.Extmax.Y - doc.Database.Extmin.Y);
                                    using (System.Drawing.Bitmap bitmap = view.GetSnapshot(new System.Drawing.Rectangle(0, 0, Width, (int)(Width * (doc.Database.Extmax.Y - doc.Database.Extmin.Y) / (doc.Database.Extmax.X - doc.Database.Extmin.X)))))
                                    {
                                        Bitmap2Png(bitmap).Save(filename);
                                        dev.Erase(view);
                                        view.EraseAll();
                                    }
                                }
                                else
                                {
                                    dev.OnSize(new System.Drawing.Size(Width, (int)(Width * (Max.Y - Min.Y) / (Max.X - Min.X))));
                                    view.ZoomExtents(Max.ToPoint3d(), Min.ToPoint3d());
                                    view.SetView(vTbRec.Target, vTbRec.Target.Subtract(new Vector3d(0, 0, 1)), Vector3d.ZAxis, Max.X - Min.X, Max.Y - Min.Y);
                                    using (System.Drawing.Bitmap bitmap = view.GetSnapshot(new System.Drawing.Rectangle(0, 0, Width, (int)(Width * (Max.Y - Min.Y) / (Max.X - Min.X)))))
                                    {
                                        Bitmap2Png(bitmap).Save(filename);
                                        dev.Erase(view);
                                        view.EraseAll();
                                    }
                                }
                            }
                        }
                    }
                }
            }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券