Beispiel #1
1
        /// <summary>关闭指定层
        /// 关闭指定层
        /// </summary>
        /// <param name="cm"></param>
        public void Off_Layer(string cm)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    LayerTable Layertable = (LayerTable)trans.GetObject(db.LayerTableId, ACDBOpenMode.ForWrite);
                    foreach (ObjectId layerid in Layertable)
                    {
                        LayerTableRecord LayertableRecord = (LayerTableRecord)trans.GetObject(layerid, ACDBOpenMode.ForWrite);//层记录表
                        if (LayertableRecord.Name == cm)
                        {
                            LayertableRecord.IsOff = true;
                        }
                    }
                }
                finally
                {
                    trans.Commit();
                    trans.Dispose();
                }
            }
        }
Beispiel #2
0
        public static void CreateLayer(string layer, Color color)
        {
            // Get the current document and database
            Document acDoc   = acApp.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Layer table for read
                LayerTable acLyrTbl;
                acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;

                if (acLyrTbl.Has(layer) == false)
                {
                    LayerTableRecord acLyrTblRec = new LayerTableRecord();

                    // Assign the layer the ACI color 1 and a name
                    //acLyrTblRec.Color = Color.FromColorIndex(ColorMethod.ByAci, layer.Value);
                    acLyrTblRec.Name  = layer;
                    acLyrTblRec.Color = color;

                    // Upgrade the Layer table for write
                    acLyrTbl.UpgradeOpen();

                    // Append the new layer to the Layer table and the transaction
                    acLyrTbl.Add(acLyrTblRec);
                    acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                }
                acTrans.Commit();
            }
            return;
        }
Beispiel #3
0
        /// <summary>
        /// 删除指定名称的图层
        /// </summary>
        /// <param name="db">数据库对象</param>
        /// <param name="layerName">图层名</param>
        /// <returns>如果删除成功,则返回true,否则返回false</returns>
        public static bool DeleteLayer(this Database db, string layerName)
        {
            //打开层表
            LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead);

            //如果层名为0或Defpoints,则返回(这两个图层不能删除)
            if (layerName == "0" || layerName == "Defpoints")
            {
                return(false);
            }
            //如果不存在名为layerName的图层,则返回
            if (!lt.Has(layerName))
            {
                return(false);
            }
            ObjectId layerId = lt[layerName];//获取名为layerName的层表记录的Id

            //如果要删除的图层为当前层,则返回(不能删除当前层)
            if (layerId == db.Clayer)
            {
                return(false);
            }
            //打开名为layerName的层表记录
            LayerTableRecord ltr = (LayerTableRecord)layerId.GetObject(OpenMode.ForRead);

            //如果要删除的图层包含对象或依赖外部参照,则返回(不能删除这些层)
            lt.GenerateUsageData();
            if (ltr.IsUsed)
            {
                return(false);
            }
            ltr.UpgradeOpen(); //切换层表记录为写的状态
            ltr.Erase(true);   //删除名为layerName的图层
            return(true);      //删除图层成功
        }
Beispiel #4
0
        private static void ChangeLayerToMavat(DBObject element, LayerTable layerTable)
        {
            XPathDocument  xml = new XPathDocument("../../ConvertTable.xml");
            XPathNavigator nav = xml.CreateNavigator();

            string curLay = (element as Entity).Layer;
            string toLay;

            if ((toLay = (string)nav.Evaluate($"string(Root/Layers/Layer[From = '{curLay}']/To)")) != "")
            {
                if (!layerTable.Has(toLay))
                {
                    using (Transaction trans = dataBase.TransactionManager.StartTransaction())
                    {
                        using (LayerTableRecord ltr = new LayerTableRecord())
                        {
                            ltr.Name = toLay;
                            layerTable.UpgradeOpen();
                            layerTable.Add(ltr);
                            trans.AddNewlyCreatedDBObject(ltr, true);
                        }

                        trans.Commit();
                    }
                }

                (element as Entity).UpgradeOpen();
                (element as Entity).Layer = toLay;
            }
        }
Beispiel #5
0
 public static void MyCreateLayer(this Database acdb, string layerName, short colorIndex, ColorMethod corlorMethod, bool needPrint)
 {
     using (Transaction trans = acdb.TransactionManager.StartTransaction())
     {
         LayerTable layerTable = trans.GetObject(acdb.LayerTableId, OpenMode.ForRead) as LayerTable;
         if (!layerTable.Has(layerName))
         {
             LayerTableRecord ltr = new LayerTableRecord()
             {
                 Name = layerName, Color = Color.FromColorIndex(corlorMethod, colorIndex)
             };
             ltr.IsPlottable = needPrint;
             layerTable.UpgradeOpen();
             layerTable.Add(ltr);
             trans.AddNewlyCreatedDBObject(ltr, true);
         }
         else
         {
             layerTable.UpgradeOpen();
             LayerTableRecord ltr = trans.GetObject(layerTable[layerName], OpenMode.ForWrite) as LayerTableRecord;
             ltr.Color       = Color.FromColorIndex(corlorMethod, colorIndex);
             ltr.IsPlottable = needPrint;
         }
         trans.Commit();
     }
 }
Beispiel #6
0
        //添加层
        public ObjectId AddLayer(Database db, string layerName)
        {
            ObjectId oId = ObjectId.Null;

            using (var trans = db.TransactionManager.StartTransaction())
            {
                var lyerTbl = db.LayerTableId.GetObject(OpenMode.ForWrite) as LayerTable;

                if (lyerTbl.Has(layerName))
                {
                    trans.Commit();
                    return(lyerTbl[layerName]);
                }
                var lyerTblRec = new LayerTableRecord();
                lyerTblRec.Name = layerName;

                lyerTbl.Add(lyerTblRec);
                trans.AddNewlyCreatedDBObject(lyerTblRec, true);

                lyerTbl.DowngradeOpen();

                trans.Commit();

                return(lyerTbl[layerName]);
            }
        }
Beispiel #7
0
        public ObjectId CreateLayer()
        {
            ObjectId layerId = ObjectId.Null;

            var db = HostApplicationServices.WorkingDatabase;

            using (var trans = db.TransactionManager.StartTransaction())
            {
                var lt = trans.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;
                if (lt.Has("EmployeeLayer"))
                {
                    layerId = lt["EmployeeLayer"];
                }
                else
                {
                    var ltr = new LayerTableRecord();
                    ltr.Name  = "EmployeeLayer";
                    ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 2);
                    layerId   = lt.Add(ltr);
                    trans.AddNewlyCreatedDBObject(ltr, true);
                }

                trans.Commit();
            }

            return(layerId);
        }
Beispiel #8
0
        public void Refresh()
        {
            //Datenbank
            Database db = HostApplicationServices.WorkingDatabase;

            if (db != null)
            {
                Transaction myT = db.TransactionManager.StartTransaction();

                using (DocumentLock dl = _AcAp.Application.DocumentManager.MdiActiveDocument.LockDocument())
                {
                    LayerTable layT = (LayerTable)myT.GetObject(db.LayerTableId, OpenMode.ForRead);
                    m_lsLayerTableRecord.Clear();

                    //Layernamen in Liste schreiben
                    foreach (ObjectId id in layT)
                    {
                        LayerTableRecord ltr = (LayerTableRecord)(myT.GetObject(id, OpenMode.ForRead));

                        m_lsLayerTableRecord.Add(ltr);
                    }
                }

                myT.Commit();
                myT.Dispose();
            }
        }
