Example #1
1
        private Point3d PickPoint()
        {
            try
            {
                Document     acDoc   = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                AcadDocument AcadDoc = acDoc.AcadDocument as AcadDocument;
                m_CADObjectEditCtrl.RemoveSelectionChangedEvent();
                Microsoft.VisualBasic.Interaction.AppActivate(AcadDoc.Application.Caption);
                keybd_event(Keys.Escape, 0, 0, 0);
                SendKeys.SendWait("{ESC}");
                System.Windows.Forms.Application.DoEvents();
                //aApp.DocumentManager.MdiActiveDocument.Editor.GetSelection();
                string pickPrompt = "拾取坐标";
                //   AcadDoc.Utility.GetEntity(out returnObj, out pickPoint, pickPrompt);
                m_CADObjectEditCtrl.AddSelectionChangedEvent();
                PromptPointResult pPromptEntityResult = aApp.DocumentManager.MdiActiveDocument.Editor.GetPoint(pickPrompt);
                return(pPromptEntityResult.Value);

                // AcadPoint ReturnPoint = pickPoint as AcadPoint;
                //AcadObject returnCADObj = (AcadObject)returnObj;

                //return ReturnPoint;
            }
            catch
            { return(new Point3d()); }
        }
Example #2
0
 public void Init(ref AcadDocument robjAcadDocument, ref Dictionary <object, object> robjDictReadCodes, ref Dictionary <object, object> robjDictReadValues)
 {
     mstrAcadVer        = robjAcadDocument.AcadVer;
     mobjAcadDocument   = robjAcadDocument;
     mobjDictReadCodes  = robjDictReadCodes;
     mobjDictReadValues = robjDictReadValues;
 }
Example #3
0
        internal bool FriendOpenDoc(string vstrFileName, ref AcadDocument robjAcadDocument, ref string nrstrErrMsg = "")
        {
            nrstrErrMsg      = null;
            robjAcadDocument = null;
            string dstrAcadVer = default(string);

            if (Operators.ConditionalCompareObjectEqual(Application.FriendGetVariable("SDI"), 1, TextCompare: false))
            {
                nrstrErrMsg = "Diese Methode ist im SDI-Modus nicht erlaubt.";
            }
            else if (InternCheckName(vstrFileName, ref nrstrErrMsg) && hwpDxf_Functions.BkDXF_OpenFile(vstrFileName, ref dstrAcadVer, ref nrstrErrMsg))
            {
                hwpDxf_Vars.pblnReadDocument = true;
                robjAcadDocument             = InternAddDoc(dstrAcadVer, vblnRaiseEvent: false, vstrFileName);
                bool dblnRead = InternReadFile(vstrFileName, ref robjAcadDocument, ref nrstrErrMsg);
                hwpDxf_Vars.pblnReadDocument = false;
                if (dblnRead)
                {
                    bool flag = true;
                    robjAcadDocument.Database.FriendAddAndInitObjects();
                    return(true);
                }
                FriendRemoveDoc(ref robjAcadDocument);
                robjAcadDocument = null;
            }
            bool FriendOpenDoc = default(bool);

            return(FriendOpenDoc);
        }
Example #4
0
        public static void Test()
        {
            AcadApplication   AcadApp = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application.22");
            AcadDocument      doc     = AcadApp.ActiveDocument;
            AcadModelSpace    ms      = doc.ModelSpace;
            AcadSelectionSets SelSets = doc.SelectionSets;
            //SelSets.
            AcadSelectionSet sles = SelSets.Add("Ssd");

            sles.SelectOnScreen();
            Console.WriteLine("{0}", sles.Count);

            List <AcadLWPolyline> curList = new List <AcadLWPolyline>();

            foreach (var item in sles)
            {
                try
                {
                    AcadLWPolyline PL = (AcadLWPolyline)item;
                    if (PL.Closed)
                    {
                        curList.Add(PL);
                    }
                }
                catch (Exception)
                {
                    continue;
                }


                // Console.WriteLine("Length={0}", L.Length);
            }

            sles.Delete();
        }
        /// <summary>
        ///
        /// </summary>
        public static void OpenAutoCAD()
        {
            try
            {
                AcadApp = (AcadApplication)Marshal.GetActiveObject("Autocad.Application");
                AcadDoc = AcadApp.ActiveDocument;
            }
            catch
            {
                try
                {
                    AcadApp         = new AcadApplication();
                    AcadApp.Visible = true;
                    OpenFileDialog openFileDialog = new OpenFileDialog()
                    {
                        Multiselect = true, Filter = "Abrir Plantilla|*.dwg", Title = "Archivo dwg"
                    };
                    openFileDialog.ShowDialog();

                    if (openFileDialog != null)
                    {
                        AcadDoc = AcadApp.Documents.Add(openFileDialog.FileName);
                    }
                }
                catch {
                    NotificadorErrores?.Invoke("Error inesperado.");
                }
            }
        }
