Exemplo n.º 1
0
        public static ObjectId GetArrowObjectId(string arrow, string newArrName)
        {
            var Return = ObjectId.Null;

            string oldArrName = Application.GetSystemVariable(arrow).ToString();

            Application.SetSystemVariable(arrow, newArrName);

            if (oldArrName.Length != 0)
            {
                Application.SetSystemVariable(arrow, oldArrName);
            }

            using (Transaction t = AC.DB.TransactionManager.StartTransaction())
            {
                var BT = t.GetObject(AC.DB.BlockTableId, OpenMode.ForWrite) as BlockTable;

                //ObjectId d = new ObjectId(new IntPtr(165522592));
                //var A = t.GetObject(d, OpenMode.ForRead) as BlockTableRecord;
                //MessageBox.Show(A.Name);

                Return = BT[newArrName];
                t.Commit();
            }

            return(Return);
        }
Exemplo n.º 2
0
        private static bool SetMapScale(Document document)
        {
            // http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-4fff.htm,topicNumber=d0e346024
            var dynmode = AcadApplication.GetSystemVariable("DYNMODE");

            AcadApplication.SetSystemVariable("DYNMODE", 2); // 2 means "Dimensional input on"

            int    defaultScale = 500;
            string strPrompt    = String.Format("\n设置绘图比例尺为1:<{0}>", defaultScale);
            var    pScaleOpts   = new PromptIntegerOptions(strPrompt)
            {
                AllowNone = true,
                AllowZero = false
            };

            var pScaleRes = document.Editor.GetInteger(pScaleOpts);

            AcadApplication.SetSystemVariable("DYNMODE", dynmode);
            if (pScaleRes.Status == PromptStatus.OK || pScaleRes.Status == PromptStatus.None)
            {
                double scale = defaultScale;
                if (pScaleRes.Status == PromptStatus.OK)
                {
                    scale = pScaleRes.Value;
                }
                MapScaleUtils.SetApplicationMapScale(scale);

                return(true);
            }
            return(false);
        }
Exemplo n.º 3
0
        /* Sends the pdf into AutoCAD and runs -PDFIMPORT then quits the program
         * Calls: NewDrawing, SaveActiveDrawing
         * Called by: Main
         * Returns: none
         */
        //[CommandMethod("PdfImport")]
        public void ImportPdf(string userfile, int userpage, string usersave, int pageend)
        {
            var dwg = CadApp.DocumentManager.MdiActiveDocument;
            //var ed = dwg.Editor;
            int    fileDia = Convert.ToInt32(CadApp.GetSystemVariable("FILEDIA"));
            string save;

            for (int page = userpage; page <= pageend; page++)
            {
                //Start command -PDFIMPORT with pdf file name supplied
                var cmd = "-PDFIMPORT f\r";
                dwg = NewDrawing();
                dwg.SendStringToExecute(cmd, true, false, false);
                dwg.SendStringToExecute(userfile + "\r", true, false, false);
                // supply page input
                dwg.SendStringToExecute(page + "\r", true, false, false);
                // supply insertion location inputset
                dwg.SendStringToExecute("10.0,10.0\r", true, false, false);
                // supply scale input
                dwg.SendStringToExecute("1.0\r", true, false, false);
                // supply rotation input
                dwg.SendStringToExecute("0.0\r", true, false, false);
                save = SaveActiveDrawing(usersave, page, dwg);
                dwg.SendStringToExecute("SAVE\r", true, false, false);
                dwg.SendStringToExecute(save + "\r", true, false, false);
            }
            dwg.SendStringToExecute("_QUIT\r", true, false, false);
        }
Exemplo n.º 4
0
        public void Call()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            string   line;

            // Local do arquivo de dados: O diretório do .dwg onde está sendo
            // executado o programa.
            string curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString();

            var commandsFile = new StreamReader(curDwgPath + "\\commands.txt");

            while (!commandsFile.EndOfStream)
            {
                line = commandsFile.ReadLine();
                if (line != "")
                {
                    try
                    {
                        ed.Command(line);
                    }
                    catch (System.Exception)
                    {
                        throw;
                    }
                }
            }

            commandsFile.Close();
        }
        public void AutoDwgAndSave()
        {
            //通过系统变量获取样板的路径
            string sLocalRoot    = AcadApp.GetSystemVariable("LOCALROOTPREFIX") as string;
            string sTemplatePath = sLocalRoot + "Template\\acad.dwt";


            //新建一个文档
            Document m_doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.Add(sTemplatePath);

            Database acCurDb = m_doc.Database;

            //初始化类 并且更新需要在哪个document生成图形
            this.OperatingCadInitialize(m_doc);  //这里一定要初始化赋值

            //操作非当前文档,建立先锁定文档
            using (DocumentLock docLock = m_doc.LockDocument())
            {
                Database db = doc.Database;
                // 新建表格
                Table table = new Table();
                table.SetSize(10, 5);                                     // 表格大小
                table.SetRowHeight(10);                                   // 设置行高
                table.SetColumnWidth(50);                                 // 设置列宽
                table.Columns[0].Width       = 20;                        // 设置第一列宽度为20
                table.Position               = new Point3d(100, 100, 0);  // 设置插入点
                table.Cells[0, 0].TextString = "测试表格数据统计";                // 表头
                table.Cells[0, 0].TextHeight = 6;                         //设置文字高度
                Color color = Color.FromColorIndex(ColorMethod.ByAci, 3); // 声明颜色
                table.Cells[0, 0].BackgroundColor = color;                // 设置背景颜色
                color = Color.FromColorIndex(ColorMethod.ByAci, 1);
                table.Cells[0, 0].ContentColor = color;                   //内容颜色
                //开启事务处理
                using (Transaction trans = acCurDb.TransactionManager.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    btr.AppendEntity(table);
                    trans.AddNewlyCreatedDBObject(table, true);
                    trans.Commit();
                }
            }

            //判断该文件是否存在
            string strCableName = "Testdoc"; // 保存文件名

            if (!File.Exists("D:" + "\\" + strCableName + ".dwg"))
            {
                //然后另存为并且关闭
                m_doc.Database.SaveAs("D:" + "\\" + strCableName + ".dwg", DwgVersion.Current);  //另存为 这里需要命名
                m_doc.CloseAndDiscard();                                                         //关闭
            }
            else
            {
                File.Delete("D:" + "\\" + strCableName + ".dwg");
                m_doc.Database.SaveAs("D:" + "\\" + strCableName + ".dwg", DwgVersion.Current);
                m_doc.CloseAndDiscard();
            }
        }
Exemplo n.º 6
0
        private void LoadMyCui(string cuiFile)
        {
            Document doc        = Application.DocumentManager.MdiActiveDocument;
            object   oldCmdEcho = Application.GetSystemVariable("CMDECHO");

            Application.SetSystemVariable("CMDECHO", 0);
            doc.SendStringToExecute("(command \"_.CUILOAD\" \"" + cuiFile + "\")(setvar \"CMDECHO\" " + oldCmdEcho + ")(princ) ", false, false, false);
        }
Exemplo n.º 7
0
        private static bool IsCommandActive()
        {
            String str = (String)Application.GetSystemVariable("CMDNAMES");

            if (String.Compare(commandName, str, true) != 0)
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 8
0
        public void MoveBlock()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            // LOcal do arquivo de dados: O diretório do .dwg onde está send
            // executado o programa.
            string curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString();

            // Cria um StreamReader para ler o arquivo 'moveblocks.txt', que contém
            // os dados para mover os blocos.
            var fileData = new StreamReader(curDwgPath + "\\moveBlocks.txt");

            // Armazenará uma linha que será lida do 'moveBlocks.txt'
            string[] sFileLine;

            string blockId;

            string[] coords;
            string   coordX;
            string   coordY;
            Point3d  oldPos;
            Point3d  newPos;
            Vector3d vector;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                while (!fileData.EndOfStream)
                {
                    sFileLine = fileData.ReadLine().Split(';');
                    blockId   = sFileLine[0];
                    coords    = sFileLine[1].Split(',');
                    coordX    = coords[0];
                    coordY    = coords[1];

                    DBObject     dbModelSpace = tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);
                    ObjectId     extId        = dbModelSpace.ExtensionDictionary;
                    DBDictionary dbExt        = (DBDictionary)tr.GetObject(extId, OpenMode.ForRead);

                    BlockReference blkRef      = GetRefBlkFromIndex(db, dbExt, blockId);
                    BlockReference blkRefWrite = (BlockReference)tr.GetObject(blkRef.Id, OpenMode.ForWrite);

                    oldPos = blkRef.Position;
                    newPos = new Point3d(Convert.ToDouble(coordX), Convert.ToDouble(coordY), 0);
                    vector = oldPos.GetVectorTo(newPos);

                    blkRefWrite.TransformBy(Matrix3d.Displacement(vector));
                }
                tr.Commit();
            }
        }
Exemplo n.º 9
0
        MakePointEnt(Point3d pt, int colorIndex, Transaction tr, Database db)
        {
            short mode = (short)AcadApp.GetSystemVariable("pdmode");

            if (mode == 0)
            {
                AcadApp.SetSystemVariable("pdmode", 99);
            }

            using (DBPoint dbPt = new DBPoint(pt)) {
                dbPt.ColorIndex = colorIndex;
                MgdDbg.Utils.SymTbl.AddToCurrentSpace(dbPt, db, tr);
            }
        }
Exemplo n.º 10
0
        MakePointEnt(Point3d pt, int colorIndex, Transaction tr)
        {
            m_db = Utils.Db.GetCurDwg();

            short mode = (short)AcadApp.GetSystemVariable("pdmode");

            if (mode == 0)
            {
                AcadApp.SetSystemVariable("pdmode", 99);
            }

            using (DBPoint dbPt = new DBPoint(Utils.Db.WcsToUcs(pt))) {
                dbPt.ColorIndex = colorIndex;
                Utils.Db.TransformToWcs(dbPt, m_db);
                Utils.SymTbl.AddToCurrentSpace(dbPt, m_db, tr);
            }
        }
Exemplo n.º 11
0
        public void LoadMyCui()
        {
            var path       = ElectronTransferBll.Register.GetItemValue("CustomAutoCAD", "LOADER", false);
            var folderPath = path.Substring(0, path.LastIndexOf('\\'));
            var cuiPath    = Path.Combine(folderPath, "zhsc.cuix");

            var doc        = Application.DocumentManager.MdiActiveDocument;
            var oldCmdEcho = Application.GetSystemVariable("CMDECHO");
            var oldFileDia = Application.GetSystemVariable("FILEDIA");

            Application.SetSystemVariable("CMDECHO", 0);
            Application.SetSystemVariable("FILEDIA", 0);

            var mainCuiFile = (string)Application.GetSystemVariable("MENUNAME") + ".cuix";
            var str         = Path.GetFileNameWithoutExtension(mainCuiFile);

            if (str.ToLower() == "acad")
            {
                doc.SendStringToExecute(
                    "_.cuiunload "
                    + "acad"
                    + " ",
                    false, false, false);

                doc.SendStringToExecute(
                    "_.cuiload "
                    + cuiPath + " ",
                    false, false, false);
            }


            doc.SendStringToExecute(
                "(setvar \"FILEDIA\" "
                + oldFileDia
                + ")(princ) ",
                false, false, false
                );

            doc.SendStringToExecute(
                "(setvar \"CMDECHO\" "
                + oldCmdEcho
                + ")(princ) ",
                false, false, false
                );
        }
Exemplo n.º 12
0
        public static void SaveActiveDrawing()
        {
            Document acDoc      = Application.DocumentManager.MdiActiveDocument;
            string   strDWGName = acDoc.Name;
            object   obj        = Application.GetSystemVariable("DWGTITLED");
            //图形命名了吗?0-没呢
            //if (System.Convert.ToInt16(obj) == 0) {
            // 如果图形使用了默认名 (Drawing1、Drawing2等),
            // 就提供一个新文件名
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter   = "CAD文件|*.dwg";
            saveFileDialog.FileName = strDWGName;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                acDoc.Database.SaveAs(saveFileDialog.FileName, true, DwgVersion.Current,
                                      acDoc.Database.SecurityParameters);
            }
            //}
        }