Beispiel #9
0
        /// <summary>
        /// Определяет видны ли объекты на слое, указанном его ObjectId и принадлежность "не нужным" слоям.
        /// </summary>
        /// <param name="layerId">ObjectId слоя.</param>
        /// <returns></returns>
        bool IsLayerOn(ObjectId layerId)
        {
            List <string> listLayer = new List <string>()
            {
                "Осевая",
                "Осевая линия(ГОСТ)",
                "i_Осевые линии",
                "i_Отверстия",
                "i_Резьбы",
                "i_Шильд",
                "Зона сверления"
            };

            using (LayerTableRecord ltr = layerId.Open(OpenMode.ForRead) as LayerTableRecord)
            {
                if (ltr.IsFrozen)
                {
                    return(false);
                }
                if (ltr.IsOff)
                {
                    return(false);
                }
                if (ltr.Name == "Defpoints")
                {
                    return(false);
                }
                if (listLayer.BinarySearch(ltr.Name) >= 0)
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #10
0
        // Returns the id of the layer (Creates the layer if it does not exist)
        public static ObjectId GetOrCreateLayer(Database db, string layerName, Autodesk.AutoCAD.Colors.Color color)
        {
            ObjectId id = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayerTable table = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                if (table.Has(layerName))
                {
                    id = table[layerName];
                }
                else
                {
                    LayerTableRecord layer = new LayerTableRecord();
                    layer.Name = layerName;
                    if (color != null)
                    {
                        layer.Color = color;
                    }

                    table.UpgradeOpen();
                    id = table.Add(layer);
                    table.DowngradeOpen();
                    tr.AddNewlyCreatedDBObject(layer, true);
                }

                tr.Commit();
            }

            return(id);
        }
Beispiel #11
0
        public void Run()
        {
            //Создаем документ и привязываем его к активному окну
            Document doc = Application.DocumentManager.MdiActiveDocument;
            // Cоздаем ссылку на базу данных
            Database db = doc.Database;
            //Создаем ссылку на таблицу слоев
            ObjectId Layers = db.LayerTableId;

            List <string> LayerList = new List <string>();

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayerTable layertable = tr.GetObject(Layers, OpenMode.ForRead) as LayerTable;
                foreach (ObjectId item in layertable)
                {
                    LayerTableRecord layerTableRecord = tr.GetObject(item, OpenMode.ForRead) as LayerTableRecord;
                    LayerList.Add(layerTableRecord.Name);
                }
                //обращаемся к командной строке
                Editor edit = doc.Editor;

                foreach (var item in LayerList)
                {
                    edit.WriteMessage("\n{0}", item);
                }
                tr.Commit();
            }
        }
Beispiel #12
0
        public void ERZ()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            PromptSelectionOptions pso = new PromptSelectionOptions
            {
                MessageForAdding = "\nADT——冻结图层:\n选取图元以冻结其所在的图层"
            };
            PromptSelectionResult psr = ed.GetSelection(pso);

            if (psr.Status == PromptStatus.OK)
            {
                SelectionSet ss = psr.Value;
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead);
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        Entity           ent = (Entity)trans.GetObject(id, OpenMode.ForRead);
                        LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(lt[ent.Layer], OpenMode.ForWrite);
                        if (!ltr.IsFrozen)
                        {
                            ltr.IsLocked = false;
                        }
                    }
                    trans.Commit();
                }
            }
        }
Beispiel #13
0
        public void ERV()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            ed.WriteMessage("\n百福工具箱——打开全部图层");
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead);
                foreach (ObjectId id in lt)
                {
                    LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(id, OpenMode.ForWrite);
                    if (ltr.IsOff)
                    {
                        ltr.IsOff = false;
                    }
                    else
                    {
                        ltr.IsOff = true;
                    }
                }
                trans.Commit();
            }
        }
Beispiel #14
0
        //Konstruktor (damit kein Default Konstruktor generiert wird!)
        protected MyLayer()
        {
            //Datenbank
            try {
                _AcDb.Database    db  = _AcDb.HostApplicationServices.WorkingDatabase;
                _AcDb.Transaction myT = db.TransactionManager.StartTransaction();

                using (DocumentLock dl = _AcAp.Application.DocumentManager.MdiActiveDocument.LockDocument())
                {
                    _AcDb.LayerTable layT = (_AcDb.LayerTable)myT.GetObject(db.LayerTableId, OpenMode.ForRead);

                    //Layernamen in Liste schreiben
                    foreach (ObjectId id in layT)
                    {
                        LayerTableRecord ltr = (LayerTableRecord)(myT.GetObject(id, OpenMode.ForRead));

                        m_lsLayerTableRecord.Add(ltr);
                    }
                }

                myT.Commit();
                myT.Dispose();
            }
            catch { }
        }
Beispiel #15
0
        public static bool CreateLayer(Document doc, string layerName, Color layerColor)
        {
            bool isLayerCreated = false;
            Database acCurDb = doc.Database;
            Editor ed = doc.Editor;

            using (Transaction trans = acCurDb.TransactionManager.StartTransaction())
                {
                    LayerTable layTb = (LayerTable)trans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead);
                    if (layTb.Has(layerName) == false)
                    {
                        using (LayerTableRecord layTbRec = new LayerTableRecord())
                        {
                            layTbRec.Color = layerColor;
                            layTbRec.Name = layerName;
                            layTb.UpgradeOpen();
                            layTb.Add(layTbRec);
                            trans.AddNewlyCreatedDBObject(layTbRec, true);
                            trans.Commit();
                            isLayerCreated = true;
                        }
                    }
                }

            return isLayerCreated;
        }
Beispiel #16
0
        //Methoden
        //neuen Layer anlegen
        public int Add(string Name)
        {
            //Datenbank
            int         isLayerCreated = 0;
            Database    db             = HostApplicationServices.WorkingDatabase;
            Transaction myT            = db.TransactionManager.StartTransaction();

            using (DocumentLock dl = _AcAp.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                LayerTable layT = (LayerTable)myT.GetObject(db.LayerTableId, OpenMode.ForWrite);

                if (!layT.Has(Name))
                {
                    LayerTableRecord layTR = new LayerTableRecord()
                    {
                        Name = Name
                    };

                    layT.Add(layTR);
                    m_lsLayerTableRecord.Add(layTR);
                    myT.AddNewlyCreatedDBObject(layTR, true);
                    isLayerCreated = 1;
                }
            }
            myT.Commit();
            myT.Dispose();

            return(isLayerCreated);
        }
