コード例 #1
0
        /// <summary>ObjectId блока для стрелки</summary>
        /// <param name="newArrName">Имя блока для стрелки</param>
        /// <returns>ObjectId нового блока стрелки</returns>
        public static ObjectId GetArrowObjectId(string newArrName)
        {
            ObjectId arrObjId;
            var      doc = AcApp.DocumentManager.MdiActiveDocument;
            var      db  = doc.Database;

            // Получаем текущее значение переменной DIMBLK
            var oldArrName = AcApp.GetSystemVariable("DIMBLK") as string;

            // Устанавливаем новое значение DIMBLK
            // (если такой блок отсутствует в чертеже, то он будет создан)
            AcApp.SetSystemVariable("DIMBLK", newArrName);

            // Возвращаем предыдущее значение переменной DIMBLK
            if (!string.IsNullOrEmpty(oldArrName))
            {
                AcApp.SetSystemVariable("DIMBLK", oldArrName);
            }

            // Теперь получаем objectId блока
            var tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                arrObjId = bt[newArrName];
                tr.Commit();
            }

            return(arrObjId);
        }
コード例 #2
0
 private void AutoCadMessageHandler(object sender, PreTranslateMessageEventArgs e)
 {
     if (e.Message.message == (int)WndMsg.WM_KEYDOWN)
     {
         if ((int)e.Message.wParam == (int)WndKey.VK_F1)
         {
             // F1 pressed
             if (_currentTooltip != null && _currentTooltip.Length > 8 && _currentTooltip.StartsWith("https://modplus.org/"))
             {
                 // Another implementation could be to look up the help topic in an index file matching it to URLs.
                 _dropNextHelpCall = true; // Even though we don't forward this F1 keypress, AutoCAD sends a message to itself to open the AutoCAD help file
                 object nomutt = AcApp.GetSystemVariable("NOMUTT");
                 string cmd    = $"._BROWSER {_currentTooltip} _NOMUTT {nomutt} ";
                 AcApp.SetSystemVariable("NOMUTT", 1);
                 AcApp.DocumentManager.MdiActiveDocument.SendStringToExecute(cmd, true, false, false);
                 e.Handled = true;
             }
         }
     }
     else if (e.Message.message == (int)WndMsg.WM_ACAD_HELP && _dropNextHelpCall)
     {
         // Seems this is the message AutoCAD generates itself to open the help file. Drop this if help was called from a ribbon tooltip.
         _dropNextHelpCall = false; // Reset state of help calls
         e.Handled         = true;  // Stop this message from being passed on to AutoCAD
     }
 }
コード例 #3
0
 /// <summary>
 /// This method creates an instance for Commands
 /// This constructor is called once per document
 /// on first call of the method 'CommandMethod'
 /// </summary>
 public Commands()
 {
     // Initialization of private fields (initial default values)
     doc    = AcAp.DocumentManager.MdiActiveDocument;
     radius = 10.0;
     layer  = (string)AcAp.GetSystemVariable("clayer");
 }
コード例 #4
0
        private static void AchtergrondCommand_(TileConfig tileConfig)
        {
            try
            {
                var location = AutocadUtils.GetRectangle();
                if (location == null)
                {
                    return;
                }

                var tileNames = tileConfig.GetTileByLocation(location).ToArray();
                if (!tileNames.Any())
                {
                    Application.ShowAlertDialog(GeenAchtergrondGevonden);
                }
                foreach (var tileName in tileNames)
                {
                    var num = (short)Application.GetSystemVariable("FILEDIA");
                    Application.DocumentManager.CurrentDocument.SendStringToExecute("_FILEDIA " + 0 + " ", true, false,
                                                                                    false);
                    var str = $"_MAPIINSERT \"{tileName}\" N ";
                    Application.DocumentManager.CurrentDocument.SendStringToExecute(str, false, true, true);
                    Application.DocumentManager.CurrentDocument.SendStringToExecute("_FILEDIA " + num + " ", true, false,
                                                                                    false);
                }
            }
            catch (Exception ex)
            {
                Utilities.HandleError(ex);
            }
        }
コード例 #5
0
        public override bool WorldDraw(Drawable drawable, WorldDraw wd)
        {
            if (!wd.Context.IsPlotGeneration) // Не в состоянии печати!
            {
                var ent = drawable as Entity;
                if (ent != null && !ent.IsAProxy && !ent.IsCancelling && !ent.IsDisposed && !ent.IsErased)
                {
                    try
                    {
                        if (ent.IsModPlusProduct())
                        {
                            double height = (double)AcApp.GetSystemVariable("VIEWSIZE");
                            var    scale  = height / 1500;
                            var    offset = 20;
                            var    plane  = ent.GetPlane();

                            Matrix3d          ucs     = AcApp.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem;
                            var               extents = ent.GeometricExtents;
                            var               pt      = extents.MaxPoint.TransformBy(ucs.Inverse());
                            Point3dCollection points  = new Point3dCollection();
                            points.Add(new Point3d(pt.X + ((offset + 00) * scale), pt.Y + ((offset + 00) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 00) * scale), pt.Y + ((offset + 10) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 10) * scale), pt.Y + ((offset + 10) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 10) * scale), pt.Y + ((offset + 30) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 00) * scale), pt.Y + ((offset + 30) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 00) * scale), pt.Y + ((offset + 40) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 30) * scale), pt.Y + ((offset + 40) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 30) * scale), pt.Y + ((offset + 30) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 20) * scale), pt.Y + ((offset + 30) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 20) * scale), pt.Y + ((offset + 10) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 30) * scale), pt.Y + ((offset + 10) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 30) * scale), pt.Y + ((offset + 00) * scale), plane.PointOnPlane.Z));
                            points.Add(new Point3d(pt.X + ((offset + 00) * scale), pt.Y + ((offset + 00) * scale), plane.PointOnPlane.Z));

                            short    backupColor    = wd.SubEntityTraits.Color;
                            FillType backupFillType = wd.SubEntityTraits.FillType;
                            wd.SubEntityTraits.FillType = FillType.FillAlways;
                            wd.SubEntityTraits.Color    = 150;
                            wd.Geometry.Polygon(points);
                            wd.SubEntityTraits.FillType = FillType.FillNever;

                            // restore
                            wd.SubEntityTraits.Color    = backupColor;
                            wd.SubEntityTraits.FillType = backupFillType;
                        }
                    }
                    catch (System.Exception exception)
                    {
                        // not showing. Only sending by AppMetrica
                        Statistic.SendException(exception);
                    }
                }
            }

            return(base.WorldDraw(drawable, wd));
        }