Exemplo n.º 13
0
        public void Initialize()
        {
            try
            {
                CurrentDirectory = System.IO.Directory.GetCurrentDirectory();
                //bool verify = Verify();
                //if (!verify)
                //{
                //    System.Windows.MessageBox.Show("您的软件使用权已经过期.\n 请联系软件提供商.", "Error");
                //    return;
                //}

                Utility.ClearApplicationConfig();
                DataConfig.init_config_path();
                DataConfig.loadCustomConfig();
                loadConfigData();
                //初始化常量
                Constants.InitilizeConstant();
                //显示各控件
                showSolution();
                //关闭选项卡
                //closeRibbon();
                showTool();
                showAttrsEditor();
                //最后进行文件恢复
                restore();
                //测试截图
                Application.SetSystemVariable("NAVVCUBEDISPLAY", 0);
                Application.SetSystemVariable("NAVBARDISPLAY", 0);
                Object obj = Application.GetSystemVariable("DBLCLKEDIT");
                Application.SetSystemVariable("DBLCLKEDIT", 0);
            }
            catch (System.Exception e)
            {
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(e.Message);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Type "CANNOSCALE" to get current scale
        /// </summary>
        /// <param name="scalename"></param>
        /// <returns></returns>
        public static AnnotationScale GetAnnoScale(string scalename)
        {
            if (scalename == "CANNOSCALE")
            {
                scalename = App.GetSystemVariable("CANNOSCALE").ToString();
            }

            Document acDoc   = App.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            AnnotationScale asc = new AnnotationScale();

            ObjectContextManager ocm = acCurDb.ObjectContextManager;

            if (ocm != null)
            {
                ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES");
                if (occ != null)
                {
                    asc = occ.GetContext(scalename) as AnnotationScale;
                }
            }
            return(asc);
        }
Exemplo n.º 15
0
        public void PrintTT()
        {
            Document      acDoc     = Application.DocumentManager.MdiActiveDocument;
            Database      acCurDb   = acDoc.Database;
            Editor        ed        = Application.DocumentManager.MdiActiveDocument.Editor;
            List <String> imagelist = new List <String>();

            string directory = @"D:\";//磁盘路径
            string MediaName = comboBoxMedia.SelectedItem.ToString().Replace(" ", "_").Replace("毫米", "MM").Replace("英寸", "Inches").Replace("像素", "Pixels");

            try
            {
                if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        int flag = 0;
                        //获取当前布局管理器变量
                        LayoutManager acLayoutMgr = LayoutManager.Current;
                        //获取当前布局变量
                        Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead);
                        //Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForWrite);
                        //获取当前布局的打印信息
                        PlotInfo acPlInfo = new PlotInfo()
                        {
                            Layout = acLayout.ObjectId
                        };



                        //提示用户输入打印窗口的两个角点
                        PromptPointResult resultp = ed.GetPoint("\n指定第一个角点");
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d basePt = resultp.Value;
                        resultp = ed.GetCorner("指定对角点", basePt);
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d cornerPt = resultp.Value;

                        //选择实体对象
                        // PromptSelectionOptions result1 = new PromptSelectionOptions();

                        SelectionFilter frameFilter = new SelectionFilter(
                            new TypedValue[]
                            { new TypedValue(0, "LWPOLYLINE"),
                              new TypedValue(90, 4),
                              new TypedValue(70, 1) });


                        PromptSelectionResult selectedFrameResult = ed.SelectWindow(basePt, cornerPt, frameFilter);
                        // PromptSelectionResult selectedFrameResult = ed.GetSelection(result1, frameFilter);
                        PromptSelectionResult selectedFrameResult1 = ed.SelectAll(frameFilter);
                        if (selectedFrameResult.Status == PromptStatus.OK)
                        {
                            List <ObjectId> selectedObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            List <ObjectId> resultObjectIds   = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            RemoveInnerPLine(acTrans, ref selectedObjectIds, ref resultObjectIds);
                            foreach (ObjectId frameId in resultObjectIds)
                            {
                                Polyline framePline = acTrans.GetObject(frameId, OpenMode.ForRead) as Polyline;
                                framePline.Highlight();
                            }


                            PlotSettings acPlSet = new PlotSettings(acLayout.ModelType);
                            acPlSet.CopyFrom(acLayout);
                            //着色打印选项,设置按线框进行打印
                            acPlSet.ShadePlot = PlotSettingsShadePlotType.Wireframe;
                            PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                            //打印比例
                            //用户标准打印
                            acPlSetVdr.SetUseStandardScale(acPlSet, true);
                            acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);

                            //居中打印
                            acPlSetVdr.SetPlotCentered(acPlSet, true);
                            //调用GetPlotStyleSheetList之后才可以使用SetCurrentStyleSheet
                            System.Collections.Specialized.StringCollection sc = acPlSetVdr.GetPlotStyleSheetList();
                            //设置打印样式表
                            if (comboBoxStyleSheet.SelectedItem.ToString() == "无")
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, "acad.ctb");
                            }

                            else
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, comboBoxStyleSheet.SelectedItem.ToString());
                            }

                            //选择方向
                            if (radioButtonHorizontal.Checked)
                            {
                                //横向
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090);
                            }

                            //竖向
                            if (radioButtonVertical.Checked)
                            {
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);//获取打印图纸尺寸ComboxMedia
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees000);
                            }
                            PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, resultObjectIds.Count, true);
                            string             imagename   = "";
                            string[]           files       = new string[] { };
                            List <string>      listfile    = new List <string>();
                            foreach (var frame in resultObjectIds)
                            {
                                if (!Directory.Exists(directory))
                                {
                                    Directory.CreateDirectory(directory);
                                }
                                flag++;

                                Entity ent = acTrans.GetObject(frame, OpenMode.ForRead) as Entity;

                                imagename = string.Format("{0}-{1}.pdf", frame, flag);
                                //imagelist.Add(directory + imagename);
                                listfile.Add(directory + imagename);


                                //设置是否使用打印样式
                                acPlSet.ShowPlotStyles = true;
                                //设置打印区域
                                Extents3d extents3d = ent.GeometricExtents;

                                Extents2d E2d = new Extents2d(extents3d.MinPoint.X, extents3d.MinPoint.Y, extents3d.MaxPoint.X, extents3d.MaxPoint.Y);
                                acPlSetVdr.SetPlotWindowArea(acPlSet, E2d);
                                acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                //重载和保存打印信息
                                acPlInfo.OverrideSettings = acPlSet;
                                //验证打印信息设置,看是否有误
                                PlotInfoValidator acPlInfoVdr = new PlotInfoValidator();
                                acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                acPlInfoVdr.Validate(acPlInfo);

                                while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                                {
                                    continue;
                                }
                                #region BackUpCode

                                //保存App的原参数
                                short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                                //设定为前台打印,加快打印速度
                                Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                                PlotEngine acPlEng1 = PlotFactory.CreatePublishEngine();
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                                //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                                acPlProgDlg.LowerPlotProgressRange = 0;
                                acPlProgDlg.UpperPlotProgressRange = 100;
                                acPlProgDlg.PlotProgressPos        = 0;
                                acPlProgDlg.OnBeginPlot();
                                acPlProgDlg.IsVisible = true;
                                acPlEng1.BeginPlot(acPlProgDlg, null);
                                acPlEng1.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                                //  acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                                acPlProgDlg.OnBeginSheet();
                                acPlProgDlg.LowerSheetProgressRange = 0;
                                acPlProgDlg.UpperSheetProgressRange = 100;
                                acPlProgDlg.SheetProgressPos        = 0;
                                PlotPageInfo acPlPageInfo = new PlotPageInfo();
                                acPlEng1.BeginPage(acPlPageInfo, acPlInfo, true, null);
                                acPlEng1.BeginGenerateGraphics(null);
                                acPlEng1.EndGenerateGraphics(null);
                                acPlEng1.EndPage(null);
                                acPlProgDlg.SheetProgressPos = 100;
                                acPlProgDlg.OnEndSheet();
                                acPlEng1.EndDocument(null);
                                acPlProgDlg.PlotProgressPos = 100;
                                acPlProgDlg.OnEndPlot();
                                acPlEng1.EndPlot(null);
                                acPlEng1.Dispose();
                                acPlEng1.Destroy();
                                Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);

                                #endregion
                            }


                            files = listfile.ToArray();
                            PlotConfig config = PlotConfigManager.CurrentConfig;
                            //获取去除扩展名后的文件名(不含路径)
                            string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(acDoc.Name, "dwg");
                            //定义保存文件对话框
                            PromptSaveFileOptions opt = new PromptSaveFileOptions("文件名")
                            {
                                //保存文件对话框的文件扩展名列表
                                Filter           = "*" + config.DefaultFileExtension + "|*" + config.DefaultFileExtension,
                                DialogCaption    = "浏览打印文件",                            //保存文件对话框的标题
                                InitialDirectory = @"D:\",                              //缺省保存目录
                                InitialFileName  = fileName + "-" + acLayout.LayoutName //缺省保存文件名
                            };
                            //根据保存对话框中用户的选择,获取保存文件名
                            PromptFileNameResult result = ed.GetFileNameForSave(opt);
                            if (result.Status != PromptStatus.OK)
                            {
                                return;
                            }
                            fileName = result.StringResult;

                            //string fileName = @"D:\输出.pdf";
                            PdfDocumentBase docx = PdfDocument.MergeFiles(files);
                            docx.Save(fileName, FileFormat.PDF);
                            System.Diagnostics.Process.Start(fileName);



                            //保存App的原参数
                            short bgPlot1 = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                            //设定为前台打印,加快打印速度
                            Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                            PlotEngine acPlEng = PlotFactory.CreatePublishEngine();
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                            acPlProgDlg.LowerPlotProgressRange = 0;
                            acPlProgDlg.UpperPlotProgressRange = 100;
                            acPlProgDlg.PlotProgressPos        = 0;
                            acPlProgDlg.OnBeginPlot();
                            acPlProgDlg.IsVisible = true;
                            acPlEng.BeginPlot(acPlProgDlg, null);
                            acPlEng.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                            acPlProgDlg.OnBeginSheet();
                            acPlProgDlg.LowerSheetProgressRange = 0;
                            acPlProgDlg.UpperSheetProgressRange = 100;
                            acPlProgDlg.SheetProgressPos        = 0;
                            PlotPageInfo acPlPageInfo1 = new PlotPageInfo();
                            acPlEng.BeginPage(acPlPageInfo1, acPlInfo, true, null);
                            acPlEng.BeginGenerateGraphics(null);
                            acPlEng.EndGenerateGraphics(null);
                            acPlEng.EndPage(null);
                            acPlProgDlg.SheetProgressPos = 100;
                            acPlProgDlg.OnEndSheet();
                            acPlEng.EndDocument(null);
                            acPlProgDlg.PlotProgressPos = 100;
                            acPlProgDlg.OnEndPlot();
                            acPlEng.EndPlot(null);
                            acPlEng.Dispose();
                            acPlEng.Destroy();
                            Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot1);

                            acPlProgDlg.Dispose();
                            acPlProgDlg.Destroy();

                            for (int i = 0; i < files.Length; i++)
                            {
                                File.Delete(files[i]);
                            }
                        }
                        while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                        {
                            continue;
                        }
                        //MessageBox.Show("打印完成!");
                    }
                }
                else
                {
                    ed.WriteMessage("\n另一个打印进程正在进行中.");
                }
            }



            catch (System.Exception)
            {
                throw;
            }
        }