Beispiel #17
0
        public void CreateLayer(string layer)
        {
            Database    workingDatabase = HostApplicationServices.WorkingDatabase;
            Transaction transaction     = workingDatabase.TransactionManager.StartTransaction();

            try
            {
                LayerTable layerTable = (LayerTable)transaction.GetObject(workingDatabase.LayerTableId, OpenMode.ForWrite);
                if (layerTable.Has(layer))
                {
                    ObjectId objectId = layerTable[layer];
                }
                else
                {
                    LayerTableRecord layerTableRecord = new LayerTableRecord();
                    layerTableRecord.Name = (layer);
                    ObjectId objectId = layerTable.Add(layerTableRecord);
                    transaction.AddNewlyCreatedDBObject(layerTableRecord, true);
                }
                transaction.Commit();
            }
            catch
            {
                transaction.Abort();
            }
            finally
            {
                transaction.Dispose();
            }
        }
Beispiel #18
0
        public void ERN()
        {
            Document            doc = Application.DocumentManager.MdiActiveDocument;
            Database            db  = doc.Database;
            Editor              ed  = doc.Editor;
            PromptStringOptions pso = new PromptStringOptions("\nADT——新建图层\n请输入新图层名称")
            {
                AllowSpaces = true
            };
            PromptResult pr = ed.GetString(pso);

            if (pr.Status == PromptStatus.OK)
            {
                string layname = pr.StringResult;

                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite);
                    if (!lt.Has(layname))
                    {
                        LayerTableRecord ltr = new LayerTableRecord
                        {
                            Name = layname
                        };
                        lt.Add(ltr);
                        trans.AddNewlyCreatedDBObject(ltr, true);
                        trans.Commit();
                    }
                }
            }
        }
Beispiel #19
0
        public static void CreateLayersForPluginTool(Document document)
        {
            var database = document.Database;

            if (!CheckAvailabilityLayers(document))
            {
                using (var documentlock = document.LockDocument())
                {
                    using (var transaction = database.TransactionManager.StartTransaction())
                    {
                        ObjectId plugin_layer;

                        var layerTable = transaction.GetObject(database.LayerTableId, OpenMode.ForWrite) as LayerTable;

                        var layerTableRecord = new LayerTableRecord();

                        layerTableRecord.Name = "selection_converter";

                        plugin_layer = layerTable.Add(layerTableRecord);

                        transaction.AddNewlyCreatedDBObject(layerTableRecord, true);

                        transaction.Commit();
                    }
                }
            }
        }
Beispiel #20
0
        public static ObjectId GetOrCreateLayerByName(Database db, string layerName)
        {
            if (db == null)
            {
                throw new ArgumentNullException(/*MSG0*/ "db");
            }
            if (string.IsNullOrEmpty(layerName))
            {
                throw new ArgumentNullException(/*MSG0*/ "layerName");
            }

            ObjectId newLayerId;

            using (Transaction transaction = db.TransactionManager.StartTransaction())
            {
                //Get layer table from database.
                var layerTable = (LayerTable)transaction.GetObject(db.LayerTableId, OpenMode.ForWrite);
                //Check if the layerName is exist. If exist, just return the name for it; else, add the new layer to layer table.
                if (!layerTable.Has(layerName))
                {
                    LayerTableRecord layerTableRecord = new LayerTableRecord();
                    layerTableRecord.Name = layerName;
                    layerTable.UpgradeOpen();
                    newLayerId = layerTable.Add(layerTableRecord);
                    transaction.AddNewlyCreatedDBObject(layerTableRecord, true);
                }
                else
                {
                    newLayerId = layerTable[layerName];
                }
                transaction.Commit();
            }

            return(newLayerId);
        }
Beispiel #21
0
        public void ERC()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptSelectionResult psr = ed.GetSelection();
            SelectionSet          ss  = psr.Value;

            if (psr.Status != PromptStatus.OK)
            {
                return;
            }
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //获取当前层的块表记录
                LayerTableRecord ltr = (LayerTableRecord)db.Clayer.GetObject(OpenMode.ForRead);
                //循环选择集
                foreach (ObjectId id in ss.GetObjectIds())
                {
                    Entity ent = (Entity)trans.GetObject(id, OpenMode.ForWrite);
                    ent.Layer = ltr.Name;
                    ent.DowngradeOpen();
                }
                trans.Commit();
            }
        }
Beispiel #22
0
        public static void PrintAllLayer()
        {
            using (PrintFrm pfrom = new PrintFrm())
            {
                pfrom.ShowInTaskbar = false;
                Application.ShowModalDialog(pfrom);
                if (pfrom.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    Document acDoc   = Application.DocumentManager.MdiActiveDocument;
                    Database acCurDb = acDoc.Database;
                    Editor   ed      = acDoc.Editor;
                    string   docName = acDoc.Name;
                    docName = docName.Remove(docName.Length - 5);
                    List <string> outputFileList = new List <string>();
                    string        outputPath     = "D:\\Tmp\\";
                    string        printDevice    = "DWF6 ePlot.pc3";
                    string        mediaDevice    = "ANSI_A_(8.50_x_11.00_Inches)";

                    Transaction acTrans = acCurDb.TransactionManager.StartTransaction();
                    // 获取图层
                    LayerTable acLyrTbl;
                    acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                    List <string> sLayerNames = new List <string>();

                    // 获取图层列表
                    foreach (ObjectId acObjId in acLyrTbl)
                    {
                        LayerTableRecord acLyrTblRec;
                        acLyrTblRec = acTrans.GetObject(acObjId, OpenMode.ForWrite) as LayerTableRecord;
                        sLayerNames.Add(acLyrTblRec.Name);
                        //outputFileList.Add(String.Concat(docName, acLyrTblRec.Name));
                        outputFileList.Add(acLyrTblRec.Name);
                        acLyrTblRec.IsOff = true;
                    }

                    for (int i = 0; i < sLayerNames.Count; i++)
                    {
                        string layerName      = sLayerNames[i].ToString();
                        string outputFileName = outputFileList[i].ToString();
                        PlotCurrentLayout(layerName, outputFileName, outputPath, printDevice, mediaDevice);

                        while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                        {
                            ed.WriteMessage("Be Printing, Please Wait.\n");
                        }
                    }
                    ed.WriteMessage("文档打印完成。\n");

                    // 将活动图层修改为第一个,即图层0
                    acCurDb.Clayer = acLyrTbl["0"];
                    LayerTableRecord acLayerTblRec = acTrans.GetObject(acLyrTbl["0"], OpenMode.ForWrite) as LayerTableRecord;
                    acLayerTblRec.IsOff = false; //显示该图层
                }
                else
                {
                    Application.ShowAlertDialog("您已经选择了放弃打印!");
                }
            }
        }