Example #6
0
        private string GetTextString(string title)
        {
            string       str     = string.Empty;
            AcadDocument AcadDoc = AcadApp.ActiveDocument;

            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            object returnObj, pickPoint;
            string pickPrompt = title;

            try
            {
                AcadDoc.Utility.GetEntity(out returnObj, out pickPoint, pickPrompt);
            }
            catch (Exception) { return(""); }
            AcadObject returnCADObj = (AcadObject)returnObj;

            if (returnCADObj.ObjectName == "AcDbText")
            {
                str = ((AcadText)returnCADObj).TextString;
            }
            else if (returnCADObj.ObjectName == "AcDbMText")
            {
                string Text = ((AcadMText)returnCADObj).TextString;
                if (Text.Contains('*'))
                {
                    int FirstIndex = Text.IndexOf('*');
                    str = Text.Substring(FirstIndex, Text.IndexOf('*', FirstIndex + 1) - FirstIndex + 1);
                }
                else
                {
                    str = Text;
                }
            }
            return(str);
        }
Example #7
0
        private void BtnTX_Click(object sender, EventArgs e)
        {
            AcadDocument AcadDoc        = AcadApp.ActiveDocument;
            AcadObject   pSelectLineobj = pSelectLineobj = GetHX();

            if (pSelectLineobj == null)
            {
                return;
            }
            try
            {
                AcadLWPolyline Adlwp      = (AcadLWPolyline)pSelectLineobj;
                double[]       AdlwpPoint = (double[])Adlwp.Coordinates;
                int            PointCount = AdlwpPoint.Length / 2;
                superGridControlCoords.PrimaryGrid.Rows.Clear();
                // ISTPoint[] pSTPoints = new ISTPoint[PointCount];
                for (int j = 0; j < PointCount; j++)
                {
                    ISTPoint pSTPoint = new STPointClass()
                    {
                        X = AdlwpPoint[j * 2], Y = AdlwpPoint[j * 2 + 1]
                    };
                    superGridControlCoords.PrimaryGrid.Rows.Add(new DevComponents.DotNetBar.SuperGrid.GridRow(
                                                                    new object[] { j + 1, Math.Round(AdlwpPoint[j * 2 + 1], 3).ToString("0.000"), Math.Round(AdlwpPoint[j * 2], 3).ToString("0.000") })
                    {
                        Tag = pSTPoint
                    });
                }
                superGridControlCoords.Tag = Adlwp;
                TxbTXMJ.Text = Adlwp.Area.ToString("0.00");
            }
            finally
            { }
        }
Example #8
0
        public void Screen()
        {
            using (var cad = new AutoCadConnector())
            {
                try
                {
                    AcadDocument doc = cad.Application.Documents.Open(FileFullName);
                    Scale = Convert.ToDouble(doc.GetVariable("DIMSCALE"));

                    var points = (double[])doc.Limits;

                    var width  = (int)Math.Ceiling((points[2] - points[0]) / Scale);
                    var height = (int)Math.Ceiling((points[3] - points[1]) / Scale);

                    //Console.WriteLine(@"file name:{0},GetPaperSize:{1}*{2}", FileShortName, w,h);
                    doc.Close(false, "");
                    Angle      = width > height ? 0 : 90;
                    Width      = width;
                    Height     = height;
                    PrintedNum = 0;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("调用CAD执行图纸筛选时时发生错误!\n错误描述:{0}", ex.Message), @"批量打印",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw;
                }
            }
        }