Exemplo n.º 16
0
        public void Avx()
        {
            int  ver          = AcAp.Version.Major;
            bool segHighlight = ver >= 18;
            bool loop         = true;

            PromptEntityOptions peo = new PromptEntityOptions(
                "\nSelet asegment where to add a vertex: ");

            peo.SetRejectMessage("\nPolyline only: ");
            peo.AllowNone = false;
            peo.AllowObjectOnLockedLayer = false;
            peo.AddAllowedClass(typeof(Polyline), false);
            while (loop)
            {
                PromptEntityResult per = ed.GetEntity(peo);
                if (per.Status != PromptStatus.OK)
                {
                    loop = false;
                    continue;
                }
                Matrix3d UCS   = ed.CurrentUserCoordinateSystem;
                ObjectId objId = per.ObjectId;
                try
                {
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        Polyline pline  = (Polyline)trans.GetObject(objId, OpenMode.ForRead, false);
                        Point3d  pickPt = pline.GetClosestPointTo(
                            per.PickedPoint.TransformBy(UCS),
                            ed.GetCurrentView().ViewDirection,
                            false);
                        double param = pline.GetParameterAtPoint(pickPt);
                        int    index = (int)param;

                        Matrix3d OCS     = Matrix3d.PlaneToWorld(pline.Normal);
                        Point3d  transPt = pickPt.TransformBy(OCS);

                        if (!OCS.CoordinateSystem3d.Zaxis.IsEqualTo(UCS.CoordinateSystem3d.Zaxis))
                        {
                            ed.CurrentUserCoordinateSystem = PlineUCS(pline, index);
                        }

                        var       aperture   = (Int16)AcAp.GetSystemVariable("APERTURE");
                        double    viewSize   = (double)AcAp.GetSystemVariable("VIEWSIZE");
                        Point2d   screenSize = (Point2d)AcAp.GetSystemVariable("SCREENSIZE");
                        double    tol        = 2 * aperture * viewSize / screenSize.Y;
                        Tolerance tolerance  = new Tolerance(tol, tol);

                        int endParam = pline.Closed ?
                                       pline.NumberOfVertices :
                                       pline.NumberOfVertices - 1;
                        Vector3d vec;
                        using (Polyline ghost = new Polyline())
                        {
                            ghost.ColorIndex = 1;

                            if (!pline.Closed && pickPt.IsEqualTo(pline.GetPoint3dAt(0), tolerance))
                            {
                                vec = pline.GetFirstDerivative(0);
                                double  bulge = pline.GetBulgeAt(0);
                                double  width = pline.GetStartWidthAt(0);
                                Point2d p0    = transPt.GetPoint2d();
                                Point2d p1    = pline.GetPoint2dAt(0);

                                ghost.AddVertexAt(0, p0, bulge, width, width);
                                ghost.AddVertexAt(1, p1, bulge, width, width);
                                ghost.Normal    = pline.Normal;
                                ghost.Elevation = pline.Elevation;
                                VertexJig jig = new VertexJig(ghost, pickPt, 0, vec, bulge,
                                                              width, width);
                                PromptResult res = ed.Drag(jig);
                                if (res.Status == PromptStatus.OK)
                                {
                                    pline.UpgradeOpen();
                                    pline.AddVertexAt(index, ghost.GetPoint2dAt(0),
                                                      ghost.GetBulgeAt(0), width, width);
                                }
                            }
                            else if (!pline.Closed && pickPt.IsEqualTo(pline.GetPoint3dAt(endParam),
                                                                       tolerance))
                            {
                                vec = pline.GetFirstDerivative(endParam);
                                double  bulge = pline.GetBulgeAt(index);
                                double  width = pline.GetEndWidthAt(endParam);
                                Point2d p0    = pline.GetPoint2dAt(endParam);
                                Point2d p1    = new Point2d(transPt.X, transPt.Y);

                                ghost.AddVertexAt(0, p0, bulge, width, width);
                                ghost.AddVertexAt(1, p1, bulge, width, width);
                                ghost.Normal    = pline.Normal;
                                ghost.Elevation = pline.Elevation;
                                VertexJig jig = new VertexJig(ghost, pickPt, 1, vec,
                                                              bulge, width, width);

                                PromptResult res = ed.Drag(jig);
                                if (res.Status == PromptStatus.OK)
                                {
                                    pline.UpgradeOpen();
                                    pline.AddVertexAt(endParam + 1, ghost.GetPoint2dAt(1),
                                                      ghost.GetBulgeAt(0), width, width);
                                    pline.SetBulgeAt(endParam, ghost.GetBulgeAt(0));
                                }
                            }
                            else
                            {
                                vec = pline.GetFirstDerivative(index);
                                double  bulge  = pline.GetBulgeAt(index);
                                double  sWidth = pline.GetStartWidthAt(index);
                                double  eWidth = pline.GetEndWidthAt(index);
                                Point2d p0     = pline.GetPoint2dAt(index);
                                Point2d p1     = transPt.GetPoint2d();
                                Point2d p2;
                                if (!pline.Closed)
                                {
                                    p2 = pline.GetPoint2dAt(index + 1);
                                }
                                else
                                {
                                    try { p2 = pline.GetPoint2dAt(index + 1); }
                                    catch { p2 = pline.GetPoint2dAt(0); }
                                }

                                FullSubentityPath subId = new FullSubentityPath(
                                    new ObjectId[] { pline.ObjectId },
                                    new SubentityId(SubentityType.Edge,
                                                    new IntPtr((long)index + 1)));
                                pline.Highlight(subId, false);
                                ghost.AddVertexAt(0, p0, bulge, sWidth, 0.0);
                                ghost.AddVertexAt(1, p1, bulge, 0, eWidth);
                                ghost.AddVertexAt(2, p2, 0.0, 0.0, 0.0);
                                ghost.Normal    = pline.Normal;
                                ghost.Elevation = pline.Elevation;
                                VertexJig jig = new VertexJig(ghost, pickPt, 1, vec,
                                                              bulge, sWidth, eWidth);
                                PromptResult res = ed.Drag(jig);
                                if (res.Status == PromptStatus.OK)
                                {
                                    pline.UpgradeOpen();
                                    pline.SetStartWidthAt(index, ghost.GetStartWidthAt(1));
                                    pline.AddVertexAt(
                                        index + 1,
                                        ghost.GetPoint2dAt(1),
                                        ghost.GetBulgeAt(1),
                                        ghost.GetStartWidthAt(1),
                                        eWidth);
                                    pline.SetBulgeAt(index, ghost.GetBulgeAt(0));
                                }
                                pline.Unhighlight(subId, false);
                            }
                        }
                        trans.Commit();
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("\nError: " + ex.Message + ex.StackTrace);
                }
                finally
                {
                    ed.CurrentUserCoordinateSystem = UCS;
                }
            }
        }
Exemplo n.º 17
0
        public static ResultDTO plotTest(string id, string file, string fileID, bool isSnap = false)
        {
            try
            {
                Document doc = Application.DocumentManager.Open(file, false);
                Application.DocumentManager.MdiActiveDocument = doc;

                PlotSettings ps     = null; //声明增强型打印设置对象
                Layout       layout = null; //当前布局对象
                bool         isTile = AppConfig.GetAppSettings("ViewMode").ToLower().Trim() == "tilepicviewer";
                using (Transaction trans = doc.Database.TransactionManager.StartTransaction())
                {
                    LayoutManager lm = LayoutManager.Current;//获取当前布局管理器
                    layout = (Layout)GetLayoutId(doc.Database, lm.CurrentLayout).GetObject(OpenMode.ForRead);

                    ps = new PlotSettings(layout.ModelType);
                    ps.CopyFrom(layout);//从已有打印设置中获取打印设置

                    //0.更新打印设备、图纸尺寸和打印样式表信息
                    PlotSettingsValidator validator = PlotSettingsValidator.Current;
                    validator.RefreshLists(ps);
                    //1.设置打印驱动
                    string plotConfigurationName = AppConfig.GetAppSettings("Printer");
                    if (isSnap)
                    {
                        plotConfigurationName = "PublishToWeb JPG.pc3";
                    }
                    validator.SetPlotConfigurationName(ps, plotConfigurationName, null);

                    //2.设置打印纸张
                    StringCollection cMNameLst = validator.GetCanonicalMediaNameList(ps);
                    string           mediaName = AppConfig.GetAppSettings("CanonicalMediaName");
                    if (isSnap)
                    {
                        mediaName = "VGA (480.00 x 640.00 像素)";
                    }
                    bool             isHas = false;
                    StringCollection canonicalMediaNames = validator.GetCanonicalMediaNameList(ps);
                    foreach (string canonicalMediaName in canonicalMediaNames)
                    {
                        string localeMediaName = validator.GetLocaleMediaName(ps, canonicalMediaName);
                        if (localeMediaName == mediaName)
                        {
                            validator.SetCanonicalMediaName(ps, canonicalMediaName);
                            isHas = true;
                            break;
                        }
                    }
                    if (!isHas)
                    {
                        throw new System.Exception("纸张:" + mediaName + "不存在!");
                    }
                    //3.设置打印样式表
                    string plotStyleSheet = AppConfig.GetAppSettings("PlotStyleSheet");
                    validator.SetCurrentStyleSheet(ps, plotStyleSheet);

                    validator.SetPlotType(ps, Autodesk.AutoCAD.DatabaseServices.PlotType.Extents);
                    validator.SetPlotCentered(ps, true);
                    validator.SetUseStandardScale(ps, true);
                    validator.SetStdScaleType(ps, StdScaleType.ScaleToFit);//设置打印时布满图纸

                    validator.SetPlotRotation(ps, PlotRotation.Degrees000);
                    trans.Commit();
                }

                PlotConfig config = PlotConfigManager.CurrentConfig;
                doc = AcadApp.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;
                //获取去除扩展名后的文件名(不含路径)
                string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(doc.Name, "dwg");
                //存放在同目录下
                var basePath = AppConfig.GetAppSettings("CacheViewFilePath");
                if (!basePath.EndsWith("\\"))
                {
                    basePath += "\\";
                }

                int    num  = Convert.ToInt32(fileID) / 1000 + 1;
                string root = basePath + "Dwg\\" + string.Format("{0}", num.ToString("D8")) + "\\";
                if (!isTile)
                {
                    root = Path.Combine(basePath, string.Format("{0}", num.ToString("D8")) + "\\");
                }
                if (!Directory.Exists(@root))
                {
                    Directory.CreateDirectory(@root);
                }

                fileName = root + id + config.DefaultFileExtension;
                if (!isTile || isSnap)
                {
                    fileName = root + fileID + config.DefaultFileExtension;
                }

                //为了防止后台打印问题,必须在调用打印API时设置BACKGROUNDPLOT系统变量为0
                short backPlot = (short)AcadApp.GetSystemVariable("BACKGROUNDPLOT");
                AcadApp.SetSystemVariable("BACKGROUNDPLOT", 0);

                PlotEngine plotEngine = PlotFactory.CreatePublishEngine(); //创建一个打印引擎
                PlotInfo   pi         = new PlotInfo();                    //创建打印信息
                pi.Layout           = layout.ObjectId;                     //要打印的布局
                pi.OverrideSettings = ps;                                  //使用ps中的打印设置

                //验证打印信息是否有效
                PlotInfoValidator piv = new PlotInfoValidator();
                piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                piv.Validate(pi);

                PlotPageInfo ppi = new PlotPageInfo();
                plotEngine.BeginPlot(null, null);
                plotEngine.BeginDocument(pi, doc.Name, null, 1, true, fileName);
                plotEngine.BeginPage(ppi, pi, true, null);
                plotEngine.BeginGenerateGraphics(null);
                plotEngine.EndGenerateGraphics(null);
                plotEngine.EndPage(null);
                plotEngine.EndDocument(null);
                plotEngine.EndPlot(null);

                plotEngine.Destroy();//销毁打印引擎

                //恢复BACKGROUNDPLOT系统变量的值
                AcadApp.SetSystemVariable("BACKGROUNDPLOT", backPlot);

                doc.CloseAndDiscard();

                if (!File.Exists(fileName))
                {
                    throw new System.Exception("打印文件生成失败!");
                }

                ResultDTO reVal = new ResultDTO();
                if (isTile && !isSnap)//如果是图片就切图
                {
                    var img = new ZoomifyImage(fileName, 1024);
                    img.Zoomify(root + id + "\\");

                    reVal.status        = true;
                    reVal.DirectoryPath = "/" + id + "/";
                    reVal.ZoomLevel     = img.ZoomLevels - 1;
                }
                else
                {
                    reVal.status = true;
                }

                try
                {
                    //强制删除过程打印文件
                    if (File.Exists(file) && !isSnap)
                    {
                        File.Delete(file);
                    }
                }
                catch { }

                return(reVal);
            }
            catch (System.Exception e)
            {
                return(new ResultDTO
                {
                    status = false,
                    ErrInfo = e.Message,
                    FileName = file
                });
            }
        }