Beispiel #23
0
        public void IsolateLayer()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // Collection of selected entities
            ObjectIdCollection ids = new ObjectIdCollection();

            // The results object for nested selection
            PromptNestedEntityResult rs;

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                // Loop until cancelled or completed
                do
                {
                    rs = ed.GetNestedEntity("\nSelect nested entity: ");
                    if (rs.Status == PromptStatus.OK)
                    {
                        ids.Add(rs.ObjectId);
                        HighlightSubEntity(doc, rs);
                    }
                }while (rs.Status == PromptStatus.OK);

                if (ids.Count > 0)
                {
                    LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    for (int i = 0; i < ids.Count; i++)
                    {
                        // Selected drawing object
                        Entity ent = tr.GetObject(ids[i], OpenMode.ForRead) as Entity;

                        // LayerTableRecord for each selected entity
                        LayerTableRecord ltr = tr.GetObject(lt[ent.Layer], OpenMode.ForRead) as LayerTableRecord;

                        db.Clayer = lt[ltr.Name];

                        LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                        foreach (ObjectId id in layerTable)
                        {
                            LayerTableRecord layerTableRecord = (LayerTableRecord)tr.GetObject(id, OpenMode.ForWrite);

                            if (layerTableRecord.Name != ltr.Name && layerTableRecord.Name != "0")
                            {
                                layerTableRecord.IsFrozen = true;
                            }
                        }
                    }
                    tr.Commit();

                    // Regen clears highlighting and reflects the new layer
                    ed.Regen();
                }
            }
        }
Beispiel #24
0
        public static void RedrawCoating()
        {
            using (Transaction Tr = _db.TransactionManager.StartTransaction())
            {
                LayerTable LayerTable = Tr.GetObject(_db.LayerTableId, OpenMode.ForRead) as LayerTable;
                foreach (Entity Ent in _entityTemp)
                {
                    Entity e = (Entity)Tr.GetObject(Ent.ObjectId, OpenMode.ForWrite);
                    try
                    {
                        if (_sheetDescriptionForm.GetCoatingLayer().Contains("Current") && _sheetDescriptionForm.GetCoatingLayer().Contains("Layer"))
                        {
                            throw new ArgumentNullException();
                        }
                        Ent.Layer = _sheetDescriptionForm.GetCoatingLayer();
                    }
                    catch
                    {
                        LayerTableRecord acLyrTblRec = Tr.GetObject(_db.Clayer, OpenMode.ForWrite) as LayerTableRecord;
                        Ent.Layer = acLyrTblRec.Name;
                    }
                    try
                    {
                        //MessageBox.Show("U2d Dim color =" + color.Name);
                        if (_sheetDescriptionForm.GetCoatingColor().Name.Contains("ByL"))
                        {
                            throw new ArgumentNullException();
                        }
                        Ent.Color = Color.FromColor(_sheetDescriptionForm.GetCoatingColor());
                    }
                    catch
                    {
                        // LayerTableRecord acLyrTblRec = acTrans.GetObject(Db.Clayer, OpenMode.ForWrite) as LayerTableRecord;
                        // acRotDim.Color = acLyrTblRec.Color;
                        try
                        {
                            if (_sheetDescriptionForm.GetCoatingLayer().Contains("Current") && _sheetDescriptionForm.GetCoatingLayer().Contains("Layer"))
                            {
                                throw new ArgumentNullException();
                            }
                            LayerTableRecord acLyrTblRec = Tr.GetObject(LayerTable[_sheetDescriptionForm.GetCoatingLayer()], OpenMode.ForWrite) as LayerTableRecord;
                            Ent.Color = acLyrTblRec.Color;
                        }
                        catch
                        {
                            LayerTableRecord acLyrTblRec = Tr.GetObject(_db.Clayer, OpenMode.ForWrite) as LayerTableRecord;
                            Ent.Color = acLyrTblRec.Color;
                        }

                        // acBlkTblRec.AppendEntity(t);
                        // acTrans.AddNewlyCreatedDBObject(t, true);
                    }
                }

                Tr.Commit();
            }
            _ed.Regen();
        }