コード例 #6
0
        private static bool ShouldSupressRunningOSnap()
        {
            if (!supressRunningOSnap)
            {
                return(false);
            }
            int num = (short)AcadApp.GetSystemVariable("OSMODE");

            return(num != 0 && (num & 16384) == 0);
        }
コード例 #7
0
ファイル: RectangleJig.cs プロジェクト: kojtoLtd/KojtoCAD
        private String GetIsoPlane( )
        {
            String result = "Left";

            if (Application.GetSystemVariable("Snapisopair").ToString( ) == "1")
            {
                result = "Top";
            }
            else if (Application.GetSystemVariable("Snapisopair").ToString( ) == "2")
            {
                result = "Right";
            }
            return(result);
        }
コード例 #8
0
        public static int Command(params object[] args)
        {
            if (AcadApp.DocumentManager.IsApplicationContext)
            {
                return(0);
            }
            int  stat         = 0;
            int  cnt          = 0;
            bool supressOSnap = ShouldSupressRunningOSnap();
            bool transform    = ShouldTransformCoords();

            using (ResultBuffer buffer = new ResultBuffer())
            {
                foreach (object o in args)
                {
                    if (supressOSnap && (o is Point3d || o is Point2d))
                    {
                        buffer.Add(new TypedValue(RTSTR, "_non"));
                    }
                    if (transform && (o is Point3d))
                    {
                        buffer.Add(new TypedValue(RT3DPOINT, WorldToCurrent((Point3d)o)));
                    }
                    else
                    {
                        buffer.Add(TypedValueFromObject(o));
                    }
                    ++cnt;
                }
                if (cnt > 0)
                {
                    string s       = (string)AcadApp.GetSystemVariable("USERS1");
                    bool   debug   = string.Compare(s, "DEBUG", true) == 0;
                    int    val     = debug ? 1 : 0;
                    object cmdecho = AcadApp.GetSystemVariable("CMDECHO");
                    Int16  c       = (Int16)cmdecho;
                    if (c != 0 || debug)
                    {
                        AcadApp.SetSystemVariable("CMDECHO", val);
                    }
                    stat = acedCmd(buffer.UnmanagedObject);
                    if (c != 0 || debug)
                    {
                        AcadApp.SetSystemVariable("CMDECHO", cmdecho);
                    }
                }
            }
            return(stat);
        }
コード例 #9
0
ファイル: Misc.cs プロジェクト: 15831944/EM
        getCommandList()
        {
            string[] cmds = null;
            string   cmd  = (string)Application.GetSystemVariable("CMDNAMES");

            if (cmd.Length > 0)
            {
                int cmdNum = cmd.Split(new char[] {
                    '\''
                }).Length;
                cmds = cmd.Split(new char[] {
                    '\''
                });
            }
            return(cmds);
        }
コード例 #10
0
 private static void GetColorTheme()
 {
     try
     {
         var sv = Application.GetSystemVariable("COLORTHEME").ToString();
         if (int.TryParse(sv, out var i))
         {
             _colorTheme = i;
         }
         else
         {
             _colorTheme = 1; // light
         }
     }
     catch
     {
         _colorTheme = 1;
     }
 }
コード例 #11
0
ファイル: Macros.cs プロジェクト: kojtoLtd/KojtoCAD
        public void RecoverTest()
        {
            Document           doc  = Application.DocumentManager.MdiActiveDocument;
            DocumentCollection docs = Application.DocumentManager;
            Editor             ed   = doc.Editor;

#if !acad2013
            ed.WriteMessage("Not supported in ACAD versions lower than 2015.");
            return;
#else
            var oldValue = Application.GetSystemVariable("PROXYNOTICE");
            Application.SetSystemVariable("PROXYNOTICE", 0);


            var errorsFile = @"errors.csv";
            var content    = File.ReadAllLines(errorsFile).Select(x => x.Split(new[] { " -> " }, StringSplitOptions.RemoveEmptyEntries));
            var forRepair  = content.Where(x => x[1].Equals("eDwgNeedsRecovery")).Select(x => x[0]);
            using (var errorLogger = new StreamWriter("Errors_Recovery.csv", true)
            {
                AutoFlush = true
            })
            {
                foreach (var file in forRepair)
                {
                    //var path = $@"\\?\{file}";
                    try
                    {
                        var path = Path.Combine(@"D:\DwgWork", file.Substring(49));
                        //path = $@"\\?\{path}";
                        docs.AppContextRecoverDocument(path);
                        Application.DocumentManager.MdiActiveDocument.CloseAndSave(path);
                    }
                    catch (System.Exception e)
                    {
                        errorLogger.WriteLine($"{file} -> {e.Message}");
                    }
                }
            }

            Application.SetSystemVariable("PROXYNOTICE", oldValue);
#endif
        }
コード例 #12
0
        private static void SubscribeDoc([CanBeNull] Document doc)
        {
            if (doc == null)
            {
                return;
            }

            if (sn == null || sn.StartsWith("000"))
            {
                try
                {
                    sn = Application.GetSystemVariable("_pkser") as string;
                    Logger.Log.Info($"EventsStatisticService (_pkser) SerialNumber = {sn}");
                }
                catch (Exception ex)
                {
                    Logger.Log.Error(ex, "EventsStatisticService - GetSystemVariable(\"_pkser\")");
                }

                if (sn == null || sn.StartsWith("000"))
                {
                    sn = GetRegistrySerialNumber();
                    Logger.Log.Info($"EventsStatisticService (Registry) SerialNumber = {sn}");
                }
            }

            try
            {
                var db = doc.Database;
                db.Events().SaveComplete.Throttle(TimeSpan.FromSeconds(3))
                .Do(s => Logger.Log.Info($"Eventer SaveComplete Do - {s}."))
                .Subscribe(s => Db_SaveComplete(s?.Sender, s?.EventArgs));
                eventer?.Finish(EventType.Open, doc.Name, sn);
                Logger.Log.Info("SubscribeDoc end");
            }
            catch (Exception ex)
            {
                Logger.Log.Error(ex, "EventsStatisticService SubscribeDoc");
            }
        }