Exemplo n.º 18
0
        checkIfCurrent(string nameFile)
        {
            bool isCurrent = false;
            int  compare   = 0;

            bool         exists = false;
            ObjectId     idDict = Dict.getNamedDictionary("XRefNames", out exists);
            ResultBuffer rb     = Dict.getXRec(idDict, "XRefNames");

            TypedValue[] tvs       = rb.AsArray();
            DateTime     lastWrite = new DateTime();

            if (File.Exists(nameFile))
            {
                FileInfo fi = new FileInfo(nameFile);
                lastWrite = fi.LastWriteTime;
                string strLastWrite = lastWrite.ToString();
                lastWrite = System.Convert.ToDateTime(strLastWrite);
            }
            for (int i = 0; i < tvs.Length; i++)
            {
                if (tvs[i].Value.ToString() == nameFile)
                {
                    DateTime savedWrite = System.Convert.ToDateTime(tvs[i + 1].Value.ToString());
                    compare = lastWrite.CompareTo(savedWrite);
                    if (compare == 0)
                    {
                        isCurrent = true;
                    }
                    if (compare > 0)
                    {
                        isCurrent = false;
                    }
                    break;
                }
            }
            if (!isCurrent)
            {
                DimPL_Global.countUpdates = 0;
                Document workDoc   = Application.DocumentManager.MdiActiveDocument;
                string   nameUser  = "";
                int      dwgStatus = Base_Tools45.FileManager.getFileStatus(nameFile, out nameUser);
                switch (dwgStatus)
                {
                case (int)filestatus.isOpenLocal:
                    Document doc = FileManager.getDoc(nameFile, true, false);
                    Application.DocumentManager.MdiActiveDocument = doc;
                    Object dbMod = Application.GetSystemVariable("DBMOD");
                    if (System.Convert.ToInt16(dbMod) != 0)
                    {
                        doc.Database.SaveAs(doc.Name, true, DwgVersion.Current, doc.Database.SecurityParameters);
                    }
                    Application.DocumentManager.MdiActiveDocument = workDoc;
                    updateDimPL(nameFile);
                    break;

                case (int)filestatus.isOpenLocalReadOnly:
                    updateDimPL(nameFile);
                    break;

                case (int)filestatus.isLocked:
                    updateDimPL(nameFile);
                    break;

                case (int)filestatus.isAvailable:
                    updateDimPL(nameFile);
                    break;
                }
                if (DimPL_Global.countUpdates > 0)
                {
                    Application.ShowAlertDialog(string.Format("{0} DimPL updates were performed.", DimPL_Global.countUpdates));
                }
            }
        }
Exemplo n.º 19
0
        static void Zoom(Point3d pMin, Point3d pMax, Point3d pCenter, double dFactor)
        {
            // Get the current document and database
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            int nCurVport = System.Convert.ToInt32(Application.GetSystemVariable("CVPORT"));

            // Get the extents of the current space no points
            // or only a center point is provided
            // Check to see if Model space is current
            if (acCurDb.TileMode == true)
            {
                if (pMin.Equals(new Point3d()) == true &&
                    pMax.Equals(new Point3d()) == true)
                {
                    pMin = acCurDb.Extmin;
                    pMax = acCurDb.Extmax;
                }
            }
            else
            {
                // Check to see if Paper space is current
                if (nCurVport == 1)
                {
                    // Get the extents of Paper space
                    if (pMin.Equals(new Point3d()) == true &&
                        pMax.Equals(new Point3d()) == true)
                    {
                        pMin = acCurDb.Pextmin;
                        pMax = acCurDb.Pextmax;
                    }
                }
                else
                {
                    // Get the extents of Model space
                    if (pMin.Equals(new Point3d()) == true &&
                        pMax.Equals(new Point3d()) == true)
                    {
                        pMin = acCurDb.Extmin;
                        pMax = acCurDb.Extmax;
                    }
                }
            }

            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Get the current view
                using (ViewTableRecord acView = acDoc.Editor.GetCurrentView())
                {
                    Extents3d eExtents;

                    // Translate WCS coordinates to DCS
                    Matrix3d matWCS2DCS;
                    matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
                    matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
                    matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                                                   acView.ViewDirection,
                                                   acView.Target) * matWCS2DCS;

                    // If a center point is specified, define the min and max
                    // point of the extents
                    // for Center and Scale modes
                    if (pCenter.DistanceTo(Point3d.Origin) != 0)
                    {
                        pMin = new Point3d(pCenter.X - (acView.Width / 2),
                                           pCenter.Y - (acView.Height / 2), 0);

                        pMax = new Point3d((acView.Width / 2) + pCenter.X,
                                           (acView.Height / 2) + pCenter.Y, 0);
                    }

                    // Create an extents object using a line
                    using (Line acLine = new Line(pMin, pMax))
                    {
                        eExtents = new Extents3d(acLine.Bounds.Value.MinPoint,
                                                 acLine.Bounds.Value.MaxPoint);
                    }

                    // Calculate the ratio between the width and height of the current view
                    double dViewRatio;
                    dViewRatio = (acView.Width / acView.Height);

                    // Tranform the extents of the view
                    matWCS2DCS = matWCS2DCS.Inverse();
                    eExtents.TransformBy(matWCS2DCS);

                    double  dWidth;
                    double  dHeight;
                    Point2d pNewCentPt;

                    // Check to see if a center point was provided (Center and Scale modes)
                    if (pCenter.DistanceTo(Point3d.Origin) != 0)
                    {
                        dWidth  = acView.Width;
                        dHeight = acView.Height;

                        if (dFactor == 0)
                        {
                            pCenter = pCenter.TransformBy(matWCS2DCS);
                        }

                        pNewCentPt = new Point2d(pCenter.X, pCenter.Y);
                    }
                    else // Working in Window, Extents and Limits mode
                    {
                        // Calculate the new width and height of the current view
                        dWidth  = eExtents.MaxPoint.X - eExtents.MinPoint.X;
                        dHeight = eExtents.MaxPoint.Y - eExtents.MinPoint.Y;

                        // Get the center of the view
                        pNewCentPt = new Point2d(((eExtents.MaxPoint.X + eExtents.MinPoint.X) * 0.5),
                                                 ((eExtents.MaxPoint.Y + eExtents.MinPoint.Y) * 0.5));
                    }

                    // Check to see if the new width fits in current window
                    if (dWidth > (dHeight * dViewRatio))
                    {
                        dHeight = dWidth / dViewRatio;
                    }

                    // Resize and scale the view
                    if (dFactor != 0)
                    {
                        acView.Height = dHeight * dFactor;
                        acView.Width  = dWidth * dFactor;
                    }

                    // Set the center of the view
                    acView.CenterPoint = pNewCentPt;

                    // Set the current view
                    acDoc.Editor.SetCurrentView(acView);
                }

                // Commit the changes
                acTrans.Commit();
            }
        }
Exemplo n.º 20
0
        public void ImportEnvData()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // Local do arquivo de dados: O diretório do .dwg onde está sendo
            // executado o programa.
            string curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString();

            // Cria um StreamReader para ler o arquivo 'ida.txt', que contém os
            // dados para inserir os blocos.
            var fileData = new StreamReader(curDwgPath + "\\ida.txt");

            // Diretório dos arquivos '.dwg' dos blocos. Pois, caso o bloco
            // não exista no desenho atual, o programa irá procurar os blocos
            // em arquivos '.dwg' externos.
            String blkPath = curDwgPath;

            // Armazenará uma linha que será lida do 'ida.txt'
            string[] sFileLine;

            // Informações dos blocos, que serão lidos do 'ida.txt'
            string           sBlkId;
            string           sBlkName;
            Point3d          ptBlkOrigin;
            double           dbBlkRot;
            string           sLayer;
            string           sColor;
            ObjectId         idBlkTblRec = ObjectId.Null;
            BlockTableRecord blkTblRec   = null;

            string[] sBlkAtts;
            string[] oneAtt;
            string   blkTag;
            string   blkValue;
            Dictionary <string, string> dicBlkAtts = new Dictionary <string, string>();

            using (var tr = db.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                // O ModelSpace será usado para gravar em seu Extension Dictionary os Id's e os handles dos blocos.
                DBObject dbModelSpace = tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);

                using (BlockTableRecord acBlkTblRec = (BlockTableRecord)tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead))
                {
                    int contId = 0;
                    while (!fileData.EndOfStream)
                    {
                        // sFileLine é uma array que lê uma linha do 'ida.txt'
                        // tendo como separador de colunas ';'
                        sFileLine = fileData.ReadLine().Split(';');

                        // Atribui os parâmetros de cada bloco que será inserido
                        // baseado no 'ida.txt'
                        sBlkId   = Convert.ToString(contId);                         // O id não é declarado no 'ida.txt' pois este arquivo vem do matlab.
                        sBlkName = sFileLine[0];
                        dbBlkRot = (Math.PI / 180) * Convert.ToDouble(sFileLine[1]); // Converte graus para radiano
                        // Aqui é usado um Point3d pois é requisitado para criar um 'BlockReference' e não um Point2d.
                        ptBlkOrigin = new Point3d(Convert.ToDouble(sFileLine[2]), Convert.ToDouble(sFileLine[3]), 0);
                        sLayer      = sFileLine[4];
                        sColor      = sFileLine[5];
                        sBlkAtts    = sFileLine[6].Split(new string[] { "//" }, StringSplitOptions.None);

                        foreach (var sBlkAtt in sBlkAtts)
                        {
                            oneAtt   = sBlkAtt.Split(new string[] { "::" }, StringSplitOptions.None);
                            blkTag   = oneAtt[0];
                            blkValue = oneAtt[1];

                            dicBlkAtts.Add(blkTag, blkValue);
                        }

                        // Se o bloco não existe no desenho atual
                        if (!acBlkTbl.Has(sBlkName))
                        {
                            try
                            {
                                using (var blkDb = new Database(false, true))
                                {
                                    // Lê o '.dwg' do bloco, baseado no diretório especificado.
                                    blkDb.ReadDwgFile(blkPath + "/" + sBlkName + ".dwg", FileOpenMode.OpenForReadAndAllShare, true, "");

                                    // E então insere o bloco no banco de dados do desenho atual.
                                    // Mas ainda não está inserido no desenho.
                                    idBlkTblRec = db.Insert(sBlkName, blkDb, true); // Este método retorna o id do bloco.
                                }
                            }
                            catch // Expressão para pegar erros.
                            {
                            }
                        }
                        else
                        {
                            idBlkTblRec = acBlkTbl[sBlkName];
                        }

                        if (idBlkTblRec != ObjectId.Null)
                        {
                            blkTblRec = idBlkTblRec.GetObject(OpenMode.ForWrite) as BlockTableRecord;

                            using (var trColor = db.TransactionManager.StartOpenCloseTransaction())
                            {
                                // Altera a cor para "ByBlock"
                                foreach (ObjectId oId in blkTblRec)
                                {
                                    Entity ent = (Entity)trColor.GetObject(oId, OpenMode.ForWrite);
                                    ent.ColorIndex = 0;
                                }
                                trColor.Commit();
                            }

                            // Aqui o bloco será adicionado ao desenho e serão gravados
                            // seu id (identificação dada pelo programa atual, começando em 0 e incrementado 1 a 1)
                            // pareado ao seu handle, para o uso dos outros comandos.
                            using (BlockReference acBlkRef = new BlockReference(ptBlkOrigin, idBlkTblRec))
                            {
                                BlockTableRecord acCurSpaceBlkTblRec;
                                acCurSpaceBlkTblRec = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                                acCurSpaceBlkTblRec.AppendEntity(acBlkRef);
                                tr.AddNewlyCreatedDBObject(acBlkRef, true);
                                acBlkRef.Rotation   = dbBlkRot;
                                acBlkRef.Layer      = sLayer;
                                acBlkRef.ColorIndex = Convert.ToInt32(sColor);

                                // Início: Setar atributos do bloco ***********************************************************
                                if (blkTblRec.HasAttributeDefinitions)
                                {
                                    RXClass rxClass = RXClass.GetClass(typeof(AttributeDefinition));
                                    foreach (ObjectId idAttDef in blkTblRec)
                                    {
                                        if (idAttDef.ObjectClass == rxClass)
                                        {
                                            DBObject obj = tr.GetObject(idAttDef, OpenMode.ForRead);

                                            AttributeDefinition ad = obj as AttributeDefinition;
                                            AttributeReference  ar = new AttributeReference();
                                            ar.SetAttributeFromBlock(ad, acBlkRef.BlockTransform);

                                            if (dicBlkAtts.ContainsKey(ar.Tag))
                                            {
                                                ar.TextString = dicBlkAtts[ar.Tag];
                                            }


                                            acBlkRef.AttributeCollection.AppendAttribute(ar);
                                            tr.AddNewlyCreatedDBObject(ar, true);
                                        }
                                    }

                                    // Setar propriedades dos blocos dinâmicos
                                    if (acBlkRef.IsDynamicBlock)
                                    {
                                        DynamicBlockReferencePropertyCollection pc = acBlkRef.DynamicBlockReferencePropertyCollection;
                                        foreach (DynamicBlockReferenceProperty prop in pc)
                                        {
                                            if (dicBlkAtts.ContainsKey(prop.PropertyName))
                                            {
                                                // Propriedade de distância
                                                if (prop.PropertyTypeCode == 1)
                                                {
                                                    prop.Value = Convert.ToDouble(dicBlkAtts[prop.PropertyName]);
                                                }
                                                // Propriedade visibilidade
                                                else if (prop.PropertyTypeCode == 5)
                                                {
                                                    prop.Value = dicBlkAtts[prop.PropertyName];
                                                }
                                            }
                                        }
                                    }
                                }
                                // Fim: Setar atributos do bloco ************************************************************

                                Entity   eBlk  = (Entity)tr.GetObject(acBlkRef.Id, OpenMode.ForRead);
                                DBObject blkDb = (DBObject)tr.GetObject(acBlkRef.Id, OpenMode.ForRead);

                                // Grava o id(dado pelo programa - base 0) e o handle do bloco
                                // no Extension Dictionary do ModelSpace.
                                RecOnXDict(dbModelSpace, sBlkId, DxfCode.Handle, eBlk.Handle, tr);

                                // Grava o id do bloco em seu próprio Extension Dictionary, para fazer
                                // uma 'busca reversa' no XDic do ModelSpace depois.
                                RecOnXDict(blkDb, "id", DxfCode.XTextString, sBlkId, tr);
                            }
                        }
                        contId++;
                        dicBlkAtts.Clear();
                    }
                }
                fileData.Close();
                tr.Commit();
            }
        }