Beispiel #25
0
        public void Tutorial_5_Layer_control()
        {
            CivilDocument doc       = CivilApplication.ActiveDocument;
            Document      MdiActdoc = Application.DocumentManager.MdiActiveDocument;
            Editor        editor    = MdiActdoc.Editor;
            Database      currentDB = MdiActdoc.Database;

            using (Transaction trans = HostApplicationServices.WorkingDatabase.TransactionManager.StartOpenCloseTransaction())
            {
                BlockTable       blockTab      = trans.GetObject(currentDB.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord modelSpaceBTR = trans.GetObject(blockTab[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                //We will still use same code as in Tutorial 3. You might noticed that the line is always created at current layer when you use Tut3 command.
                //Can we change the layer it goes? Of course.
                //If you type in myline and a dot (myline.), you will see there is a LayerId parameter. We can change the layer of Line by changing its layerId.
                //But it's asking for a layerId while what you only know is the layer name. How to get the corresponding layerId from a name?
                //Let's try to find layer "AAA"



                LayerTable layerTab = trans.GetObject(currentDB.LayerTableId, OpenMode.ForWrite) as LayerTable;       //Each layer is an instance of LayerTableRecord
                                                                                                                      //all LayerTableRecord in current drawing are stored in LayerTable


                ObjectId AAA_layerId = ObjectId.Null;                       //Declare a null instance of ObjectId to store the layerId we need.


                if (layerTab.Has("AAA") == true)                            //try to find if layer "AAA" exist already. "AAA" here is called a key, Table works like a dictionary.
                {
                    AAA_layerId = layerTab["AAA"];                          //layerTab["AAA"] returns the ObjectId of layer AAA
                }

                else                                                        //"AAA" doesn't exist, we need to create "AAA".
                {
                    LayerTableRecord myLayer = new LayerTableRecord();      //Create a new instance of LayerTableRecord .  "myLayer" is not Layer Name
                    myLayer.Name = "AAA";                                   //this is Layer Name. Type myLayer. to access more properties of layer.

                    layerTab.Add(myLayer);                                  //Add the new layer to layerTable
                    trans.AddNewlyCreatedDBObject(myLayer, true);           //Add the new layer to transaction. No need to add to modelSpace.

                    AAA_layerId = myLayer.ObjectId;
                }

                //************* Copy section above everytime you want to do something with layer. ************


                Point3d startPt = new Point3d(0, 0, 0);
                Point3d endPt   = new Point3d(5, 5, 5);

                Line myline = new Line(startPt, endPt);
                myline.LayerId = AAA_layerId;                                   //now you can set the layerId

                modelSpaceBTR.AppendEntity(myline);
                trans.AddNewlyCreatedDBObject(myline, true);

                trans.Commit();
            }
        }
Beispiel #26
0
        public static void RegisterLayer(this Database currentDatabase, string layerId, short colorIndex = 7,
                                         string linetype = "CONTINUOUS")
        {
            if (currentDatabase == null)
            {
                throw new ArgumentNullException(nameof(currentDatabase));
            }

            // Start a transaction
            Transaction acTrans = currentDatabase.TransactionManager.TopTransaction;

            // Open the Layer table for read
            LayerTable acLyrTbl = acTrans.GetObject(currentDatabase.LayerTableId, OpenMode.ForRead) as LayerTable;

            if (acLyrTbl is null)
            {
                throw new NullReferenceException("Layer table dictionary not retrieved");
            }

            //Return if layer exists
            if (acLyrTbl.Has(layerId))
            {
                return;
            }

            using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
            {
                // Assign the layer the ACI color 3 and a name
                acLyrTblRec.Color = Color.FromColorIndex(ColorMethod.ByAci, colorIndex);
                acLyrTblRec.Name  = layerId;

                LinetypeTable acLinTbl = acTrans.GetObject(currentDatabase.LinetypeTableId, OpenMode.ForRead) as LinetypeTable;

                if (acLinTbl is null)
                {
                    throw new NullReferenceException("Linetype dictionary not retrieved");
                }

                if (acLinTbl.Has(linetype))
                {
                    // Set the linetype for the layer
                    acLyrTblRec.LinetypeObjectId = acLinTbl[linetype];
                }
                else
                {
                    throw new ArgumentOutOfRangeException("Linetype does not exist", new Exception());
                }

                // Upgrade the Layer table for write
                acLyrTbl.UpgradeOpen();

                // Append the new layer to the Layer table and the transaction
                acLyrTbl.Add(acLyrTblRec);
                acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
            }
        }
Beispiel #27
0
        public static List <Triangle> ToCeometricCADDataTriangleList(ObjectId[] faceIDs)
        {
            Database        workingDatabase = HostApplicationServices.WorkingDatabase;
            List <Triangle> list            = new List <Triangle>();

            using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
            {
                string     blockModelSpaceName = SymbolUtilityServices.BlockModelSpaceName;
                LayerTable arg_30_0            = (LayerTable)transaction.GetObject(workingDatabase.LayerTableId, (OpenMode)0);
                for (int i = 0; i < faceIDs.Length; i++)
                {
                    Autodesk.AutoCAD.DatabaseServices.Face face = (Autodesk.AutoCAD.DatabaseServices.Face)transaction.GetObject(faceIDs[i], (OpenMode)0, true);
                    LayerTableRecord layerTableRecord           = (LayerTableRecord)transaction.GetObject(face.LayerId, (OpenMode)0);
                    Autodesk.AutoCAD.Colors.Color color         = face.Color;
                    if (color.IsByLayer)
                    {
                        color = layerTableRecord.Color;
                    }
                    System.Drawing.Color empty = System.Drawing.Color.Empty;
                    short colorIndex           = 256;
                    Conversions.GetColors(color, ref empty, ref colorIndex);
                    CADData cADData = new CADData();
                    cADData.Layer.Name = layerTableRecord.Name;
                    cADData.Color      = empty;
                    cADData.ColorIndex = colorIndex;
                    cADData.BlockName  = blockModelSpaceName;
                    Point3d vertexAt  = face.GetVertexAt(0);
                    Point3d vertexAt2 = face.GetVertexAt(1);
                    Point3d vertexAt3 = face.GetVertexAt(2);
                    Point3d vertexAt4 = face.GetVertexAt(3);
                    ngeometry.VectorGeometry.Point point  = new ngeometry.VectorGeometry.Point(vertexAt.X, vertexAt.Y, vertexAt.Z);
                    ngeometry.VectorGeometry.Point point2 = new ngeometry.VectorGeometry.Point(vertexAt2.X, vertexAt2.Y, vertexAt2.Z);
                    ngeometry.VectorGeometry.Point point3 = new ngeometry.VectorGeometry.Point(vertexAt3.X, vertexAt3.Y, vertexAt3.Z);
                    ngeometry.VectorGeometry.Point point4 = new ngeometry.VectorGeometry.Point(vertexAt4.X, vertexAt4.Y, vertexAt4.Z);
                    if (point != point2 && point != point3 && point != point4 && point2 != point3 && point2 != point4 && point3 != point4)
                    {
                        list.Add(new Triangle(point, point2, point4, false)
                        {
                            CADData = cADData
                        });
                        list.Add(new Triangle(point2, point3, point4, false)
                        {
                            CADData = cADData
                        });
                    }
                    else
                    {
                        list.Add(new Triangle(point, point2, point3, false)
                        {
                            CADData = cADData
                        });
                    }
                }
            }
            return(list);
        }
Beispiel #28
0
        public void warstwa()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = Application.DocumentManager.MdiActiveDocument.Editor;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable       tb     = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord record = trans.GetObject(tb[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                LayerTable       laytb  = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                LayerTableRecord layrec = new LayerTableRecord();

                string cNazwa = "LINIA";

                if (laytb.Has(cNazwa) == false)
                {
                    layrec.Color = Color.FromRgb(255, 0, 0);
                    layrec.Name  = cNazwa;
                    laytb.UpgradeOpen();
                    laytb.Add(layrec);
                    trans.AddNewlyCreatedDBObject(layrec, true);
                }
                else
                {
                    Application.ShowAlertDialog("Warstwa już istnieje.");
                }
                trans.Commit();
            }

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable       tb     = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord record = trans.GetObject(tb[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                LayerTable       laytb  = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                LayerTableRecord layrec = new LayerTableRecord();

                string cNazwa = "OKRAG";

                if (laytb.Has(cNazwa) == false)
                {
                    layrec.Color = Color.FromRgb(0, 255, 0);
                    layrec.Name  = cNazwa;
                    laytb.UpgradeOpen();
                    laytb.Add(layrec);
                    trans.AddNewlyCreatedDBObject(layrec, true);
                }
                else
                {
                    Application.ShowAlertDialog("Warstwa już istnieje.");
                }
                trans.Commit();
            }
        }
Beispiel #29
0
        public static void UnlockLayer(this Document doc, LayerTableRecord layer)
        {
            var db = doc.Database;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                layer.IsLocked = false;
                tr.Commit();
            }
        }
Beispiel #30
0
        private static LayerTableRecord GetCurrentLayer(Database db)
        {
            LayerTableRecord layer = new LayerTableRecord();

            using (Transaction transaction = db.TransactionManager.StartTransaction())
            {
                layer = transaction.GetObject(db.Clayer, OpenMode.ForRead) as LayerTableRecord;
            }
            return(layer);
        }
Beispiel #31
0
        /// <summary>
        /// Adds the given entities to this layer.
        /// </summary>
        /// <param name="layer">The layer instance.</param>
        /// <param name="entities">The entities to add.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when parameter <i>entities</i> is null.</exception>
        /// <exception cref="System.Exception">Thrown when adding an entity throws an exception.</exception>
        public static void AddRange(this LayerTableRecord layer, IEnumerable <Entity> entities)
        {
            Require.ParameterNotNull(layer, nameof(layer));
            Require.ParameterNotNull(entities, nameof(entities));

            foreach (var entity in entities)
            {
                AddInternal(layer, entity);
            }
        }
Beispiel #32
0
 private LayerTableRecord GetLayer(string layerName, LayerType fx, bool isPlottable, Transaction trans)
 {
     LayerTableRecord ltr = new LayerTableRecord();
     ltr.Name = layerName;
     Color color = GetLayerColor(fx);
     ltr.Color = color;
     LinetypeTable ltt = trans.GetObject(db.LinetypeTableId, OpenMode.ForRead) as LinetypeTable;
     ltr.LinetypeObjectId = ltt["Continuous"];
     ltr.IsPlottable = isPlottable;
     return ltr;
 }
Beispiel #33
0
        public static void addMyLayer()
        {
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) {
                LayerTable acLyrTbl;
                acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;

                if (acLyrTbl.Has("MyLayer") != true) {
                    acLyrTbl.UpgradeOpen();

                    LayerTableRecord acLyrTblRec = new LayerTableRecord();
                    acLyrTblRec.Name = "MyLayer";

                    acLyrTbl.Add(acLyrTblRec);
                    acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);

                    acTrans.Commit();
                }
                acTrans.Dispose();
            }
        }
Beispiel #34
0
 /// <summary>
 /// Установка свойст LayerInfo к слою LayerTableRecord
 /// </summary>
 /// <param name="lay"></param>
 public void SetProp(LayerTableRecord lay, Database db)
 {
     lay.Name = Name;
     lay.Color = Color;
     lay.IsFrozen = IsFrozen;
     lay.IsLocked = IsLocked;
     lay.IsOff = IsOff;
     lay.IsPlottable = IsPlotable;
     lay.LineWeight = LineWeight;
     if (!LinetypeObjectId.IsNull)
         lay.LinetypeObjectId = LinetypeObjectId;
     else if (!string.IsNullOrEmpty(LineType))
     {
         lay.LinetypeObjectId = db.GetLineTypeIdByName(LineType);
     }
     else
     {
         lay.LinetypeObjectId = db.GetLineTypeIdContinuous();
     }
 }
        // GetSSFilter – copy this code: creates a SS
        // GetSS Out: SS; In: SelectionFilter (AssumeWorks)
        // GetSS Out: SS; In: SelectionFilter, PromptSelectionOptions
        // GetAllIDsFromSS Out: all Ids of objects in SS (ObjctIDCollection); In: SS
        // GetAV Out: Attribute value;  In: BlockReferenceID, attributeName  (WORKS)
        // GetAV Out: attribute Value, In: BlockReferenceID, attributeIndex   (WORKS)
        // GetAV out: attribute value, In BlockName, attributeName
        // GetAV out: attribute value, In: blockName, attributeName, bool showError?
        // GetAT (get attribute tag): out: attributeTag (string); In: BRid, attributeIndex
        // GetBRids Out: ObjectIDCollectionReferenceIDs; In: BlockName    (ModelSpaceVersion)
        // GetBrId      Out: BlockId, In: BlockName
        // Works: Tested!
        // GetBRids Out: ObjectIDCollectionReferenceIDs; In: BlockName, selectionset (SsetVersion)
        // Works: Tested!
        // GetAVsandBRidsFromBRids Out:  Dictionary(RefIDs, attributeValues); In (BrefIds, attributename, blockname)
        // GetAVsandBRidsFromMS Out: Dictionary(RefIDs, attributeValues); In (attributeName, blockName) --- ModelSpaceVersion Works: Tested!
        // GetAVsandBRidsFromSS Out: Dictionary(RefIDs, attributeValues); In (selectionSet, attributename, blockname) – selectionSetVersion  Works: Tested!
        // WriteAVtoBlock Out: void; In: BlockRefID, attributeName (i.e. Tag), New attribute Value
        // SetAVs Out: void In: attributetag/attributeName, attributeValue, blockname - changes the attribute values of all blocks for a particular tag
        // SetAV Out: void; In: ObjectID, attributetag/attributeName, attributeValue
        // SetAV Out: void; In: ObjectID, attributetagIndex (int), attributeValue (string)
        // AreObjectsInPaperSpace returns bool - depending on whether there are objects in the paper space.
        // GetInsertionPointOfBlockReference -- the blockReference numbers that go in - must actually exist. Out: Point3d, In: blockRefID,
        // GetInsertionPoint Out: Point3d, In: blockRefID, attributeName
        // GetInsertionPoints Out: List<Point3d>, In: blockRefIDs (collection), attributeName
        // TESTING WHERE POINTS LOCATED
        // TestDrawLine  In: Line Out: void (draws lines in ModelSpace)
        // TestDrawCircle In: centre Out: void (draws a circle in the ModelSpace)
        // Working with TEXT and Grids (from Left to Right (or bottom to top?)):
        //              (A) ORDEROBJECTS put in a selection set and whether the objects are ordered left to right or
        //              or bottom to top (true if horizontal) and you'll get out a List of
        //              the x/y coordinates (depending on what the true false (horizontal/vertical)
        //              boolean is) as well as the actual length of the dimension (integer):
        //              Out: SortedList<double, int> In: SelectionSet, bool rightToLeft? true if horizontal (or bottom to top)?
        //              (B) GetTextPosition; In: SelectionSet, Out: List<Point3d> (selection set objects must be either DBtext or Mtext)
        //                  differencesInPositions: In: Dictionary<ObjectId, DBText>, bool (rightToLeft?); OUT: List<int> --> The distance between lines (which are located in the DBText value of the dictionary, are not put in an integer List).
        // GetFolderPath: Out: String(path of a folder), in: void (gets the path to a folder. if no path is successfully selected then the "MyDocuments" folder is returned"
        // Need to write the following:
        // Need to write this: Set AV given blockname and attribute tag.
        // GetPoint; In: String(instructions), Out: Point3d ***Double check to see if Point is not (0,0,0)
        // ReturnOtherEndOfLine In: Point3d, rawLine, Out: Point3d (other end of line)
        // IsPointInPolygon In: List<Point3d> polygon, Point3d point, Out: true/false
        // GetHandle In: BlockReferenceID; Out: handle
        // GetxOrYOffset In: Point3dOrigin, Point3dOffsetPoint, bool offsettingXvalues, Out: xorYvalue offset at the case may be
        // GetxOrYOffsetPoint In: Point3dOrigin, xOryOffsetAmount, bool offsettingXvalues, Out: Point3d (OffsetPoint)
        // IsBlockReference In: ObjectID, Out: true or false bool (whether the objectID was a blockreference).
        // HighlightLine Out: Void (highlights Line) In: (Ln, bool: to highlight or unhighlight)
        // HighlightBlock Out: Void (highlights block) In: (Objectid (blockreference object id), bool: to highlight or unhighlight)
        // GetBlockReference In: BRid, Out: BlockReference, if the objectID passed in is not a block reference, an exception is thrown.
        // IsLineEqual In: Ln1, Ln2, tolerance Out: bool
        // IsBlockReferenceDuplicate In: BlockReference1, BlockReference2 Out: bool
        // IsLineDuplicate In: ln1, ln2, Tolerance; Out: bool (tests to see whether two lines are the same with a tolerance
        // DeleteEntitesonLayer - deletes all entities on a specified layer
        public static void CheckLayerAndCreate(string layerName)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            using (DocumentLock docLock = doc.LockDocument())
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    // create a layer if none already exists
                    if ( !lt.Has(layerName))
                    {
                        LayerTableRecord ltr = new LayerTableRecord();

                        // set its properties
                        ltr.Name = layerName;

                        ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 256);

                        // add the layer to the layer table

                        lt.UpgradeOpen();

                        ObjectId ltId = lt.Add(ltr);

                        tr.AddNewlyCreatedDBObject(ltr, true);

                        tr.Commit();
                    }
                }

            }
        }