コード例 #13
0
            protected override bool WorldDraw(WorldDraw draw)
            {
                var wg = draw.Geometry;

                if (wg != null)
                {
                    ObjectId arrId = AutocadHelpers.GetArrowObjectId(ArrowName);

                    var mtxt = new MText();
                    mtxt.SetDatabaseDefaults();
                    mtxt.Contents   = MlText;
                    mtxt.Location   = _secondPoint;
                    mtxt.Annotative = AnnotativeStates.True;
                    mtxt.TransformBy(AcApp.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem);

                    _mleader = new MLeader();
                    var ldNum = _mleader.AddLeader();
                    _mleader.AddLeaderLine(ldNum);
                    _mleader.SetDatabaseDefaults();
                    _mleader.ContentType           = ContentType.MTextContent;
                    _mleader.ArrowSymbolId         = arrId;
                    _mleader.MText                 = mtxt;
                    _mleader.TextAlignmentType     = TextAlignmentType.LeftAlignment;
                    _mleader.TextAttachmentType    = TextAttachmentType.AttachmentBottomOfTopLine;
                    _mleader.TextAngleType         = TextAngleType.HorizontalAngle;
                    _mleader.EnableAnnotationScale = true;
                    _mleader.Annotative            = AnnotativeStates.True;
                    _mleader.AddFirstVertex(ldNum, FirstPoint);
                    _mleader.AddLastVertex(ldNum, _secondPoint);
                    _mleader.LeaderLineType = LeaderType.StraightLeader;
                    _mleader.EnableDogleg   = false;
                    _mleader.DoglegLength   = 0.0;
                    _mleader.LandingGap     = 1.0;
                    _mleader.TextHeight     = double.Parse(AcApp.GetSystemVariable("TEXTSIZE").ToString());

                    draw.Geometry.Draw(_mleader);
                }

                return(true);
            }
コード例 #14
0
        public static bool PaletteVisible()
        {
            bool result;

            try
            {
                object systemVariable = Application.GetSystemVariable("TPSTATE");
                if ((short)systemVariable == 0)
                {
                    result = false;
                }
                else
                {
                    result = true;
                }
            }
            catch
            {
                result = false;
            }
            return(result);
        }
コード例 #15
0
 private static void IncludeFolderLocation(string folderLocation)
 {
     try
     {
         Application.GetSystemVariable("_TOOLPALETTEPATH");
         string   text  = (string)Application.GetSystemVariable("_TOOLPALETTEPATH");
         string[] array = text.Split(new char[]
         {
             ';'
         });
         bool     flag   = false;
         string[] array2 = array;
         for (int i = 0; i < array2.Length; i++)
         {
             string path = array2[i];
             if (string.Compare(Path.GetFullPath(path).TrimEnd(new char[]
             {
                 '\\'
             }), Path.GetFullPath(folderLocation).TrimEnd(new char[]
             {
                 '\\'
             }), StringComparison.InvariantCultureIgnoreCase) == 0)
             {
                 flag = true;
                 break;
             }
         }
         if (!flag)
         {
             text += string.Format(";{0}", folderLocation);
             Application.SetSystemVariable("_TOOLPALETTEPATH", text);
             Application.GetSystemVariable("TPSTATE");
         }
     }
     catch
     {
     }
 }