Exemplo n.º 21
0
        void tableRegDescr_CellPropertyChanged(object sender, XPTable.Events.CellEventArgs e)
        {
            // MessageBox.Show( e.CellPos.Column + "\n" + e.CellPos.Row + "\n" + e.Cell.Text + "\n" +  tableRegDescr.TableModel.Rows[e.CellPos.Row].Cells[0].Text + "\n" + e.OldValue);

            if (e.Column == 1)
            {
                if (tableRegDescr.TableModel.Rows[e.CellPos.Row].Cells[0].Text == " Density")
                {
                    RMS.Density = Convert.ToDouble(tableRegDescr.TableModel.Rows[15].Cells[1].Data);
                    RMS.G       = RMS.Density * RMS.LinearVolume;
                    tableRegDescr.TableModel.Rows[16].Cells[1].Data = RMS.G;
                    tableRegDescr.TableModel.Rows[17].Cells[1].Data = RMS.G;
                    tableRegDescr.TableModel.Rows[18].Cells[1].Data = RMS.G * 9.80665;
                }

                return;
            }

            UnitsValue UnitToConvertTo = UnitsValue.Millimeters;

            foreach (UnitsValue aUnit in Enum.GetValues(typeof(UnitsValue)))
            {
                if (aUnit.ToString() == e.Cell.Text)
                {
                    UnitToConvertTo = aUnit;
                }
            }

            string     checkStr        = tableRegDescr.TableModel.Rows[e.CellPos.Row].Cells[0].Text;
            UnitsValue scaleUnitsValue = UnitsValue.Millimeters;
            string     sysUnits        = (Application.GetSystemVariable("INSUNITS")).ToString();

            switch (sysUnits)
            {
            case "1":
                scaleUnitsValue = UnitsValue.Inches;
                break;

            case "2":
                scaleUnitsValue = UnitsValue.Feet;
                break;

            case "4":
                scaleUnitsValue = UnitsValue.Millimeters;
                break;

            case "5":
                scaleUnitsValue = UnitsValue.Centimeters;
                break;

            case "6":
                scaleUnitsValue = UnitsValue.Meters;
                break;

            case "14":
                scaleUnitsValue = UnitsValue.Decimeters;
                break;

            default:
                MessageBox.Show("\nUnits to scale inserted content: UNRECOGNIZED ?!", "units E R R O R");
                break;
            }
            switch (checkStr.Remove(0, 1) /*tableRegDescr.TableModel.Rows[e.CellPos.Row].Cells[0].Text*/)
            {
            case "Area":
                RMS.AreaUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[0].Cells[1].Data = RMS.Area *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.AreaUnit), 2);
                break;

            case "Iy":
                RMS.IyUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[1].Cells[1].Data = RMS.Iy *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.IyUnit), 4);
                break;

            case "Wy_Upper":
                RMS.WyUpperUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[2].Cells[1].Data = RMS.WyUpper *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.WyUpperUnit), 3);
                break;

            case "Wy_Lower":
                RMS.WyLowerUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[3].Cells[1].Data = RMS.WyLower *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.WyLowerUnit), 3);
                break;

            case "D_Upper":
                RMS.DUpperUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[4].Cells[1].Data = RMS.DUpper *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.DUpperUnit), 1);
                break;

            case "D_Lower":
                RMS.DLowerUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[5].Cells[1].Data = RMS.DLower *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.DLowerUnit), 1);
                break;

            case "Iyy":
                RMS.IyyUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[6].Cells[1].Data = RMS.Iyy *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.IyyUnit), 1);
                break;

            case "Iz":
                RMS.IzUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[7].Cells[1].Data = RMS.Iz *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.IzUnit), 4);
                break;

            case "Wz_Right":
                RMS.WzRightUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[8].Cells[1].Data = RMS.WzRight *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.WzRightUnit), 3);
                break;

            case "Wz_Left":
                RMS.WzLeftUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[9].Cells[1].Data = RMS.WzLeft *
                                                                 Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.WzLeftUnit), 3);
                break;

            case "D_Right":
                RMS.DRightUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[10].Cells[1].Data = RMS.DRight *
                                                                  Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.DRightUnit), 1);
                break;

            case "D_Left":
                RMS.DLeftUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[11].Cells[1].Data = RMS.DLeft *
                                                                  Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.DLeftUnit), 1);
                break;

            case "Izz":
                RMS.IzzUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[12].Cells[1].Data = RMS.Izz *
                                                                  Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.IzzUnit), 1);
                break;

            case "Imin":
                RMS.IminUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[13].Cells[1].Data = RMS.Imin *
                                                                  Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.IminUnit), 4);
                break;

            case "Imax":
                RMS.ImaxUnit = UnitToConvertTo;
                tableRegDescr.TableModel.Rows[14].Cells[1].Data = RMS.Imax *
                                                                  Math.Pow(
                    UnitsConverter.GetConversionFactor(
                        scaleUnitsValue, RMS.ImaxUnit), 4);
                break;
                // case "Density":
                // RMS.DensityUnit = UnitToConvertTo;
                //  break;
                //   case "G":
                //RMS.GUnit = UnitToConvertTo;
                //     break;
                //   case "LinearVolume":
                //     RMS.LinearVolumeUnit = UnitToConvertTo;
                //    break;
            }

            // RegionDescription.DrawText( ref RMS );
        }