Beispiel #36
0
 // This function returns the objectId for the "EmployeeLayer", creating it if necessary.
 private ObjectId CreateLayer()
 {
     ObjectId layerId;
     Database db = HostApplicationServices.WorkingDatabase;
     using (Transaction trans = db.TransactionManager.StartTransaction())
     {
         // open the layer table for read first, to check to see if the requested layer exists
         LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead);
         // Check if EmployeeLayer exists...
         if (lt.Has("EmployeeLayer"))
         {
             layerId = lt["EmployeeLayer"];
         }
         else
         {
             // if not, create the layer here.
             LayerTableRecord ltr = new LayerTableRecord();
             ltr.Name = "EmployeeLayer"; // Set the layer name
             ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 2);
             // upgrade the open from read to write
             lt.UpgradeOpen();
             // now add the new layer
             layerId = lt.Add(ltr);
             trans.AddNewlyCreatedDBObject(ltr, true);
             trans.Commit(); // Only need to commit when we have made a change!
         }
     }
     return layerId;
 }
Beispiel #37
0
        /// <summary>
        /// Переопределение параметров задаваемого слоя согласно свойствам объекта класса.
        /// </summary>
        /// <param name="acadLayer"></param>
        public void Update(ref LayerTableRecord acadLayer)
        {
            if (acadLayer != null)
            {
                if (acadLayer.Name != "0")
                {
                    if (!acadLayer.Name.Contains("|"))
                    {
                        acadLayer.Name = Name;
                    }
                    else
                    {
                        MessageBox.Show("Слой не может быть переименован, т.к. содержит внешние ссылки.");
                    }
                }
                else if (acadLayer.Name != Name)
                {
                    MessageBox.Show("Слой 0 нельзя переименовать.");
                }

                acadLayer.IsOff = !Visibility;
                acadLayer.Color = Color;
            }
        }