コード例 #16
0
        //------------------------------------------------------------------------//
        //
        public static void Zoom(Point3d pMin, Point3d pMax, Point3d pCenter, double dFactor)
        {
            // Get de 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)
            {
                if (pMin.Equals(new Point3d()) && pMax.Equals(new Point3d()))
                {
                    pMin = acCurDb.Extmin;
                    pMax = acCurDb.Extmax;
                }
            }
            else
            {
                // Check to see if Paper space is current
                if (nCurVport == 1)
                {
                    // Get the extents of Papers space
                    if (pMin.Equals(new Point3d()) && pMax.Equals(new Point3d()))
                    {
                        pMin = acCurDb.Pextmin;
                        pMax = acCurDb.Pextmax;
                    }
                }
                else
                {
                    // Get the extents of Model space
                    if (pMin.Equals(new Point3d()) && pMax.Equals(new Point3d()))
                    {
                        pMin = acCurDb.Extmin;
                        pMax = acCurDb.Extmax;
                    }
                }
            }

            // Start transation
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Get the current view
                using (ViewTableRecord acView = acDoc.Editor.GetCurrentView())
                {
                    // 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 specified, define the min and max
                    // point of extents for Center and Scale modes
                    if (!pCenter.DistanceTo(Point3d.Origin).Equals(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
                    Line acLine = new Line(pMin, pMax);
                    if (acLine.Bounds != null)
                    {
                        Extents3d 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 = (acView.Width / acView.Height);

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

                        double  dWidth;
                        double  dHeight;
                        Point2d pNewCentPt;

                        // Check see if a center point was provided (Center an dScale modes)
                        if (!pCenter.DistanceTo(Point3d.Origin).Equals(0.0))
                        {
                            dWidth  = acView.Width;
                            dHeight = acView.Height;

                            if (dFactor.Equals(0.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 current view
                            dWidth  = eExtents.MaxPoint.X - eExtents.MinPoint.X;
                            dHeight = eExtents.MaxPoint.Y - eExtents.MinPoint.Y;

                            //Get te 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.Equals(0.0))
                        {
                            acView.Height = dHeight * dFactor;
                            acView.Width  = dWidth * dFactor;
                        }

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

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

                acTrans.Commit();
            }
        }
コード例 #17
0
ファイル: RcWeldMark.cs プロジェクト: chuongmep/RabCab
        public void Cmd_WeldMark()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;

            _ = acCurDoc.Editor;

            try
            {
                Entity jigEnt = WeldJig.Jig(out var arrowStart, out var symStart);
                var    jigId  = ObjectId.Null;

                if (jigEnt == null)
                {
                    //jigEnt.Dispose();
                    return;
                }

                jigId = acCurDb.AppendEntity(jigEnt);
                Line line       = null;
                var  lineId     = ObjectId.Null;
                var  leftFacing = false;

                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    var arrowPt = new Point2d(arrowStart.X, arrowStart.Y);
                    var symPt   = new Point2d(symStart.X, symStart.Y);

                    var angle = arrowPt.AngleBetween(symPt);

                    var dDimScale =
                        (double)Application.GetSystemVariable("DIMSCALE");
                    var length = SettingsUser.WeldSymbolLength * dDimScale;

                    if (angle > 90 || angle < -90)
                    {
                        length     = -length;
                        leftFacing = true;
                    }

                    line = new Line(symStart, new Point3d(symStart.X + length, symStart.Y, 0));

                    lineId = acCurDb.AppendEntity(line, acTrans);


                    acTrans.Commit();
                }

                var weldGui = new WeldGui(line.StartPoint, line.EndPoint);
                weldGui.LeftFacing = leftFacing;

                var result = weldGui.ShowDialog();

                TransientAgent.Clear();

                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    if (result == DialogResult.OK)
                    {
                        foreach (var ent in weldGui.drawnEnts)
                        {
                            acCurDb.AppendEntity(ent, acTrans);
                        }
                    }
                    else
                    {
                        var jigDel = acTrans.GetObject(jigId, OpenMode.ForWrite) as Entity;
                        if (jigDel != null)
                        {
                            jigDel.Erase();
                            jigDel.Dispose();
                        }

                        var lineDel = acTrans.GetObject(lineId, OpenMode.ForWrite) as Entity;
                        if (lineDel != null)
                        {
                            lineDel.Erase();
                            lineDel.Dispose();
                        }

                        line.Dispose();
                    }

                    acTrans.Commit();
                }

                weldGui.Dispose();

                Utils.SetFocusToDwgView();
            }
            catch (Exception ex)
            {
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString());
            }
        }
コード例 #18
0
        private static void DocumentManager_DocumentLockModeChanged(object sender, DocumentLockModeChangedEventArgs e)
        {
            Debug.WriteLine($"DocumentManager_DocumentLockModeChanged {e.GlobalCommandName} {e.Document.Name}");
            try
            {
                short dbmod = (short)Application.GetSystemVariable("DBMOD");
                switch (e.GlobalCommandName)
                {
                case "QSAVE":
                    Logger.Log.Info("Eventer DocumentLockModeChanged=QSAVE");
                    StopSave(e, Case.Default);
                    lastModeChange = "QSAVE";
                    break;

                case "SAVEAS":
                    Logger.Log.Info("Eventer DocumentLockModeChanged=SAVEAS");
                    if (lastModeChange != "SAVEAS")
                    {
                        lastModeChange = "SAVEAS";
                        StopSave(e, Case.SaveAs);
                    }

                    break;

                case "#SAVEAS":
                    Logger.Log.Info("Eventer DocumentLockModeChanged=#SAVEAS");
                    if (lastModeChange != "SAVEAS" || lastSaveAsFile != e.Document.Name)
                    {
                        StopSave(e, Case.SaveAs);
                    }

                    lastModeChange = "#SAVEAS";
                    break;

                case "CLOSE":
                    Logger.Log.Info("Eventer DocumentLockModeChanged=CLOSE");
                    if (dbmod != 0 && lastModeChange != "CLOSE")
                    {
                        switch (MessageBox.Show("Файл изменен. Хотите сохранить изменения?", "Внимание!",
                                                MessageBoxButton.YesNoCancel, MessageBoxImage.Warning))
                        {
                        case MessageBoxResult.Yes:
                            if (!StopSave(e, Case.Default))
                            {
                                e.Veto();
                                CloseSave(e.Document);
                            }
                            else
                            {
                                e.Veto();
                                CloseDiscard(e.Document);
                            }

                            lastModeChange = "CLOSE";
                            break;

                        case MessageBoxResult.No:
                            e.Veto();
                            CloseDiscard(e.Document);
                            break;

                        case MessageBoxResult.Cancel:
                            e.Veto();
                            break;
                        }
                    }

                    lastModeChange = "CLOSE";
                    break;

                default:
                    lastModeChange = null;
                    break;
                }
            }
            catch (OperationCanceledException)
            {
                // Отмена
                e.Veto();
            }
            catch (Exception ex)
            {
                Logger.Log.Fatal(ex, $"EventsStatisticService DocumentManager_DocumentLockModeChanged, GlobalCommandName={e?.GlobalCommandName}");
            }
        }
コード例 #19
0
        XO()
        {
            object  objOffset = Application.GetSystemVariable("OFFSETDIST");
            Point3d pnt3dBeg = Pub.pnt3dO;
            Point3d pnt3dEnd = Pub.pnt3dO;
            Point3d pnt3dCen, pnt3dX;
            string  defPrompt;

            if (objOffset.ToString() == "-1")
            {
                defPrompt = "Through";
            }
            else
            {
                defPrompt = objOffset.ToString();
            }

            double disX = 0.0, offset = 0.0, radius = 0.0;

            bool   through = false;
            string result, prompt = "\nSpecify Offset distance or [Through]: ";

            UserInput.getUserInput(defPrompt, prompt, out result, false);
            if (result == string.Empty)
            {
                return;
            }

            Point3d  pnt3dPick = Pub.pnt3dO;
            string   nameLayer = string.Empty;
            ObjectId idBlkRef  = ObjectId.Null;
            ObjectId idEnt     = xRef.getEntity("\nSelect object to offset or <exit>: ", true, out nameLayer, out pnt3dPick, out idBlkRef);

            if (idEnt == ObjectId.Null)
            {
                return;
            }

            PromptStatus ps = PromptStatus.Cancel;

            if (result.ToUpper() == "THROUGH" || result.ToUpper() == "T")
            {
                through = true;
                pnt3dX  = UserInput.getPoint("\nSpecify Offset point : ", out ps, osMode: 0);
            }
            else
            {
                offset = double.Parse(result);
                Application.SetSystemVariable("OFFSETDIST", offset);
                if (offset == 0)
                {
                    idEnt.copy("0");
                    return;
                }
                else
                {
                    pnt3dX = UserInput.getPoint("\nSpecify point on side to offset: ", out ps, osMode: 0);
                }
            }
            bool rh = true;

            string typeEnt = idEnt.getType();

            switch (typeEnt)
            {
            case "Polyline":
                double bulge = 0.0;
                try
                {
                    using (Transaction tr = BaseObjs.startTransactionDb())
                    {
                        Polyline poly = (Polyline)tr.GetObject(idEnt, OpenMode.ForRead);
                        if (poly.Closed)
                        {
                            idEnt.checkIfClosed();
                        }
                        int vtx = Geom.getVertexNo(idEnt, pnt3dX);
                        pnt3dBeg = poly.GetPoint3dAt(vtx);
                        pnt3dEnd = poly.GetPoint3dAt(vtx + 1);
                        bulge    = poly.GetBulgeAt(vtx);
                        tr.Commit();
                    }
                }
                catch (System.Exception ex)
                {
                    BaseObjs.writeDebug(ex.Message + " cmdXO.cs: line: 86");
                }
                if (bulge == 0.0)
                {
                    processLine(pnt3dBeg, pnt3dEnd, pnt3dX, through, disX, ref offset);
                }
                else
                {
                    if (bulge < 0)
                    {
                        rh = false;
                    }
                    pnt3dCen = Geom.getCenter(pnt3dBeg, pnt3dEnd, bulge);

                    if (!processArc(pnt3dBeg, pnt3dEnd, pnt3dCen, pnt3dX, through, radius, rh, idEnt, disX, ref offset))
                    {
                        return;
                    }
                }
                break;

            case "Line":
                Line line = (Line)idEnt.getEnt();
                pnt3dBeg = line.StartPoint;
                pnt3dEnd = line.EndPoint;
                processLine(pnt3dBeg, pnt3dEnd, pnt3dX, through, disX, ref offset);
                break;

            case "Arc":
                Arc arc = (Arc)idEnt.getEnt();
                pnt3dBeg = arc.StartPoint;
                pnt3dEnd = arc.EndPoint;
                pnt3dCen = arc.Center;
                radius   = arc.Radius;
                Vector3d v3d = arc.Normal;
                if (v3d.Z < 0)
                {
                    rh = false;
                }

                if (!processArc(pnt3dBeg, pnt3dEnd, pnt3dCen, pnt3dX, through, radius, rh, idEnt, disX, ref offset))
                {
                    return;
                }
                break;
            }
            idEnt.offset(offset);
            idEnt.delete();
        }
コード例 #20
0
        public void DrawCircleCmd()
        {
            var db = doc.Database;
            var ed = doc.Editor;

            // Layer choice
            var layerList = GetLayerNames(db);

            if (!layerList.Contains(layer))
            {
                layer = (string)AcAp.GetSystemVariable("clayer");
            }

            // Request user input for layer name
            var layerName = new PromptStringOptions("\nLayer name: ");

            layerName.DefaultValue    = layer;
            layerName.UseDefaultValue = true;

            var layerInput = ed.GetString(layerName);

            if (layerInput.Status != PromptStatus.OK)
            {
                return;
            }

            if (!layerList.Contains(layerInput.StringResult.ToUpper()))
            {
                ed.WriteMessage(
                    $"\nNo layer named '{layerInput.StringResult}' in the layer's table.");
                return;
            }

            layer = layerInput.StringResult.ToUpper();

            // Request user input for radius value
            var radiusInput = new PromptDistanceOptions("\nEnter the radius: ");

            radiusInput.DefaultValue    = radius;
            radiusInput.UseDefaultValue = true;

            var distResult = ed.GetDistance(radiusInput);

            if (distResult.Status != PromptStatus.OK)
            {
                return;
            }

            radius = distResult.Value;

            // Request user input for centre point
            var centrePoint = ed.GetPoint("\nEnter the centre point: ");

            if (centrePoint.Status == PromptStatus.OK)
            {
                // Draw the circle in current space
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    var curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                    using (var circle = new Circle(centrePoint.Value, Vector3d.ZAxis, radius))
                    {
                        circle.TransformBy(ed.CurrentUserCoordinateSystem);
                        circle.Layer = layerInput.StringResult;
                        curSpace.AppendEntity(circle);
                        tr.AddNewlyCreatedDBObject(circle, true);
                    }
                    tr.Commit();
                }
            }
        }
コード例 #21
0
        public static void SaveAsPDF(ResultBuffer rbArgs)
        {
            var editor = Acad.DocumentManager.MdiActiveDocument.Editor;

            editor.WriteMessage("Процесс экспорта чертежей в формат PDF начинается...");
            // Получение директории и параметров поиска
            if (rbArgs != null)
            {
                string str     = "";
                bool   subDirs = false;
                foreach (TypedValue rb in rbArgs)
                {
                    if (rb.TypeCode == (int)Autodesk.AutoCAD.Runtime.LispDataType.Text)
                    {
                        if (rb.Value.ToString() == "true")
                        {
                            subDirs = true;
                        }
                        else if (rb.Value.ToString() == "false")
                        {
                            subDirs = false;
                        }
                        else
                        {
                            str += rb.Value.ToString();
                        }
                    }
                }
                Acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Путь к чертежам: " + str);
                // Получение списка файлов с учетом заданного пути и параметров поиска
                try
                {
                    str = str.Replace('/', '\\');
                    System.IO.DirectoryInfo rootDir = new System.IO.DirectoryInfo(str);
                    System.IO.FileInfo[]    dirs    = rootDir.GetFiles("*.dwg", subDirs ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                    short bgp = (short)Acad.GetSystemVariable("BACKGROUNDPLOT");
                    Acad.SetSystemVariable("BACKGROUNDPLOT", 0);
                    //Список листов найденных чертежей
                    foreach (FileInfo dir in dirs)
                    {
                        editor.WriteMessage(Environment.NewLine + dir);
                        using (Database dwgDB = new Database(false, true))
                        {
                            dwgDB.ReadDwgFile(dir.FullName, System.IO.FileShare.ReadWrite, false, "");


                            //Далее манипуляции с базой данных чертежа
                            using (Transaction acTrans = dwgDB.TransactionManager.StartTransaction())
                            {
                                List <Layout> layouts    = new List <Layout>();
                                DBDictionary  layoutDict = (DBDictionary)acTrans.GetObject(dwgDB.LayoutDictionaryId, OpenMode.ForRead);
                                editor.WriteMessage("Листы чертежа " + dir + ":");
                                foreach (DBDictionaryEntry id in layoutDict)
                                {
                                    if (id.Key != "Model")
                                    {
                                        Layout                ltr    = (Layout)acTrans.GetObject((ObjectId)id.Value, OpenMode.ForRead);
                                        PlotConfig            config = PlotConfigManager.SetCurrentConfig("AutoCAD PDF (High Quality Print).pc3");
                                        PlotSettingsValidator psv    = PlotSettingsValidator.Current;
                                        PlotSettings          ps     = new PlotSettings(ltr.ModelType);
                                        psv.SetPlotConfigurationName(ps, "AutoCAD PDF (High Quality Print).pc3", null);
                                        psv.RefreshLists(ps);
                                        layouts.Add(ltr);
                                        editor.WriteMessage(Environment.NewLine + ltr.LayoutName);
                                        editor.WriteMessage(Environment.NewLine + ltr.PlotPaperSize.ToString());
                                        editor.WriteMessage(Environment.NewLine + ltr.PlotSettingsName);
                                    }
                                }
                                layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
                                string filename = Path.ChangeExtension(dwgDB.Filename, "pdf");

                                MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
                                plotter.Publish();
                                editor.WriteMessage(Environment.NewLine + dwgDB.Filename + " успешно экспортирован");
                                acTrans.Commit();
                            }
                        }
                    }
                    Acad.SetSystemVariable("BACKGROUNDPLOT", bgp);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception e)
                {
                    editor.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
                }
            }
        }
コード例 #22
0
ファイル: RectangleJig.cs プロジェクト: kojtoLtd/KojtoCAD
        private bool IsometricSnapIsOn( )
        {
            var snapVarValue = Application.GetSystemVariable("Snapstyl").ToString();

            return(snapVarValue == "1");
        }
コード例 #23
0
ファイル: Convert_App.cs プロジェクト: 15831944/EM
        convertBubble()
        {
            ObjectId idWO  = ObjectId.Null; //wipeout
            ObjectId idSM  = ObjectId.Null; //symbol
            ObjectId idTX  = ObjectId.Null; //text
            ObjectId idLDR = ObjectId.Null; //leader

            Point3d pnt3d  = Pub.pnt3dO;
            Object  osMode = SnapMode.getOSnap();

            int scale = Misc.getCurrAnnoScale();

            TypedValue[] tvs = new TypedValue[2];
            tvs.SetValue(new TypedValue((int)DxfCode.Start, "INSERT"), 0);
            tvs.SetValue(new TypedValue((int)DxfCode.LayerName, "BUBBLE"), 1);

            SelectionSet ss = Select.buildSSet(tvs);

            ObjectId[] idsBR = ss.GetObjectIds();

            ObjectId idLayer   = Layer.manageLayers("BUBBLE");
            double   angleView = -(double)Application.GetSystemVariable("VIEWTWIST");

            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction tr = BaseObjs.startTransactionDb())
            {
                DBDictionary     groups = (DBDictionary)db.GroupDictionaryId.GetObject(OpenMode.ForRead);
                BlockTableRecord ms     = Blocks.getBlockTableRecordMS();

                foreach (ObjectId idBR in idsBR)
                {
                    BlockReference br = (BlockReference)tr.GetObject(idBR, OpenMode.ForWrite);

                    if (br.Name == "CWP")
                    {
                        br.ObjectId.delete();
                        continue;
                    }

                    Scale3d  scaleFactor = br.ScaleFactors;
                    Matrix3d m3d         = scaleFactor.GetMatrix();
                    double   scaleBR     = m3d.GetScale();

                    double              rotation = br.Rotation;
                    Point3d             pnt3dPos = br.Position;
                    string              name     = br.Name;
                    string              value    = string.Empty;
                    Entity              ent      = null;
                    AttributeCollection atts     = br.AttributeCollection;
                    foreach (ObjectId id in atts)
                    {
                        ent = id.getEnt();
                        AttributeReference attDef = (AttributeReference)ent;
                        value = attDef.TextString;
                    }

                    Vector3d v3d = new Vector3d(scaleBR * 1.35, scaleBR * 1.35, 0);
                    v3d = v3d * 1.1;
                    Point3d pnt3dLL = pnt3dPos - v3d;
                    Point3d pnt3dUR = pnt3dPos + v3d;
                    Point3d pnt3dLR = new Point3d(pnt3dUR.X, pnt3dLL.Y, 0.0);
                    Point3d pnt3dUL = new Point3d(pnt3dLL.X, pnt3dUR.Y, 0.0);

                    Point3dCollection pnts3d = new Point3dCollection {
                        pnt3dLL,
                        pnt3dLR,
                        pnt3dUR,
                        pnt3dUL,
                        pnt3dLL
                    };

                    tvs = new TypedValue[2];
                    tvs.SetValue(new TypedValue((int)DxfCode.Start, "LWPOLYLINE"), 0);
                    tvs.SetValue(new TypedValue((int)DxfCode.LayerName, "BUBBLE"), 1);

                    Point3d pnt3dBeg = Pub.pnt3dO;
                    Point3d pnt3dEnd = Pub.pnt3dO;
                    Point3d pnt3dMid = Pub.pnt3dO;

                    double             bulge = 0.0, delta0 = 0.0;
                    double             dirChord, dirTarget, disChord, disTarget;
                    Polyline           poly;
                    ObjectIdCollection idsLdr = new ObjectIdCollection();
                    ss = Select.buildSSet(tvs, pnts3d);
                    if (ss != null && ss.Count > 0)
                    {
                        ObjectId[] ids = ss.GetObjectIds();
                        foreach (ObjectId id in ids)
                        {
                            poly = (Polyline)id.getEnt();
                            if (poly != null)
                            {
                                pnt3dBeg = poly.StartPoint;
                                pnt3dMid = poly.GetPoint3dAt(1);
                                pnt3dEnd = poly.EndPoint;

                                bulge     = poly.GetBulgeAt(1);
                                delta0    = Geom.getDelta(bulge);
                                disChord  = pnt3dMid.getDistance(pnt3dEnd);
                                disTarget = (0.5 * disChord) / System.Math.Cos(delta0 / 4);
                                dirChord  = pnt3dMid.getDirection(pnt3dEnd);
                                dirTarget = dirChord - delta0 / 4;
                                pnt3dMid  = pnt3dMid.traverse(dirTarget, disTarget);

                                //dirTarget = pnt3dEnd.getDirection(pnt3dPos);    //direction towards center of circle
                                //disTarget = pnt3dEnd.getDistance(pnt3dPos);     //distance from original end point to center
                                //disTarget = disTarget - Pub.radius * scale * 0.85;    //0.85 per addSymbolAndWipeout  - factors to adjust symbols for best fit.
                                //pnt3dEnd = pnt3dEnd.traverse(dirTarget, disTarget);

                                pnt3dEnd = pnt3dPos;

                                pnts3d = new Point3dCollection {
                                    pnt3dBeg,
                                    pnt3dMid,
                                    pnt3dEnd
                                };
                                ObjectId idLdr = Ldr.addLdr(pnts3d, idLayer, 0.09 * scale, 0, clr.byl, ObjectId.Null, spline: true);
                                idsLdr.Add(idLdr);
                                poly.ObjectId.delete();
                            }
                        }
                    }

                    idSM = Base_Tools45.Draw.addSymbolAndWipeout(pnt3dPos, angleView, out idWO, Pub.radius, 1024, true);
                    idSM.moveToTop();
                    idSM.moveBelow(new ObjectIdCollection {
                        idWO
                    });
                    if (idsLdr.Count > 0)
                    {
                        idWO.moveBelow(idsLdr);
                    }
                    Color color = new Color();
                    color = Color.FromColorIndex(ColorMethod.ByLayer, 256);
                    idTX  = Txt.addMText(value, pnt3dPos, angleView, 0.8, 0.09, AttachmentPoint.MiddleCenter, "Annotative", "BUBBLE", color, Pub.JUSTIFYCENTER);
                    br.ObjectId.delete();

                    Draw.addXData(idSM, scale, idTX, idsLdr, idWO, 1024, "0".stringToHandle(), "");
                    //DBObjectCollection dbObjs = new DBObjectCollection();
                    //ent = (Entity)br;
                    //ent.Explode(dbObjs);
                    //foreach(Autodesk.AutoCAD.DatabaseServices.DBObject dbObj in dbObjs){
                    //    Autodesk.AutoCAD.DatabaseServices.Entity e = (Autodesk.AutoCAD.DatabaseServices.Entity)dbObj;
                    //    ms.AppendEntity(e);
                    //    tr.AddNewlyCreatedDBObject(e, true);
                    //    if(e.GetType() == typeof(Circle)){
                    //        foreach (DBDictionaryEntry entry in groups)
                    //        {
                    //            ObjectId idGrp = entry.Value;
                    //            Group group = (Group)tr.GetObject(idGrp, (OpenMode.ForRead));
                    //            ObjectId[] ids = group.GetAllEntityIds();
                    //            List<ObjectId> lstIDs = new List<ObjectId>();
                    //            foreach (ObjectId id in ids)
                    //                lstIDs.Add(id);
                    //            if (lstIDs.Contains(idBR))
                    //            {
                    //                group.UpgradeOpen();
                    //                foreach (ObjectId idEnt in lstIDs)
                    //                {
                    //                    group.Remove(idEnt);
                    //                    idEnt.delete();
                    //                }
                    //                group.Erase();
                    //                break;
                    //            }
                    //        }
                    //    }
                    //    e.ObjectId.delete();
                    //}
                }
                tr.Commit();
            }

            SnapMode.setOSnap((int)osMode);
        }
コード例 #24
0
ファイル: Exporter.cs プロジェクト: alx1808/Parifizierung
        public void ExportPari()
        {
            log.Info("ExportPari");
            try
            {
                var           factory  = new Factory();
                IPariDatabase database = factory.CreatePariDatabase();

                if (!CheckTableValidity(database))
                {
                    return;
                }

                var blockReader = new BlockReader();
                blockReader.ReadBlocksFromModelspace();
                var blockInfos   = blockReader.BlockInfos;
                var wohnungInfos = blockReader.WohnungInfos;
                var projektInfo  = blockReader.ProjektInfo;
                if (projektInfo == null)
                {
                    var msg = string.Format(CultureInfo.CurrentCulture, "Der ProjektInfo-Block existiert nicht in der Zeichnung!");
                    log.Error(msg);
                    Application.ShowAlertDialog(msg);
                    return;
                }
                var dwgName   = Application.GetSystemVariable("DwgName").ToString();
                var dwgPrefix = Application.GetSystemVariable("DwgPrefix").ToString();
                projektInfo.DwgName   = dwgName;
                projektInfo.DwgPrefix = dwgPrefix;
                var projektId = database.GetProjektId(projektInfo);
                if (projektId >= 0)
                {
                    var msg = string.Format(CultureInfo.CurrentCulture, "Das Projekt '{0}' existiert bereits! ProjektId = {1}.", projektInfo.Bauvorhaben, projektId);
                    log.Error(msg);
                    Application.ShowAlertDialog(msg);
                    return;
                }

                var tableBuilder = new TableBuilder();
                tableBuilder.Build(blockInfos, wohnungInfos);

                if (CheckInvalidCategoriesAskUser(tableBuilder))
                {
                    return;
                }


                var doc    = Application.DocumentManager.MdiActiveDocument;
                var editor = doc.Editor;

                database.SaveToDatabase(tableBuilder, projektInfo);

                var raumWithoutTop = tableBuilder.RaumTable.Where(x => string.IsNullOrEmpty(x.Top)).ToList();
                if (raumWithoutTop.Count > 0)
                {
                    editor.WriteMessage("\nFolgende Räume haben keine TOP-Information: ");
                    editor.WriteMessage("\n-----------------------------------------------------------------");
                    foreach (var ri in raumWithoutTop)
                    {
                        var msg = string.Format(CultureInfo.CurrentCulture, "\nRaum: {0}\tGeschoss: {1}\tNutzwert: {2}\tHandle: {3}", ri.Raum, ri.Lage, ri.RNW, ri.AcadHandle);
                        log.Warn(msg);
                        editor.WriteMessage(msg);
                    }
                }

                editor.WriteMessage("\n\nExport beendet.");
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                Application.ShowAlertDialog(ex.Message);
            }
        }
コード例 #25
0
 private static bool ShouldTransformCoords()
 {
     return(transformToUcs && (0 == (short)AcadApp.GetSystemVariable("WORLDUCS")));
 }
コード例 #26
0
ファイル: Exporter.cs プロジェクト: alx1808/Parifizierung
        public void ExcelPari()
        {
            log.Info("ExcelPari");
            try
            {
                var fact          = new Factory();
                var excelExporter = fact.CreateVisualOutputHandler();
                var database      = fact.CreatePariDatabase();

                var dwgPrefix = Application.GetSystemVariable("DwgPrefix").ToString();
                var dwgName   = Application.GetSystemVariable("DwgName").ToString();

                int projektId = -1;
                var doc       = Application.DocumentManager.MdiActiveDocument;
                _AcEd.PromptIntegerOptions inOpts = new _AcEd.PromptIntegerOptions("\nId des Projekts, für das eine Exceldatei erstellt werden soll <Return für aktuelles>: ");
                inOpts.AllowNegative = false;
                inOpts.AllowNone     = true;
                var intRes = doc.Editor.GetInteger(inOpts);
                if (intRes.Status == _AcEd.PromptStatus.OK)
                {
                    projektId = intRes.Value;
                    var pi = database.ListProjInfos().FirstOrDefault(x => x.ProjektId == projektId);
                    if (pi == null)
                    {
                        var msg = string.Format(CultureInfo.CurrentCulture, "Das Projekt mit Id {0} existiert nicht in der Datenbank!", projektId);
                        log.Error(msg);
                        Application.ShowAlertDialog(msg);
                        return;
                    }
                }
                else if (intRes.Status == _AcEd.PromptStatus.None)
                {
                    var blockReader = new BlockReader();
                    blockReader.ReadBlocksFromModelspace();
                    var projektInfo = blockReader.ProjektInfo;
                    if (projektInfo == null)
                    {
                        var msg = string.Format(CultureInfo.CurrentCulture, "Der ProjektInfo-Block existiert nicht in der Zeichnung!");
                        log.Error(msg);
                        Application.ShowAlertDialog(msg);
                        return;
                    }

                    projektInfo.DwgName   = dwgName;
                    projektInfo.DwgPrefix = dwgPrefix;

                    projektId = database.GetProjektId(projektInfo);
                    if (projektId < 0)
                    {
                        var msg = string.Format(CultureInfo.CurrentCulture, "Das Projekt wurde nicht gefunden in der Datenbank!");
                        log.Error(msg);
                        Application.ShowAlertDialog(msg);
                        return;
                    }
                }

                doc.Editor.WriteMessage("\nExport wird gestartet...");
                //var targetFile = Path.Combine(dwgPrefix, Path.GetFileNameWithoutExtension(dwgName) + "_NW" + ".xlsx");
                excelExporter.ExportNW(database, null, projektId);
                excelExporter.ExportNF(database, null, projektId);
                doc.Editor.WriteMessage("\nExport fertiggestellt.");
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                Application.ShowAlertDialog(ex.Message);
            }
        }
コード例 #27
0
        //[CommandMethod("PolylineToCSV", "plcsv", CommandFlags.Modal | CommandFlags.UsePickSet)]
        public static void ExportPolyPointsToCSV()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;

            var db = doc.Database;

            var ed = doc.Editor;

            try
            {
                using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction())
                {
                    var dec = ((short)Application.GetSystemVariable("LUPREC")).ToString();

                    var pso = new PromptSelectionOptions();

                    pso.MessageForRemoval = "\n >>  Nothing selected....";

                    pso.MessageForAdding = "\n  >>  Select a single polyline >> ";

                    pso.AllowDuplicates = false;

                    pso.SingleOnly = true;

                    var sf = new SelectionFilter
                                 (new[] { new TypedValue(0, "lwpolyline") });

                    var res = ed.GetSelection(pso, sf);

                    if (res.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    var sb  = new StringBuilder();
                    var ids = res.Value.GetObjectIds();

                    var poly = (Polyline)tr.GetObject(ids[0], OpenMode.ForRead, false);
                    for (var i = 0; i < poly.NumberOfVertices; i++)
                    {
                        var pt     = poly.GetPoint2dAt(i);
                        var vexstr = string.Format("{0:f" + dec + "};{1:f" + dec + "}", pt.X, pt.Y);
                        sb.AppendLine(vexstr);
                    }
                    var csvFile = string.Empty;

                    var sfd = new SaveFileDialog();
                    sfd.ValidateNames    = true;
                    sfd.Title            = "Save polyline vertices to CSV file";
                    sfd.DefaultExt       = ".csv";
                    sfd.InitialDirectory = @"C:\PGA\";
                    sfd.RestoreDirectory = true;

                    if (sfd.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    csvFile = sfd.FileName;

                    // write point to defined file
                    using (var sw = new StreamWriter(csvFile))
                    {
                        sw.Write(sb.ToString());

                        sw.Flush();
                    }
                    sfd.Dispose(); // non resident object, so kill 'em

                    tr.Commit();
                }
            }
            catch (AcadRuntime.Exception ex)
            {
                ed.WriteMessage("\n" + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
            }
        }