Example #9
0
        private AcadObject GetHX()
        {
            // tableLayoutPanel2.Enabled = false;
            AcadDocument AcadDoc = AcadApp.ActiveDocument;

            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            object returnObj, pickPoint;
            string pickPrompt = "获取入库红线";

            try
            {
                AcadDoc.Utility.GetEntity(out returnObj, out pickPoint, pickPrompt);
            }
            catch { return(null); }
            AcadObject returnCADObj = (AcadObject)returnObj;

            if (returnCADObj.ObjectName == "AcDbPolyline")
            {
                AcadLWPolyline Adlwp = (AcadLWPolyline)returnCADObj;
                if (!Adlwp.Closed)
                {
                    return(null);
                }
                GeoChange = true;
                return(returnCADObj);
            }
            //Microsoft.VisualBasic.Interaction.AppActivate(this.Text);
            return(null);
        }
Example #10
0
        internal AcadDocument FriendGetItem(object vvarIndex)
        {
            int dlngIndex = default(int);

            if (Information.VarType(RuntimeHelpers.GetObjectValue(vvarIndex)) == VariantType.String)
            {
                InternFindName(Conversions.ToString(vvarIndex), ref dlngIndex);
            }
            else
            {
                dlngIndex = Conversions.ToInteger(vvarIndex);
            }
            AcadDocument FriendGetItem = default(AcadDocument);

            try
            {
                FriendGetItem = (AcadDocument)mcolClass["K" + Conversions.ToString(dlngIndex)];
                return(FriendGetItem);
            }
            catch (Exception ex2)
            {
                ProjectData.SetProjectError(ex2);
                Exception ex = ex2;
                ProjectData.ClearProjectError();
                return(FriendGetItem);
            }
        }
Example #11
0
        public static void Auto_Mate()
        {
            AcadApplication acAppObj  = null;
            const String    strProgId = "AutoCAD.Application.22.0";

            // get a running instance of autocad
            try
            {
                acAppObj = (AcadApplication)Marshal.GetActiveObject(strProgId);
            }
            catch  // an error occurs if no instance is running
            {
                try
                {
                    // create a new instance of autocad
                    acAppObj = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgId), true);
                }
                catch
                {
                    // if an instandce is not created then message and exit
                    System.Windows.Forms.MessageBox.Show("Instance of 'AutoCAD.Application' could not be created");
                    return;
                }
            }
            // display the application and return the name and the version
            acAppObj.Visible = true;
            System.Windows.Forms.MessageBox.Show("Now Running " + acAppObj.Name + " Version " + acAppObj.Version);

            // get the active document
            AcadDocument acDoc = acAppObj.ActiveDocument;

            // optionally, load your assembly and start command
        }
Example #12
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            AcadApp = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application");
            string       template = "acad.dwt";
            AcadDocument dwg      = AcadApp.Documents.Add(template);

            //AcadApp = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID("AutoCAD.Application.22"), true);
            //AcadApp.Visible = true;

            if (incomer.Contains("2500 4P ACB"))
            {
                double   RadiusOfCircle = 5;
                double[] CenterOfCircle = new double[3];
                CenterOfCircle[0] = 0;
                CenterOfCircle[1] = 0;
                CenterOfCircle[2] = 0;
                Circle            = AcadApp.ActiveDocument.ModelSpace.AddCircle(CenterOfCircle, RadiusOfCircle);


                double[] CenterOfBlock = new double[3];
                CenterOfBlock[0] = 0;
                CenterOfBlock[1] = 0;
                CenterOfBlock[2] = 0;
                //AcadApp.ActiveDocument.ModelSpace.InsertBlock(CenterOfBlock, "D:\\Block\\250A_MCCB_3P.dwg", 1, 1, 1, 0);
            }
        }
Example #13
0
        ///将DWG文件中的图形导入到CAD
        public static void ImportEntityFromDwg(string sourceFileName)
        {
            //gbl_doc.Open(sourceFileName,null);
            //gbl_doc.LoadShapeFile(sourceFileName);
            //AcadDocument document = null;
            //document = gbl_app.Documents.Open(sourceFileName, false, Type.Missing);
            //gbl_app.Documents.Add(sourceFileName);
            //document.Activate();
            gbl_doc = gbl_app.Documents.Open(sourceFileName, false, Type.Missing);

            gbl_doc.Activate();

            /*           Database db = HostApplicationServices.WorkingDatabase;
             *         Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
             *         Database sourcedb = new Database(false, true);
             *         sourcedb.ReadDwgFile(sourceFileName, System.IO.FileShare.Read, true, null);
             *
             *         using (Transaction trans = (Transaction)sourcedb.TransactionManager.StartTransaction())
             *         {
             *             BlockTable sourcebt = (BlockTable)trans.GetObject(sourcedb.BlockTableId, OpenMode.ForRead);
             *             BlockTableRecord sourcebtr = (BlockTableRecord)trans.GetObject(sourcebt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
             *
             *             foreach (ObjectId id in sourcebtr)
             *             {
             *                 Hatch ent = (Hatch)trans.GetObject(id, OpenMode.ForRead);
             *                 //ents.Add(ent);
             *             }
             *             trans.Commit();
             *             sourcebt.Dispose();
             *         }
             *         //ents.Clear();
             *         //操作完成,销毁源数据库
             *         sourcedb.Dispose();
             * */
        }