Beispiel #38
0
        public Layer(LayerTableRecord layer)
        {
            _id = layer.Id;
            _name = layer.Name;
            _color = layer.Color;
            _visibility = !layer.IsOff;

            _points = new ObservableCollection<Point>();
            _lines = new ObservableCollection<Line>();
            _circles = new ObservableCollection<Circle>();

            _selectedPoint = new Point();
            _selectedLine = new Line();
            _selectedCirle = new Circle();
        }
Beispiel #39
0
 public void CreateLayer()
 {
     ObjectId layerId;
     Database db = HostApplicationServices.WorkingDatabase;
     //��ʼһ������
     Transaction trans = db.TransactionManager.StartTransaction();
     try
     {
         //����ȡ�ò��
         LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite);
         //���MyLayer���Ƿ����
         if (lt.Has("MyLayer"))
         {
             layerId = lt["MyLayer"];
         }
         else
         {
             //���MyLayer�㲻���ڣ��ʹ�����
             LayerTableRecord ltr = new LayerTableRecord();
             ltr.Name = "MyLayer"; //�������
             layerId = lt.Add(ltr);
             trans.AddNewlyCreatedDBObject(ltr, true);
         }
         //�ύ����
         trans.Commit();
     }
     catch (Autodesk.AutoCAD.Runtime.Exception e)
     {
         //��������
         trans.Abort();
     }
     finally
     {
         // ��ʽ���ͷ�
         trans.Dispose();
     }
 }
Beispiel #40
0
        }  //遍历块表记录 ++ 升降级打开对象

        //创建一个层
        public ObjectId CreateLayer()
        {


            ObjectId layerId; //它返回函数的值

            Database db = HostApplicationServices.WorkingDatabase;

            Transaction trans = db.TransactionManager.StartTransaction();

            //首先取得层表……

            LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite);

            //检查EmployeeLayer层是否存在……


            if (lt.Has("EmployeeLayer"))
            {

                layerId = lt["EmployeeLayer"];
            }
            else
            {

                //如果EmployeeLayer层不存在,就创建它

                LayerTableRecord ltr = new LayerTableRecord();

                ltr.Name = "EmployeeLayer"; //设置层的名字

                ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 2);

                layerId = lt.Add(ltr);

                trans.AddNewlyCreatedDBObject(ltr, true);

            }

            trans.Commit();

            trans.Dispose();

            return layerId;

        }