Exemplo n.º 22
0
        private void SetSystemVariable(string name, string value, bool isReWrite)
        {
            object nameVar = null;

            try
            {
                nameVar = AutoCadApp.GetSystemVariable(name);
            }
            catch
            {
                return;
            }

            if (name.ToUpper() == "TRUSTEDPATHS")
            {
                var paths = value.Split(';').Select(p => Path.Combine(_localSettingsFolder, p));
                value = String.Join(";", paths);
                if (isReWrite)
                {
                    nameVar = value;
                }
                else
                {
                    nameVar = getOnlyExistsPaths(nameVar?.ToString(), "TRUSTEDPATHS");
                    if (string.IsNullOrEmpty(nameVar?.ToString()))
                    {
                        nameVar = value;
                    }
                    else
                    {
                        nameVar += ";" + value;
                    }
                }
                nameVar = getOnlyExistsPaths(nameVar?.ToString(), "TRUSTEDPATHS");
                try
                {
                    Log.Info("TRUSTEDPATHS = {0}", nameVar);
                }
                catch { }
            }
            else
            {
                if (isReWrite)
                {
                    nameVar = value;
                }
                else
                {
                    if ((nameVar == null) || (Convert.ToString(nameVar) == ""))
                    {
                        nameVar = value;
                    }
                    else if (!value.ToUpper().Contains((nameVar.ToString().Remove(nameVar.ToString().Length - 1, 1)).ToUpper()))
                    {
                        nameVar += ";" + value;
                    }
                }
            }

            try
            {
                AutoCadApp.SetSystemVariable(name, nameVar);
            }
            catch
            {
                try
                {
                    AutoCadApp.SetSystemVariable(name, Convert.ToInt16(nameVar));
                }
                catch (Exception ex)
                {
                    try
                    {
                        Log.Error(ex, $"SetSystemVariable {name}");
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 23
0
        public static void ZoomExtents(Point3d P1, Point3d P2, double dFactor)
        {
            #region 포인트 지정 [P1, P2, P3]
            //var P1 = new Point3d();
            //var P2 = new Point3d();
            var P3 = GetCenterPoint3d(P1, P2);

            int nCurVport = System.Convert.ToInt32(Application.GetSystemVariable("CVPORT"));

            /// 포인트가 없을 경우 따로 포인트 범위를 지정해줘야한다.
            if (DB.TileMode == true)
            {
                if (P1.IsEqualTo(new Point3d()) && P2.IsEqualTo(new Point3d()))
                {
                    P1 = DB.Extmin; // Extents Space
                    P2 = DB.Extmax;
                }
            }
            else
            {
                if (nCurVport == 1)
                {
                    if (P1.IsEqualTo(new Point3d()) && P2.IsEqualTo(new Point3d()))
                    {
                        P1 = DB.Pextmin;    // Paper Space
                        P2 = DB.Pextmax;
                    }
                }
                else
                {
                    if (P1.IsEqualTo(new Point3d()) && P2.IsEqualTo(new Point3d()))
                    {
                        P1 = DB.Extmin;
                        P2 = DB.Extmax;
                    }
                }
            }
            #endregion

            using (Transaction T = DB.TransactionManager.StartTransaction())
            {
                using (ViewTableRecord VTR = Doc.Editor.GetCurrentView())
                {
                    Extents3d extents;

                    // Translate WCS coordinates to DCS
                    Matrix3d matrix;
                    matrix = Matrix3d.PlaneToWorld(VTR.ViewDirection);
                    matrix = Matrix3d.Displacement(VTR.Target - Point3d.Origin) * matrix;
                    matrix = Matrix3d.Rotation(-VTR.ViewTwist, VTR.ViewDirection, VTR.Target) * matrix;

                    if (P3.IsEqualTo(Point3d.Origin))
                    {
                        P1 = new Point3d(P3.X - (VTR.Width / 2), P3.Y - (VTR.Height / 2), 0);
                        P2 = new Point3d((VTR.Width) / 2 * P3.X, (VTR.Height / 2) + P3.Y, 0);
                    }

                    using (var L = new Line(P1, P2))
                    {
                        extents = new Extents3d(L.Bounds.Value.MinPoint, L.Bounds.Value.MaxPoint);
                    }

                    double V_Ratio = VTR.Width / VTR.Height;

                    matrix = matrix.Inverse();
                    extents.TransformBy(matrix);

                    double  W;
                    double  H;
                    Point2d NewCenP;

                    if (!P3.IsEqualTo(Point3d.Origin))
                    {
                        W = VTR.Width;
                        H = VTR.Height;

                        if (dFactor == 0)
                        {
                            P3 = P3.TransformBy(matrix);
                        }

                        NewCenP = new Point2d(P3.X, P3.Y);
                    }
                    else
                    {
                        W = extents.MaxPoint.X - extents.MinPoint.X;
                        H = extents.MaxPoint.Y - extents.MinPoint.Y;

                        NewCenP = new Point2d((extents.MaxPoint.X + extents.MinPoint.X) * 0.5, (extents.MaxPoint.Y + extents.MinPoint.Y) * 0.5);
                    }

                    if (W > (H * V_Ratio))
                    {
                        H = H / V_Ratio;
                    }
                    if (dFactor != 0)
                    {
                        VTR.Height = H * dFactor;
                        VTR.Width  = W * dFactor;
                    }

                    VTR.CenterPoint = NewCenP;

                    ED.SetCurrentView(VTR);
                }

                T.Commit();
            }
        }
Exemplo n.º 24
0
        public void ReadBlocksData()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // Diretório do desenho atual que chamou o comando.
            string curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString();

            // Arquivo onde será escrito os dados obtidos.
            StreamWriter fileOut = new StreamWriter(curDwgPath + "\\blocksData.txt");

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var      BlkTbl       = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
                var      BlkTblRec    = (BlockTableRecord)tr.GetObject(BlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                var      dbModelSpace = (DBObject)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);
                ObjectId extId        = dbModelSpace.ExtensionDictionary;
                var      dbExt        = (DBDictionary)tr.GetObject(extId, OpenMode.ForRead);

                PromptSelectionResult acSSRes = ed.GetSelection();
                if (acSSRes.Status == PromptStatus.OK)
                {
                    SelectionSet acSSet = acSSRes.Value;

                    foreach (SelectedObject selectedObject in acSSet)
                    {
                        // Início: Pega o id guardado em seu XDic******************************************************
                        var blkRef = (BlockReference)tr.GetObject(selectedObject.ObjectId, OpenMode.ForRead);

                        // Se o bloco não tem XDic, cria-o e já grava o dado
                        if (blkRef.ExtensionDictionary == ObjectId.Null)
                        {
                            blkRef.UpgradeOpen();
                            RecOnXDict(blkRef, "id", DxfCode.XTextString, dbExt.Count.ToString(), tr);
                            RecOnXDict(dbModelSpace, dbExt.Count.ToString(), DxfCode.Handle, blkRef.Handle, tr);
                        }

                        var          blkDic   = (DBDictionary)tr.GetObject(blkRef.ExtensionDictionary, OpenMode.ForRead);
                        var          xRecBlk  = (Xrecord)tr.GetObject(blkDic.GetAt("id"), OpenMode.ForRead);
                        ResultBuffer rb       = xRecBlk.Data;
                        TypedValue[] xRecData = rb.AsArray();
                        string       sBlkId   = xRecData[0].Value.ToString();
                        // Fim: Pega o id guardado em seu XDic*************************************************************************************

                        // Início: checa se o id do bloco confere com o handle registrado no MS ***************************************************
                        var blkRef2 = GetRefBlkFromIndex(db, dbExt, sBlkId);

                        if (blkRef.Id != blkRef2.Id)
                        {
                            RecOnXDict(blkRef, "id", DxfCode.XTextString, dbExt.Count.ToString(), tr);
                            RecOnXDict(dbModelSpace, dbExt.Count.ToString(), DxfCode.Handle, blkRef.Handle, tr);
                        }
                        // Fim: checa se o id do bloco confere com o handle registrado no MS ******************************************************

                        string blkName = blkRef.Name;

                        // Se é bloco dinamico, a forma de pegar o nome do bloco
                        // é desse jeito:
                        BlockTableRecord realBlock = null;
                        string           atts      = "";
                        if (blkRef.IsDynamicBlock)
                        {
                            realBlock = (BlockTableRecord)tr.GetObject(blkRef.DynamicBlockTableRecord, OpenMode.ForRead);
                            blkName   = realBlock.Name;

                            // Le os atributos do bloco
                            if (realBlock.HasAttributeDefinitions)
                            {
                                var     blkRefAtts = (AttributeCollection)blkRef.AttributeCollection;
                                RXClass rxClass    = RXClass.GetClass(typeof(AttributeReference));
                                foreach (ObjectId idAttDef in blkRefAtts)
                                {
                                    if (idAttDef.ObjectClass == rxClass)
                                    {
                                        AttributeReference obj = (AttributeReference)tr.GetObject(idAttDef, OpenMode.ForRead);

                                        atts += obj.Tag + "::" + obj.TextString + "//";
                                    }
                                }
                            }
                        }

                        double blkRot   = blkRef.Rotation * (180 / Math.PI);
                        string blkX     = blkRef.Position.X.ToString("n2");
                        string blkY     = blkRef.Position.Y.ToString("n2");
                        string blkLayer = blkRef.Layer;
                        string blkColor = Convert.ToString(blkRef.ColorIndex);

                        fileOut.WriteLine(sBlkId + ";" + blkName + ";" + blkRot + ";" + blkX + ";" + blkY + ";"
                                          + blkLayer + ";" + blkColor + ";" + atts + ";");
                    }
                }

                fileOut.Close();
                tr.Commit();
            }
        }
Exemplo n.º 25
0
        public void ConnectConduits()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // Local do arquivo de dados
            // ***************************************************************************************************************************
            //string curDwgPath = Directory.GetCurrentDirectory();
            string curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString();
            var    fileData   = new StreamReader(curDwgPath + "\\let.txt");

            // ***************************************************************************************************************************

            string[]      sLine;
            List <string> lLine = new List <string>();

            using (var tr = db.TransactionManager.StartTransaction())
            {
                BlockTable       BlkTbl       = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                BlockTableRecord BlkTblRec    = tr.GetObject(BlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                DBObject         dbModelSpace = tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);
                ObjectId         extId        = dbModelSpace.ExtensionDictionary;
                DBDictionary     dbExt        = (DBDictionary)tr.GetObject(extId, OpenMode.ForRead);
                Point3d          ptAux;
                Point2d          ptVert;
                int indexVert;
                int lineColor = -1;

                while (!fileData.EndOfStream)
                {
                    sLine     = fileData.ReadLine().Split(';');
                    indexVert = 0;

                    foreach (string value in sLine)
                    {
                        if (value != "")
                        {
                            lLine.Add(value);
                        }
                    }

                    lineColor = Convert.ToInt32(lLine.Last());
                    lLine.RemoveAt(lLine.Count - 1);

                    using (Polyline oPLine = new Polyline())
                    {
                        // address pode ser um index ou um ponto
                        foreach (string address in lLine)
                        {
                            if (address != "")
                            {
                                // Se tem vírgula é um ponto, onde suas coordenadas
                                // são separadas por uma vírgula.
                                if (address.Contains(','))
                                {
                                    string[] coords = address.Split(',');
                                    ptVert = new Point2d(Convert.ToDouble(coords[0]), Convert.ToDouble(coords[1]));
                                }
                                // Se não tem vírgula, é um index,
                                // na qual é usado o método 'GetRefBlkFromIndex'
                                // para pegar o ponto do bloco.
                                else
                                {
                                    ptAux  = GetRefBlkFromIndex(db, dbExt, address).Position;
                                    ptVert = new Point2d(ptAux.X, ptAux.Y);
                                }

                                oPLine.AddVertexAt(indexVert, ptVert, 0, 0, 0);
                                indexVert++;
                            }
                        }
                        oPLine.ColorIndex = lineColor;
                        BlkTblRec.AppendEntity(oPLine);
                        tr.AddNewlyCreatedDBObject(oPLine, true);
                    }
                    lLine.Clear();
                }
                tr.Commit();
            }
        }
Exemplo n.º 26
0
 public PlotMultiPDF()
 {
     _bgp = (short)AcAp.GetSystemVariable("BACKGROUNDPLOT");
     AcAp.SetSystemVariable("BACKGROUNDPLOT", 0);
     Application.Publisher.CancelledOrFailedPublishing += Publisher_CancelledOrFailedPublishing;
 }
Exemplo n.º 27
0
        public void Main()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                #region Create selection set filter
                // Cria uma array do tipo TypedValue de tamanho 1
                TypedValue[] acTypValAr = new TypedValue[1];

                // Atribui o valor do index 0, este valor é um par ordenado
                // DxfCode.Start é o tipo (Objeto) e o "LWPOLYLINE" especifica que o
                // objeto a ser selecionado é uma polyline.
                acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "LWPOLYLINE"), 0);
                //acTypValAr.SetValue(new TypedValue((int)DxfCode.LayerName, "LANG-PAREDE"), 1);

                // Atribui o array de par ordenado ao filtro de seleção
                SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);
                #endregion

                // Cria o selection set e pede ao usuário para selecionar
                // através do método GetSelection
                PromptSelectionResult acSSPrompt = ed.GetSelection(acSelFtr);

                // Se a seleção estiver OK, quer dizer que
                // os objetos foram selecionados
                if (acSSPrompt.Status == PromptStatus.OK)
                {
                    string            curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString();
                    string            csvPath    = curDwgPath + "\\pontos-do-ambiente.csv";
                    FileStream        fileCsv    = new FileStream(csvPath, FileMode.Create);
                    StreamWriter      strWrt     = new StreamWriter(fileCsv, Encoding.UTF8);
                    SelectionSet      acSSet     = acSSPrompt.Value;
                    Polyline          objPoly;
                    Point3dCollection acPt3dCol;
                    MText             objMText;
                    string            sTipo;
                    string            sDesc = "";
                    int id = 0;

                    strWrt.WriteLine("id;tipo;desc;coord x;coord y");

                    foreach (SelectedObject aObj in acSSet)
                    {
                        objPoly = tr.GetObject(aObj.ObjectId, OpenMode.ForRead) as Polyline;

                        if (objPoly.Layer.Length > 5)
                        {
                            sTipo     = objPoly.Layer.ToString().Substring(5);
                            acPt3dCol = GetCoordsOf(objPoly);

                            acTypValAr = new TypedValue[2];
                            acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "MTEXT"), 0);
                            acTypValAr.SetValue(new TypedValue((int)DxfCode.Text, "[A-Z]*"), 1);

                            acSelFtr   = new SelectionFilter(acTypValAr);
                            acSSPrompt = ed.SelectWindowPolygon(acPt3dCol, acSelFtr);

                            if (acSSPrompt.Status == PromptStatus.OK)
                            {
                                SelectionSet acSSInsideEnv = acSSPrompt.Value;
                                ObjectId[]   idMText       = new ObjectId[acSSInsideEnv.Count];
                                idMText = acSSInsideEnv.GetObjectIds();

                                objMText = tr.GetObject(idMText[0], OpenMode.ForRead) as MText;
                                sDesc    = objMText.Text;
                            }

                            // Escreve os dados do ambiente no arquivo
                            strWrt.Write(id + ";" + sTipo + ";" + sDesc + ";");
                            foreach (Point3d pt in acPt3dCol)
                            {
                                strWrt.Write(" " + pt.X.ToString("n2") + ",");
                            }
                            strWrt.Write(";");
                            foreach (Point3d pt in acPt3dCol)
                            {
                                strWrt.Write(" " + pt.Y.ToString("n2") + ",");
                            }
                            strWrt.WriteLine(";");

                            id++;
                        }
                    }

                    ed.WriteMessage("Arquivo criado em: " + csvPath);
                    strWrt.Close();
                }
                tr.Commit();
            }
        }