Example #14
0
        private void UploadCurCAD(AcadApplication AcadApp, IXMRK pXMRK)
        {
            AcadDocument AcadDoc = AcadApp.ActiveDocument;

            Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
            AcadDoc.Save();

            string path        = AcadDoc.Path;
            string DocmantPath = AcadDoc.FullName;
            //string strPath = HR.Utility.CommonConstString.STR_TempPath + "\\" + pXMRK.ID + ".dwg";
            string TempstrPath = HR.Utility.CommonConstString.STR_TempPath + pXMRK.TZBH + ".dwg";

            AcadDoc.SaveAs(TempstrPath, AcSaveAsType.ac2000_dwg, null);
            AcadDoc = AcadApp.ActiveDocument;
            AcadDoc.Close();
            Application.DoEvents();

            /* if (System.IO.File.Exists(strPath))
             * {
             *   System.IO.File.Delete(strPath);
             * }
             * System.IO.File.Copy(TempstrPath, strPath);*/

            pXMRK.UploadCAD(TempstrPath);
        }
Example #15
0
        private void button4_Click(object sender, EventArgs e)
        {
            //connect to acad
            AcadDocument doc = connectAcad();

            //netload script
            netloadToAcad(doc);
        }
Example #16
0
 private void InternRegDoc(ref AcadDocument robjAcadDocument)
 {
     checked
     {
         mlngDocumentIndex++;
         robjAcadDocument.FriendLetDocumentIndex = mlngDocumentIndex;
         mcolClass.Add("K" + Conversions.ToString(mlngDocumentIndex), robjAcadDocument);
         InternAddToAllDicts(ref robjAcadDocument, nvblnNew: true);
     }
 }
Example #17
0
        internal void FriendSDINewDoc(int vlngIndex)
        {
            Application.RaiseEventNewDrawing();
            AcadDocument dobjAcadDocument2 = (AcadDocument)mcolClass["K" + Conversions.ToString(vlngIndex)];

            dobjAcadDocument2.FriendReset("AC1018");
            dobjAcadDocument2.FriendSetFullName(InternGetNewName(), vblnDwgTitled: false);
            InternAddToAllDicts(ref dobjAcadDocument2);
            dobjAcadDocument2 = null;
        }
Example #18
0
 internal void FriendQuit()
 {
     if (mblnOpened)
     {
         mobjDictReadCodes  = null;
         mobjDictReadValues = null;
         mobjAcadDocument   = null;
         mblnOpened         = false;
     }
 }
Example #19
0
        public void netloadToAcad(AcadDocument doc)
        {
            //save the autocad script .dll for execution
            string fileName = tempDLLPath;

            File.WriteAllBytes(fileName, Properties.Resources.aCadDllTest);

            // netload the autocad script .dll
            fileName = fileName.Replace("\\", "\\\\");
            doc.SendCommand($"(command \"_netload\" \"{fileName}\") ");
        }