Beispiel #41
0
        /// <summary>
        /// Функция создет слой.
        /// </summary>
        /// <param name="layerName">Имя слоя.</param>
        /// <param name="isPlottable">Если параметр равен false, то слой будет помечен как непечатаемый.</param>
        /// <param name="isFrozen">Если параметр равен true, то слой будет помечен как замороженный.</param>
        public static bool CreateLayer(string layerName, bool isPlottable, bool isFrozen)
        {
            try
            {
                Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ.
                //Editor acDocEd = acDoc.Editor; // Editor текущего документа.
                Database acDocDb = acDoc.Database; // Database текущего документа.

                
                using (acDoc.LockDocument()) // блокировка документа
                {
                    // начинаем транзакцию
                    using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction())
                    {
                        // открываем таблицу слоев документа
                        LayerTable acLayerTable = acTrans.GetObject(acDocDb.LayerTableId, OpenMode.ForWrite) as LayerTable;

                        if (acLayerTable != null && acLayerTable.Has(layerName) == false) // проверяем отсутствие слоя с таким же именем
                        {
                            // создаем новый слой и задаем ему имя
                            LayerTableRecord acLayerTableRecord = new LayerTableRecord();
                            try
                            {
                                acLayerTableRecord.Name = layerName;
                            }

                            catch (Autodesk.AutoCAD.Runtime.Exception ex) 
                            {
                                if (ex.Message == "eInvalidInput")
                                {
                                    acTrans.Abort();
                                    MessageBox.Show("Недопустимое имя слоя!", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    return false;
                                }
                                else
                                {
                                    throw;
                                }
                            }

                            if (!isPlottable) { acLayerTableRecord.IsPlottable = false; } //делаем слой непечатаемым
                            if (isFrozen) { acLayerTableRecord.IsFrozen = true; } //делаем слой замороженным

                            // заносим созданный слой в таблицу слоев
                            acLayerTable.Add(acLayerTableRecord);

                            // добавляем созданный слой в документ
                            acTrans.AddNewlyCreatedDBObject(acLayerTableRecord, true);
                        }

                        // фиксируем транзакцию
                        acTrans.Commit();
                        return true;
                    }
                }
            }

            catch (NullReferenceException)
            {
                return false;
            }
        }
        private static void SetLayerProperties(LayerTableRecord stdLayer, LayerTableRecord ltr, Database db, Transaction tr)
        {
            ltr.Color = stdLayer.Color;
             ltr.LineWeight = stdLayer.LineWeight;
             ObjectIdCollection acObjIdColl = new ObjectIdCollection();
             acObjIdColl.Add(stdLayer.LinetypeObjectId);
             IdMapping acIdMap = new IdMapping();

             LinetypeTable acLinTbl; acLinTbl = tr.GetObject(db.LinetypeTableId, OpenMode.ForWrite) as LinetypeTable;
             db.WblockCloneObjects(acObjIdColl, acLinTbl.Id, acIdMap,
                                    DuplicateRecordCloning.Ignore, false);
             LinetypeTableRecord currentLineType = GetLineType(tr, stdLayer.LinetypeObjectId, acLinTbl);

             ltr.LinetypeObjectId = currentLineType.Id;
             ltr.IsPlottable = stdLayer.IsPlottable;
             ltr.Description = stdLayer.Description;
        }
        //create layer for signature
        private ObjectId createLayer(string lyname)
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = HostApplicationServices.WorkingDatabase;            

            //search the specific layer  
            TypedValue[] filList = new TypedValue[1] {
                        new TypedValue((int)DxfCode.LayerName, lyname)
                };
            SelectionFilter filter = new SelectionFilter(filList);

            PromptSelectionResult selRes = ed.SelectAll(filter);
            if (selRes.Status != PromptStatus.OK && 
                selRes.Status != PromptStatus.Error) //error means no such layer. can continue the following code
            {
                ed.WriteMessage("\nerror in getting all entities on a layer named " + lyname + " >>error:" + selRes.Status);
                return ObjectId.Null;
            }
                        
            LayerTableRecord signatureLayer = null;
            try
            {

                using (Transaction tr =
                    db.TransactionManager.StartTransaction())
                {
                    if (selRes.Status == PromptStatus.OK)
                    {
                        ed.WriteMessage("\nTo delete entities on the signature layer");

                        //delete all signatures (solids) on the old layer
                        ObjectId[] ids = selRes.Value.GetObjectIds();
                        foreach (ObjectId eachentid in ids)
                        {
                            Entity oEnt = tr.GetObject(eachentid, OpenMode.ForWrite) as Entity;
                            oEnt.Erase();
                        }
                    }

                    ed.WriteMessage("\nTo delete signature layer");
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;
                    if (layerTable.Has(lyname))
                    {
                        //delete the old layer
                        ObjectId LTR_id = layerTable[lyname];
                        ObjectIdCollection idCol = new ObjectIdCollection();
                        idCol.Add(LTR_id);
                        db.Purge(idCol);

                        LayerTableRecord oLTR = tr.GetObject(LTR_id, OpenMode.ForWrite) as LayerTableRecord;
                        oLTR.Erase();
                    }

                    ed.WriteMessage("\nTo create  signature layer");
                    //create new layer
                    signatureLayer = new LayerTableRecord();
                    signatureLayer.Name = lyname;
                    layerTable.Add(signatureLayer);
                    tr.AddNewlyCreatedDBObject(signatureLayer, true);

                    tr.Commit();
                }

                if (signatureLayer != null)
                    return signatureLayer.ObjectId;
                else
                    return ObjectId.Null;
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\nerror in create layer " + ex.ToString());
                return ObjectId.Null;
            }
        }
 private static void SetStandartToLayer(Database db, LayerTableRecord stdLayer, Transaction tr, string activeLayerName, string stdLayerName, LayerTable layerTable)
 {
     //  var stdDatabase = new Database(false, true);
      // stdDatabase.ReadDwgFile(@"Z:\AutoCAD_server\ShareSettings\КР-сб\КР-сб.dws", FileShare.Read, true, "");
      foreach (var layer in layerTable)
      {
     LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layer, OpenMode.ForWrite);
     if (!ltr.Name.Equals(activeLayerName)) continue;
     ltr.IsLocked = false;
     ltr.UpgradeOpen();
     if (activeLayerName == stdLayerName)
     {
        SetLayerProperties(stdLayer, ltr, db, tr);
     }
     else if (!layerTable.Has(stdLayerName))
     {
        ltr.Name = stdLayerName;
        SetLayerProperties(stdLayer, ltr, db, tr);
     }
     else
     {
        bool isLock = false;
        foreach (var layerStd in layerTable)
        {
           LayerTableRecord ltrstd = (LayerTableRecord)tr.GetObject(layerStd, OpenMode.ForWrite);
           if (!ltrstd.Name.Equals(stdLayerName)) continue;
           isLock = ltrstd.IsLocked;
           ltrstd.IsLocked = false;
           SetLayerProperties(stdLayer, ltrstd, db, tr);
           break;
        }
        SetLayerToEntity(db, activeLayerName, stdLayerName);
        ltr.IsLocked = isLock;
        DeleteLayer(activeLayerName, db);
     }
      }
 }
Beispiel #45
0
        //This function returns the objectId for the "EmployeeLayer", creating it if necessary.
        private static ObjectId CreateLayer()
        {
            ObjectId layerId = ObjectId.Null; //the return value for this function
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //Get the layer table first...
                LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead);

                //Check if EmployeeLayer exists...
                if (lt.Has("EmployeeLayer"))
                {
                    layerId = lt["EmployeeLayer"];
                }
                else
                {
                    //if not, create the layer here.
                    LayerTableRecord ltr = new LayerTableRecord();
                    ltr.Name = "EmployeeLayer"; // Set the layer name
                    ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 2);
                    // upgrade the open from read to write
                    lt.UpgradeOpen();
                    layerId = lt.Add(ltr);
                    trans.AddNewlyCreatedDBObject(ltr, true);
                }
                trans.Commit();
            }
            return layerId;
        }
        public static ObjectId CreateLayer(String name)
        {
            using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;
                Editor ed = doc.Editor;

                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                    LayerTableRecord ltr = new LayerTableRecord();
                    // ... and set its properties
                    ltr.Name = name;
                    ltr.Color = Color.FromRgb(255, 0, 0);
                    //ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 0);
                    // Add the new layer to the layer table
                    lt.UpgradeOpen();
                    ObjectId ltId = lt.Add(ltr);
                    tr.AddNewlyCreatedDBObject(ltr, true);
                    db.Clayer = ltId;
                    // Commit the transaction
                    tr.Commit();
                    return ltId;
                }
            }
        }
Beispiel #47
0
 /// <summary>
 /// Создание слоя.
 /// Слоя не должно быть в таблице слоев.
 /// </summary>
 /// <param name="layerInfo">параметры слоя</param>
 /// <param name="lt">таблица слоев открытая для чтения. Выполняется UpgradeOpen и DowngradeOpen</param>
 public static ObjectId CreateLayer(this LayerInfo layerInfo, LayerTable lt)
 {
     ObjectId idLayer = ObjectId.Null;
     // Если слоя нет, то он создается.
     using (var newLayer = new LayerTableRecord())
     {
         layerInfo.SetProp(newLayer, lt.Database);
         lt.UpgradeOpen();
         idLayer = lt.Add(newLayer);
         lt.DowngradeOpen();
     }
     return idLayer;
 }
Beispiel #48
-7
 public static string GetLayerForMark(Database db)
 {
     using (LayerTable layerTable = db.LayerTableId.Open(0) as LayerTable)
      {
     if (!layerTable.Has(Settings.Default.LayerMarks))
     {
        using (LayerTableRecord layerTableRecord = new LayerTableRecord())
        {
           layerTableRecord.Name = Settings.Default.LayerMarks;
           layerTable.UpgradeOpen();
           layerTable.Add(layerTableRecord);
        }
     }
      }
      return Settings.Default.LayerMarks;
 }