Exemplo n.º 28
0
        private static void DrawDwg(double a, double b, double daD, double r)
        {
            string   sLocalRoot    = Application.GetSystemVariable("LOCALROOTPREFIX") as string;
            string   sTemplatePath = sLocalRoot + "Template\\acad.dwt";
            Document doc           = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.Add(sTemplatePath);
            Database db            = doc.Database;
            Editor   ed            = doc.Editor;

            using (DocumentLock docLock = doc.LockDocument())
            {
                using (var trans = doc.TransactionManager.StartTransaction())
                {
                    Tools.AddLayer(db, "Contour_Layer", 7, "Continuous", "外轮廓图层");
                    Tools.AddLayer(db, "Dim_Layer", 7, "Continuous", "外轮廓图层");
                    Tools.AddLayer(db, "CenterLine_Layer", 1, "CENTER", "中心线图层");
                    var DimstyleId = Tools.AddDimStyle(db, "myDimStyle");


                    BlockTable       blockTable = trans.GetObject(doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord space      = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    //外框
                    Polyline waiKuang1 = new Polyline();
                    waiKuang1.AddVertexAt(waiKuang1.NumberOfVertices, new Point2d(-b / 2, daD / 2 - r), -Math.PI / 8, 0, 0);//左上角边框 ,顺时针
                    waiKuang1.AddVertexAt(waiKuang1.NumberOfVertices, new Point2d(-b / 2 + r, daD / 2), 0, 0, 0);
                    waiKuang1.AddVertexAt(waiKuang1.NumberOfVertices, new Point2d(b / 2 - r, daD / 2), -Math.PI / 8, 0, 0);
                    waiKuang1.AddVertexAt(waiKuang1.NumberOfVertices, new Point2d(b / 2, daD / 2 - r), 0, 0, 0);
                    waiKuang1.AddVertexAt(waiKuang1.NumberOfVertices, new Point2d(b / 2, -(daD / 2 - r)), -Math.PI / 8, 0, 0);//右下
                    waiKuang1.AddVertexAt(waiKuang1.NumberOfVertices, new Point2d(b / 2 - r, -(daD / 2)), 0, 0, 0);
                    waiKuang1.AddVertexAt(waiKuang1.NumberOfVertices, new Point2d(-(b / 2 - r), -(daD / 2)), -Math.PI / 8, 0, 0);
                    waiKuang1.AddVertexAt(waiKuang1.NumberOfVertices, new Point2d(-(b / 2), -(daD / 2 - r)), 0, 0, 0);
                    waiKuang1.Closed     = true;
                    waiKuang1.LineWeight = LineWeight.LineWeight050;
                    waiKuang1.Layer      = "Contour_Layer";
                    //中心线
                    Line centerLine = new Line(new Point3d(-b / 2 - 2, 0, 0), new Point3d(b / 2 + 2, 0, 0));
                    centerLine.Layer         = "CenterLine_Layer";
                    centerLine.LinetypeScale = 0.1;
                    //球
                    Circle Qiu = new Circle(new Point3d(0, (daD / 2 - a / 2), 0), Vector3d.ZAxis, a / 4);
                    Qiu.LineWeight = LineWeight.LineWeight050;
                    Qiu.Layer      = "Contour_Layer";
                    //球中心线
                    Line centerLine1 = new Line(new Point3d(-b / 2 - 2, (daD / 2 - a / 2), 0), new Point3d(b / 2 + 2, (daD / 2 - a / 2), 0));
                    centerLine1.Layer         = "CenterLine_Layer";
                    centerLine1.LinetypeScale = 0.1;
                    //竖着
                    Line centerLine2 = new Line(new Point3d(0, (daD / 2 - a / 2) + (a / 2 + 2), 0), new Point3d(0, (daD / 2 - a / 2) - (a / 2 + 2), 0));
                    centerLine2.Layer         = "CenterLine_Layer";
                    centerLine2.LinetypeScale = 0.1;
                    //下面十字横着
                    Line centerLine3 = new Line(new Point3d(-b / 2 + 1, -(daD / 2 - a / 2), 0), new Point3d(b / 2 - 1, -(daD / 2 - a / 2), 0));
                    //下面十字竖着
                    centerLine3.Layer = "Contour_Layer";
                    Line centerLine4 = new Line(new Point3d(0, -(daD / 2 - a / 2) + (a / 2 - 1), 0), new Point3d(0, -(daD / 2 - a / 2) - (a / 2 - 1), 0));
                    centerLine4.Layer = "Contour_Layer";

                    //下孔轮廓
                    Polyline kongLunKuoXia = new Polyline();
                    kongLunKuoXia.AddVertexAt(kongLunKuoXia.NumberOfVertices, new Point2d(-b / 2, -(daD - 2 * a) / 2 - r), -Math.PI / 8, 0, 0);
                    kongLunKuoXia.AddVertexAt(kongLunKuoXia.NumberOfVertices, new Point2d(-b / 2 + r, -(daD - 2 * a) / 2), 0, 0, 0);
                    kongLunKuoXia.AddVertexAt(kongLunKuoXia.NumberOfVertices, new Point2d(b / 2 - r, -(daD - 2 * a) / 2), -Math.PI / 8, 0, 0);
                    kongLunKuoXia.AddVertexAt(kongLunKuoXia.NumberOfVertices, new Point2d(b / 2, -(daD - 2 * a) / 2 - r), 0, 0, 0);
                    kongLunKuoXia.LineWeight = LineWeight.LineWeight050;
                    Polyline kongLunKuoShang = (Polyline)kongLunKuoXia.GetTransformedCopy(Matrix3d.Mirroring(new Plane(Point3d.Origin, Vector3d.YAxis)));
                    kongLunKuoShang.LineWeight = LineWeight.LineWeight050;
                    //圆珠截取点

                    double x     = a / 4 * Math.Cos(Math.PI / 6);
                    double y     = a / 4 * Math.Sin(Math.PI / 6);
                    Line   line1 = new Line(new Point3d(x, daD / 2 - a / 2 + y, 0), new Point3d(b / 2, daD / 2 - a / 2 + y, 0));
                    Line   line2 = new Line(new Point3d(x, daD / 2 - a / 2 - y, 0), new Point3d(b / 2, daD / 2 - a / 2 - y, 0));

                    Line line3 = new Line(new Point3d(-x, daD / 2 - a / 2 + y, 0), new Point3d(-b / 2, daD / 2 - a / 2 + y, 0));
                    Line line4 = new Line(new Point3d(-x, daD / 2 - a / 2 - y, 0), new Point3d(-b / 2, daD / 2 - a / 2 - y, 0));
                    line1.LineWeight = LineWeight.LineWeight050;
                    line2.LineWeight = LineWeight.LineWeight050;
                    line3.LineWeight = LineWeight.LineWeight050;
                    line4.LineWeight = LineWeight.LineWeight050;

                    line1.Layer = "Contour_Layer";
                    line2.Layer = "Contour_Layer";
                    line3.Layer = "Contour_Layer";
                    line4.Layer = "Contour_Layer";



                    //面域
                    Polyline waiKuang = new Polyline();
                    waiKuang.AddVertexAt(waiKuang.NumberOfVertices, new Point2d(-b / 2, daD / 2 - r), -Math.PI / 8, 0, 0);//左上角边框 ,顺时针
                    waiKuang.AddVertexAt(waiKuang.NumberOfVertices, new Point2d(-b / 2 + r, daD / 2), 0, 0, 0);
                    waiKuang.AddVertexAt(waiKuang.NumberOfVertices, new Point2d(b / 2 - r, daD / 2), -Math.PI / 8, 0, 0);
                    waiKuang.AddVertexAt(waiKuang.NumberOfVertices, new Point2d(b / 2, daD / 2 - r), 0, 0, 0);
                    waiKuang.AddVertexAt(waiKuang.NumberOfVertices, new Point2d(b / 2, daD / 2 - a / 2 + y), 0, 0, 0);
                    waiKuang.AddVertexAt(waiKuang.NumberOfVertices, new Point2d(-b / 2, daD / 2 - a / 2 + y), 0, 0, 0);
                    waiKuang.Closed = true;

                    Polyline waiKuang2 = new Polyline();
                    waiKuang2.AddVertexAt(waiKuang2.NumberOfVertices, new Point2d(-b / 2, daD / 2 - a / 2 - y), 0, 0, 0);
                    waiKuang2.AddVertexAt(waiKuang2.NumberOfVertices, new Point2d(b / 2, daD / 2 - a / 2 - y), 0, 0, 0);
                    waiKuang2.AddVertexAt(waiKuang2.NumberOfVertices, new Point2d(b / 2, -(daD / 2 - r) + (daD - a)), -Math.PI / 8, 0, 0);//右下
                    waiKuang2.AddVertexAt(waiKuang2.NumberOfVertices, new Point2d(b / 2 - r, -(daD / 2) + (daD - a)), 0, 0, 0);
                    waiKuang2.AddVertexAt(waiKuang2.NumberOfVertices, new Point2d(-(b / 2 - r), -(daD / 2) + (daD - a)), -Math.PI / 8, 0, 0);
                    waiKuang2.AddVertexAt(waiKuang2.NumberOfVertices, new Point2d(-(b / 2), -(daD / 2 - r) + (daD - a)), 0, 0, 0);
                    waiKuang2.Closed = true;


                    var regin1 = Tools.CreaterRegion(waiKuang)[0];
                    var regin2 = Tools.CreaterRegion(Qiu)[0];
                    var regin3 = Tools.CreaterRegion(waiKuang2)[0];
                    var regin4 = Tools.CreaterRegion(Qiu)[0];

                    regin1.BooleanOperation(BooleanOperationType.BoolSubtract, regin2);
                    regin3.BooleanOperation(BooleanOperationType.BoolSubtract, regin4);

                    var id8 = space.AppendEntity(regin1);
                    trans.AddNewlyCreatedDBObject(regin1, true);
                    var id9 = space.AppendEntity(regin3);
                    trans.AddNewlyCreatedDBObject(regin3, true);
                    //填充
                    Hatch hatch = new Hatch();

                    space.AppendEntity(hatch);
                    trans.AddNewlyCreatedDBObject(hatch, true);

                    hatch.SetDatabaseDefaults();
                    hatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");//ANSI31为金属剖面线

                    hatch.Associative = true;
                    ObjectIdCollection acObjIdColl = new ObjectIdCollection();
                    acObjIdColl.Add(id8);

                    hatch.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl);

                    hatch.EvaluateHatch(true);

                    //填充
                    Hatch hatch2 = new Hatch();

                    space.AppendEntity(hatch2);
                    trans.AddNewlyCreatedDBObject(hatch2, true);

                    hatch2.SetDatabaseDefaults();
                    hatch2.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");//ANSI31为金属剖面线

                    hatch2.Associative = true;
                    ObjectIdCollection acObjIdColl2 = new ObjectIdCollection();
                    acObjIdColl2.Add(id9);

                    hatch2.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl2);

                    hatch2.EvaluateHatch(true);


                    //标注
                    addHorizonRotatedDimension(db, new Point3d(-b / 2, daD / 2, 0), new Point3d(b / 2, daD / 2, 0), 1.5, DimstyleId);
                    addHorizonRotatedDimension(db, new Point3d(0, daD / 2, 0), new Point3d(b / 2, daD / 2, 0), 0.5, DimstyleId);

                    addVerticalRotatedDimension(db, new Point3d(-b / 2, -(daD - 2 * a) / 2, 0), new Point3d(-b / 2, (daD - 2 * a) / 2, 0), -1.5, DimstyleId);
                    addVerticalRotatedDimension(db, new Point3d(-b / 2, daD / 2, 0), new Point3d(-b / 2, (daD - 2 * a) / 2, 0), -1.5, DimstyleId);
                    addVerticalRotatedDimension(db, new Point3d(-b / 2, daD / 2 - a / 2 - y, 0), new Point3d(-b / 2, daD / 2 - a / 2 + y, 0), -0.5, DimstyleId);


                    addVerticalRotatedDimension(db, new Point3d(b / 2, daD / 2, 0), new Point3d(b / 2, daD / 2 - a / 2, 0), 1, DimstyleId);
                    addVerticalRotatedDimension(db, new Point3d(b / 2, daD / 2, 0), new Point3d(b / 2, -daD / 2, 0), 2, DimstyleId);

                    addDiametricDimension(db, new Point3d(0, daD / 2 - a / 2, 0), new Point3d(0, daD / 2 - a / 2, 0), new Point3d(0, daD / 2 - a, 0), new Point3d(-x, daD / 2 - a / 2 - y, 0), 0.2, DimstyleId);

                    var id7 = space.AppendEntity(line1);
                    trans.AddNewlyCreatedDBObject(line1, true);
                    var id6 = space.AppendEntity(line2);
                    trans.AddNewlyCreatedDBObject(line2, true);
                    var id5 = space.AppendEntity(line3);
                    trans.AddNewlyCreatedDBObject(line3, true);
                    var id4 = space.AppendEntity(line4);
                    trans.AddNewlyCreatedDBObject(line4, true);

                    kongLunKuoXia.Layer   = "Contour_Layer";
                    kongLunKuoShang.Layer = "Contour_Layer";

                    var id3 = space.AppendEntity(kongLunKuoShang);
                    trans.AddNewlyCreatedDBObject(kongLunKuoShang, true);

                    space.AppendEntity(kongLunKuoXia);
                    trans.AddNewlyCreatedDBObject(kongLunKuoXia, true);

                    space.AppendEntity(centerLine3);
                    trans.AddNewlyCreatedDBObject(centerLine3, true);

                    space.AppendEntity(centerLine4);
                    trans.AddNewlyCreatedDBObject(centerLine4, true);

                    space.AppendEntity(centerLine1);
                    trans.AddNewlyCreatedDBObject(centerLine1, true);

                    space.AppendEntity(centerLine2);
                    trans.AddNewlyCreatedDBObject(centerLine2, true);

                    space.AppendEntity(centerLine);
                    trans.AddNewlyCreatedDBObject(centerLine, true);

                    var id2 = space.AppendEntity(Qiu);
                    trans.AddNewlyCreatedDBObject(Qiu, true);

                    var id1 = space.AppendEntity(waiKuang1);
                    trans.AddNewlyCreatedDBObject(waiKuang1, true);


                    trans.Commit();
                }
            }
        }