Example #20
0
        /// <summary>
        /// ReadPNote is read Note in general, can be from database, can be from dwg depends on current situation.
        /// If dwgPNote is opened, is active or not, is modified or not (can't check whether or not it is modied), refer to read from DWG and updateDatabase.
        /// If dwgPNote is Not open check date, if if equals, read from database.
        /// Else: read from file + udpate todatabase.
        /// FK IT, JUST FOUND DOWN THE INTEROPT SHIT
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public static NODEDWG ReadDataPNode(SQLiteConnection connection)
        {
            NODEDWG note = null;

            string notePath = GoodiesPath.GetNotePathFromADwgPath(Application.DocumentManager.MdiActiveDocument.Name, connection);

            if (!string.IsNullOrEmpty(notePath))
            {
                if (Goodies.GetListOfDocumentOpening().Contains(notePath))
                {
                    Document doc = Goodies.GetDocumentFromDwgpath(notePath);

                    if (doc == null)
                    {
                        Application.ShowAlertDialog("ReadDwgNoteFile -> There is no Document, weird!");
                        return(null);
                    }

                    AcadDocument acadDoct = (AcadDocument)doc.GetAcadDocument();
                    if (acadDoct.Saved && GoodiesPath.IsDateTheSame(notePath, connection))
                    {
                        note = ReadFromDatabase(connection);
                    }
                    else
                    {
                        using (Database db = doc.Database)
                        {
                            note = GetData(db, connection);
                        }
                    }
                }
                else
                {
                    Database db = new Database();
                    try
                    {
                        if (GoodiesPath.IsDateTheSame(notePath, connection))
                        {
                            note = ReadFromDatabase(connection);
                        }
                        else
                        {
                            db.ReadDwgFile(notePath, FileOpenMode.OpenForReadAndAllShare, false, "");
                            note = GetData(db, connection);
                        }
                    }catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }

            return(note);
        }
 public void SendCommand(AcadDocument doc, string command)
 {
     try
     {
         doc.SendCommand(command);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        private void Btn1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.ShowDialog();
            string          filepath = ofd.FileName;
            AcadApplication app      = new AcadApplication
            {
                Visible = true
            };
            AcadDocument doc = app.Documents.Open(filepath, null, null);
        }
Example #23
0
        private void AutoRead_Click(object sender, EventArgs e)
        {
            // Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            //Database db = HostApplicationServices.WorkingDatabase;
            tAcadApplication = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application");
            AcadDocument doc = tAcadApplication.ActiveDocument;

            double[] d2 = new double[3] {
                0, 0, 0
            };
            var d = doc.Utility.GetPoint(d2, "Select a point:");
        }
Example #24
0
 internal bool FriendAddDoc(string vstrAcadVer, ref AcadDocument robjAcadDocument, object nvvarReservedHandles = null, ref string nrstrErrMsg = "")
 {
     nrstrErrMsg      = null;
     robjAcadDocument = null;
     if (Operators.ConditionalCompareObjectEqual(Application.FriendGetVariable("SDI"), 1, TextCompare: false))
     {
         nrstrErrMsg = "Diese Methode ist im SDI-Modus nicht erlaubt.";
         bool FriendAddDoc = default(bool);
         return(FriendAddDoc);
     }
     robjAcadDocument = InternAddDoc(vstrAcadVer, vblnRaiseEvent: true, null, RuntimeHelpers.GetObjectValue(nvvarReservedHandles));
     return(true);
 }
Example #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("DXFReaderConsoleRunner");
            AcadApplications acadApplication = new AcadApplications();
            AcadDocument     acadDocument    = new AcadDocument();
            string           fileName        = string.Empty;

            acadDocument.OpenDoc(fileName);



            Console.WriteLine("Press any key to exit the program");
            Console.ReadKey();
        }
Example #26
0
 private void SetRefPoint_Click(object sender, EventArgs e)
 {
     // AutoCAD.AcadApplication Cad = new AutoCAD.AcadApplication();
     try
     {
         int Width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
         int heigh = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
         tAcadApplication.Width  = Width;
         tAcadApplication.Height = heigh;
     }
     catch (System.Exception)
     {
     }
     this.WindowState = FormWindowState.Minimized;
     try
     {
         tAcadApplication = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application");
         if (tAcadApplication.Name == "AutoCAD")
         {
             tAcadApplication.Visible = true;
             AcadDocument caddocument = tAcadApplication.ActiveDocument;
             caddocument.Activate();
             try
             {
                 caddocument.Utility.Prompt("请选择一个基准点:");
                 var point = caddocument.Utility.GetPoint();
                 RefPoint         = point;
                 SX_AIX.Text      = Convert.ToString(point[0]);
                 SY_AIX.Text      = Convert.ToString(point[1]);
                 this.WindowState = FormWindowState.Maximized;
             }
             catch (System.Exception)
             {
                 this.WindowState = FormWindowState.Maximized;
                 MessageBox.Show("UCS创建失败!e02" + e);
             }
         }
         else
         {
             this.WindowState = FormWindowState.Maximized;
             MessageBox.Show("请先打开AutoCad!+e00");
         }
     }
     catch (System.Exception)
     {
         this.WindowState = FormWindowState.Maximized;
         MessageBox.Show("请先打开AutoCad!");
     }
 }
Example #27
0
        ///将DWG文件导入到CAD并在相应的位置插入文本
        ///
        public static void ImportFromDwg(string sourceFileName, string[] strs, Point[] points)
        {
            //AcadApplication acadapp = new AcadApplication();
            //AcadDocument acaddoc = new AcadDocument();

            gbl_doc = gbl_app.Documents.Open(sourceFileName, false, Type.Missing);

            gbl_doc = gbl_app.ActiveDocument;
            gbl_app.Application.Visible = true;
            //gbl_doc.Activate();
            for (int i = 0; i < strs.Length; i++)
            {
                DrawText(points[i].X, points[i].Y, strs[i]);
            }
        }
Example #28
0
 private void InternActivateDocument(ref AcadDocument robjAcadDocument)
 {
     if (robjAcadDocument != null)
     {
         InternDeactivateDocument(mlngActiveDocumentIndex, nvblnActivateNext: false);
         mlngActiveDocumentIndex = robjAcadDocument.FriendGetDocumentIndex;
         robjAcadDocument.FriendSetActiveState(vblnActive: true);
         Application.RaiseEventActiveDocumentChanged();
     }
     else
     {
         mlngActiveDocumentIndex = -1;
         Application.RaiseEventActiveDocumentChanged();
     }
 }
 public void LoadCustomAssemblyIntoAutoCAD(AcadDocument doc)
 {
     try
     {
         if (!this._isAssemblyLoaded)
         {
             doc.SendCommand("(command " + (char)34 + "NETLOAD" + (char)34 + " " + (char)34 + _customDllPath + (char)34 + ") ");
             this._isAssemblyLoaded = true;
         }
     }
     catch (Exception ex)
     {
         this._isAssemblyLoaded = false;
         throw ex;
     }
 }
Example #30
0
        static public void Plan2Reopen()
        {
            Document doc        = Application.DocumentManager.MdiActiveDocument;
            string   strDWGName = doc.Name;

            // First cancel any running command
            if (doc.CommandInProgress != "" && string.Compare(doc.CommandInProgress, "$Plan2Reopen", StringComparison.OrdinalIgnoreCase) != 0)
            {
                AcadDocument oDoc = (AcadDocument)doc.GetAcadDocument();
                oDoc.SendCommand("\x03\x03");
            }

            doc.CloseAndDiscard();

            Application.DocumentManager.Open(strDWGName, false);
        }
Example #31
0
        public static void CreateAutoCADObject()
        {
            try
            {
                CloseAllInstance();

                gbl_app = new AcadApplication();

                gbl_doc = gbl_app.ActiveDocument;
                gbl_app.Application.Visible = true;

                gbl_modSpace = (AcadModelSpaceClass)gbl_doc.ModelSpace;
                //MessageBox.Show(gbl_app.Path);
                gbl_doc.Linetypes.Load("HIDDEN", "acad.lin");
                gbl_doc.Linetypes.Load("CENTER", "acad.lin");

                //Other Objects Layer

                SwitchLayer = CADAutomation.gbl_doc.Layers.Add("Switch110Layer");
                SwitchLayer.color = AcColor.acGreen;
                CADAutomation.gbl_doc.ActiveLayer = SwitchLayer;

                //Layer For Donuts

                TerminalsLayer = CADAutomation.gbl_doc.Layers.Add("TerminalsLayer");
                TerminalsLayer.color = AcColor.acRed;

                //Layer Termination Points

                TerminationPoints =
                  CADAutomation.gbl_doc.Layers.Add("TerminationPoints");
                TerminationPoints.color = AcColor.acWhite;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #32
0
        ///将DWG文件导入到CAD并在相应的位置插入文本
        /// 
        public static void ImportFromDwg(string sourceFileName,string[] strs,Point[] points )
        {
            //AcadApplication acadapp = new AcadApplication();
            //AcadDocument acaddoc = new AcadDocument();

            gbl_doc = gbl_app.Documents.Open(sourceFileName, false, Type.Missing);

            gbl_doc = gbl_app.ActiveDocument;
            gbl_app.Application.Visible = true;
            //gbl_doc.Activate();
            for (int i = 0; i < strs.Length; i++)
            {
                DrawText(points[i].X,points[i].Y,strs[i]);
            }
        }
Example #33
0
        ///将DWG文件中的图形导入到CAD
        public static void ImportEntityFromDwg(string sourceFileName)
        {
            //gbl_doc.Open(sourceFileName,null);
            //gbl_doc.LoadShapeFile(sourceFileName);
            //AcadDocument document = null;
            //document = gbl_app.Documents.Open(sourceFileName, false, Type.Missing);
            //gbl_app.Documents.Add(sourceFileName);
            //document.Activate();
            gbl_doc = gbl_app.Documents.Open(sourceFileName, false, Type.Missing);

            gbl_doc.Activate();
             /*           Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database sourcedb = new Database(false, true);
            sourcedb.ReadDwgFile(sourceFileName, System.IO.FileShare.Read, true, null);

            using (Transaction trans = (Transaction)sourcedb.TransactionManager.StartTransaction())
            {
                BlockTable sourcebt = (BlockTable)trans.GetObject(sourcedb.BlockTableId, OpenMode.ForRead);
                BlockTableRecord sourcebtr = (BlockTableRecord)trans.GetObject(sourcebt[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                foreach (ObjectId id in sourcebtr)
                {
                    Hatch ent = (Hatch)trans.GetObject(id, OpenMode.ForRead);
                    //ents.Add(ent);
                }
                trans.Commit();
                sourcebt.Dispose();
            }
            //ents.Clear();
            //操作完成,销毁源数据库
            sourcedb.Dispose();
              * */
        }
Example #34
0
        private void UpdateCAD()
        {
            var showInfo = "";
            var fileStaus = "";
            if (string.IsNullOrEmpty(txtSavePath.Text))
            {
                MessageBox.Show("请选择文件保存位置!", "提示信息"); return;
            }
            var FilePath = "";
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int k = 0; k < lvwList.Items.Count; k++)
            {
                lblTips.Text = "当前共有: " + lvwList.Items.Count + " 张图纸需要处理,现在正在处理第 " + (k + 1) + " 张";
                FilePath = lvwList.Items[k].ToString();
                AcadDoc = acAppComObj.Documents.Open(FilePath, null, null);
                acAppComObj.Application.Visible = false;
                AcadBlocks blocks = AcadDoc.Blocks;
                HistoryDto dto = new HistoryDto();
                CodeDto codeDto = new CodeDto();
                dto.Id = Guid.NewGuid().ToString();
                dto.FileName = AcadDoc.Name;
                dto.FilePath = FilePath;
                try
                {
                    foreach (AcadBlock block in blocks)
                    {
                        foreach (AcadEntity entity in block)
                        {
                            list.Add(entity.ObjectName);

                            ////1.替换基本属性
                            //Util.ReplaceProperty(entity);
                            ////2.替换装配图的明细表编号
                            //Util.ReplaceDrawingCode(entity, acAppComObj);
                            //entity.Update();
                        }
                    }
                    fileStaus = "图纸处理完成";
                    dto.FileStatus = fileStaus;
                    //3.处理情况保存
                    //InsertHistory(dto);
                    codeDto.Id = Guid.NewGuid().ToString();
                    codeDto.OldCode = Util.oldCode;
                    codeDto.NewCode = Util.newCode;
                    //InsertCode(codeDto);
                }
                catch (Exception ex)
                {
                    fileStaus = "图纸处理异常,异常原因:" + ex.Message;
                    dto.FileStatus = fileStaus;
                    //3.处理情况保存
                    //InsertHistory(dto);
                    continue;
                }
                dto.FileStatus = fileStaus;

                //判断是否需要保存,如需要则另存为
                if (acAppComObj.ActiveDocument.Saved == false)
                {
                    acAppComObj.ActiveDocument.SaveAs(txtSavePath.Text + "\\" + Util.newCode, AcSaveAsType.ac2013_dwg, null);
                    GC.Collect();
                }
            }
            stopwatch.Stop(); //  停止监视
            TimeSpan timespan = stopwatch.Elapsed; //  获取当前实例测量得出的总时间
            double hours = timespan.TotalHours; // 总小时
            double minutes = timespan.TotalMinutes;  // 总分钟
            double seconds = timespan.TotalSeconds;  //  总秒数
            double milliseconds = timespan.TotalMilliseconds;  //  总毫秒数
            lvwList.DataSource = list;
            MessageBox.Show(fileStaus);
            //MessageBox.Show("图纸修改完成,修改所花时间为:" + seconds.ToString());
            MessageBox.Show(showInfo);
        }