Exemplo n.º 29
0
        private void RegionDescriptionForm_Load(object sender, EventArgs e)
        {
            tableRegDescr.BeginUpdate();

            string[] Units =
            {
                UnitsValue.Millimeters.ToString(),
                UnitsValue.Centimeters.ToString(),
                UnitsValue.Decimeters.ToString(),
                UnitsValue.Meters.ToString(),
                UnitsValue.Inches.ToString()
            };


            ComboBoxCellEditor UnitsEditor = new ComboBoxCellEditor();

            UnitsEditor.DropDownStyle = DropDownStyle.DropDownList;
            UnitsEditor.Items.AddRange(Units);
            tableRegDescr.ColumnModel.Columns[2].Editor = UnitsEditor;

            foreach (string str in Units)
            {
                comboUnits.Items.Add(str);
            }

            string sysUnits = (Application.GetSystemVariable("INSUNITS")).ToString();

            switch (sysUnits)
            {
            case "1":
                sysUnits = "Inches";
                break;

            case "2":
                sysUnits = "Feet";
                break;

            case "4":
                sysUnits = "Millimeters";
                break;

            case "5":
                sysUnits = "Centimeters";
                break;

            case "6":
                sysUnits = "Meters";
                break;

            case "14":
                sysUnits = "Decimeters";
                break;

            default:
                MessageBox.Show("\nUnits to scale inserted content: UNRECOGNIZED ?!", "units E R R O R");
                buttonCancel_Click(sender, e);
                break;
            }

            comboUnits.Text = sysUnits;
            comboUnits.SelectedIndexChanged += comboUnits_SelectedIndexChanged;

            #region filling the table

            // area
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Area"), new XPTable.Models.Cell(RMS.Area),
                new XPTable.Models.Cell(sysUnits /*RMS.AreaUnit.ToString()*/), new XPTable.Models.Cell(" 2 "),
                new XPTable.Models.Cell("")
            }));

            // Iy
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Iy"), new XPTable.Models.Cell(RMS.Iy),
                new XPTable.Models.Cell(sysUnits /*RMS.IyUnit.ToString()*/), new XPTable.Models.Cell(" 4 "),
                new XPTable.Models.Cell(" Moment of Inertia")
            }));

            // Wy_Upper
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Wy_Upper"), new XPTable.Models.Cell(RMS.WyUpper),
                new XPTable.Models.Cell(sysUnits /*RMS.Wy_UpperUnit.ToString()*/), new XPTable.Models.Cell(" 3 "),
                new XPTable.Models.Cell(" Section Modulus")
            }));

            // Wy_Lower
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Wy_Lower"), new XPTable.Models.Cell(RMS.WyLower),
                new XPTable.Models.Cell(sysUnits /*RMS.Wy_LowerUnit.ToString()*/), new XPTable.Models.Cell(" 3 "),
                new XPTable.Models.Cell(" Section Modulus")
            }));

            // D_Upper
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" D_Upper"), new XPTable.Models.Cell(RMS.DUpper),
                new XPTable.Models.Cell(sysUnits /*RMS.D_UpperUnit.ToString()*/), new XPTable.Models.Cell(" 1 "),
                new XPTable.Models.Cell(" Distance")
            }));

            // D_Lower
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" D_Lower"), new XPTable.Models.Cell(RMS.DLower),
                new XPTable.Models.Cell(sysUnits /*RMS.D_LowerUnit.ToString()*/), new XPTable.Models.Cell(" 1 "),
                new XPTable.Models.Cell(" Distance")
            }));

            // Iyy
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Iyy"), new XPTable.Models.Cell(RMS.Iyy),
                new XPTable.Models.Cell(sysUnits /*RMS.IyyUnit.ToString()*/), new XPTable.Models.Cell(" 1 "),
                new XPTable.Models.Cell(" Radii of gyration")
            }));

            // Iz
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Iz"), new XPTable.Models.Cell(RMS.Iz),
                new XPTable.Models.Cell(sysUnits /*RMS.IzUnit.ToString()*/), new XPTable.Models.Cell(" 4 "),
                new XPTable.Models.Cell(" Moment of Inertia")
            }));

            // Wz_Right
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Wz_Right"), new XPTable.Models.Cell(RMS.WzRight),
                new XPTable.Models.Cell(sysUnits /*RMS.Wz_RightUnit.ToString()*/), new XPTable.Models.Cell(" 3 "),
                new XPTable.Models.Cell(" Section Modulus")
            }));

            // Wz_Left
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Wz_Left"), new XPTable.Models.Cell(RMS.WzLeft),
                new XPTable.Models.Cell(sysUnits /*RMS.Wz_LeftUnit.ToString()*/), new XPTable.Models.Cell(" 3 "),
                new XPTable.Models.Cell(" Section Modulus")
            }));

            // D_Right
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" D_Right"), new XPTable.Models.Cell(RMS.DRight),
                new XPTable.Models.Cell(sysUnits /*RMS.D_RightUnit.ToString()*/), new XPTable.Models.Cell(" 1 "),
                new XPTable.Models.Cell(" Distance")
            }));

            // D_Left
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" D_Left"), new XPTable.Models.Cell(RMS.DLeft),
                new XPTable.Models.Cell(sysUnits /*RMS.D_LeftUnit.ToString()*/), new XPTable.Models.Cell(" 1 "),
                new XPTable.Models.Cell(" Distance")
            }));

            // Izz
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Izz"), new XPTable.Models.Cell(RMS.Izz),
                new XPTable.Models.Cell(sysUnits /*RMS.IzzUnit.ToString()*/), new XPTable.Models.Cell(" 1 "),
                new XPTable.Models.Cell(" Radii of gyration")
            }));

            // Imin
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Imin"), new XPTable.Models.Cell(RMS.Imin),
                new XPTable.Models.Cell(sysUnits /*RMS.IminUnit.ToString()*/), new XPTable.Models.Cell(" 4 "),
                new XPTable.Models.Cell(" Principal moment")
            }));

            // Imax
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Imax"), new XPTable.Models.Cell(RMS.Imax),
                new XPTable.Models.Cell(sysUnits /*RMS.ImaxUnit.ToString()*/), new XPTable.Models.Cell(" 4 "),
                new XPTable.Models.Cell(" Principal moment")
            }));

            // Density
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" Density"), new XPTable.Models.Cell(RMS.Density),
                new XPTable.Models.Cell("kg / cubic meter" /* + sysUnits RMS.DensityUnit.ToString()*/),
                new XPTable.Models.Cell(""), new XPTable.Models.Cell("")
            }));

            // M
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" m"), new XPTable.Models.Cell(RMS.G),
                new XPTable.Models.Cell("kg / m" /*RMS.GUnit.ToString()*/), new XPTable.Models.Cell(""),
                new XPTable.Models.Cell(" Mass per length")
            }));
            // G
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" G"), new XPTable.Models.Cell(RMS.G),
                new XPTable.Models.Cell("kgf / m" /*RMS.GUnit.ToString()*/), new XPTable.Models.Cell(" ≈"),
                new XPTable.Models.Cell(" Weight per length")
            }));
            tableRegDescr.TableModel.Rows.Add(
                new XPTable.Models.Row(new[]
            {
                new XPTable.Models.Cell(" G"), new XPTable.Models.Cell(RMS.G * 9.80665),
                new XPTable.Models.Cell("N / m" /*RMS.GUnit.ToString()*/), new XPTable.Models.Cell(" ≈"),
                new XPTable.Models.Cell(" Weight per length")
            }));

            int N = tableRegDescr.TableModel.Rows.Count;
            for (int i = 0; i < N; i++)
            {
                tableRegDescr.TableModel.Rows[i].Cells[0].Enabled = false;
                tableRegDescr.TableModel.Rows[i].Cells[1].Enabled = false;
                tableRegDescr.TableModel.Rows[i].Cells[3].Enabled = false;
                tableRegDescr.TableModel.Rows[i].Cells[4].Enabled = false;
            }
            tableRegDescr.TableModel.Rows[N - 1].Cells[2].Enabled = false;
            tableRegDescr.TableModel.Rows[N - 4].Cells[1].Enabled = true;
            tableRegDescr.TableModel.Rows[N - 4].Cells[2].Enabled = false;
            tableRegDescr.TableModel.Rows[N - 3].Cells[2].Enabled = false;
            tableRegDescr.TableModel.Rows[N - 2].Cells[2].Enabled = false;

            #endregion

            tableRegDescr.CellPropertyChanged  += tableRegDescr_CellPropertyChanged;
            tableRegDescr.HeaderRenderer        = new XPTable.Renderers.GradientHeaderRenderer();
            tableRegDescr.TableModel.RowHeight += 3;
            tableRegDescr.FullRowSelect         = true;
            tableRegDescr.EndUpdate();

            radioKg.Checked         = true;
            radioKg.CheckedChanged += radioKg_CheckedChanged;

            DocumentHelper   _drawingHelper = new DocumentHelper(Application.DocumentManager.MdiActiveDocument);
            StringCollection DimStyles      = _drawingHelper.GetDimensionStylesList();

            int currentIndex = 0;
            foreach (string dimStyle in DimStyles)
            {
                comboBoxDimensionStyle.Items.Add(dimStyle);
                if (Settings.Default.SPG_DimensionStyle == dimStyle)
                {
                    comboBoxDimensionStyle.SelectedIndex = currentIndex;
                }

                currentIndex++;
            }

            //comboBoxDimensionStyle.Text = Application.DocumentManager.MdiActiveDocument.Database.Dimstyle;


            // RegionDescription.DrawText( ref RMS );
        }
Exemplo n.º 30
0
Arquivo: Ac.cs Projeto: 15831944/Geo7
 public static object GetSystemVariable(string name)
 {
     return(AcApp.GetSystemVariable(name));
 }