public static IEnumerable <Configs> GetConfigs()
            {
                var list = new List <Configs>();

                try
                {
                    var swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");

                    IModelDoc2 swModel = swApp.IActiveDoc2;
                    swModel.Extension.ViewDisplayRealView = false;

                    if (!IsSheetMetalPart((IPartDoc)swModel))
                    {
                        MessageBox.Show(@"Деталь не из листового материала");
                    }

                    var swModelConfNames2 = (string[])swModel.GetConfigurationNames();

                    foreach (var configName in from name in swModelConfNames2
                             let config = (Configuration)swModel.GetConfigurationByName(name)
                                          where !config.IsDerived()
                                          select name)
                    {
                        list.Add(new Configs
                        {
                            Name       = configName,
                            IsCheacked = true
                        });
                    }
                }
                catch (Exception exception)
                {
                    //MessageBox.Show(exception.ToString());
                }

                return(list);
            }
Exemple #2
0
 public bool GetInstance()
 {
     try
     {
         _excelapp = (Application)Marshal.GetActiveObject("Excel.Application");
         InitExcel();
         return(true);
     }
     catch (COMException)
     {
         try
         {
             _excelapp = new Application();
             InitExcel();
             return(true);
         }
         catch (COMException ex)
         {
             ErrorDialog.Show(ex);
             ComCleanUp();
             return(false);
         }
     }
 }
Exemple #3
0
        private static WordApp GetWordApplication()
        {
            Word.Application winObj = null;
            WordAPPType      type   = WordAPPType.GET;

            try
            {
                winObj = (Word.Application)Marshal.GetActiveObject("Word.Application");
                type   = WordAPPType.GET;
            }
            catch (Exception)
            {
                if (winObj == null)
                {
                    winObj = new Word.Application();
                    type   = WordAPPType.NEW;
                }
            }
            WordApp wordApp = new WordApp();

            wordApp.Type = type;
            wordApp.APP  = winObj;
            return(wordApp);
        }
Exemple #4
0
        public static ISldWorks ConnectToSolidWorks()
        {
            if (SwApp != null)
            {
                return(SwApp);
            }
            else
            {
                Debug.Print("connect to solidworks on " + DateTime.Now);
                try
                {
                    SwApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                }
                catch (COMException)
                {
                    try
                    {
                        SwApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application.23");//2015
                    }
                    catch (COMException)
                    {
                        try
                        {
                            SwApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application.26");//2018
                        }
                        catch (COMException)
                        {
                            MessageBox.Show("Could not connect to SolidWorks.", "SolidWorks", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            SwApp = null;
                        }
                    }
                }

                return(SwApp);
            }
        }
Exemple #5
0
        private void Send_Click(object sender, RoutedEventArgs e)
        {
            if (tbTo.Text == "" || tbSubject.Text == "" || tbBody.Text == "")
            {
                MessageBox.Show("Please make sure recipient and subject is not empty", "message", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else
            {
                Outlook._Application _app;

                try
                {
                    _app = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
                }
                catch (Exception)
                {
                    _app = new Outlook.Application();
                }
                try
                {
                    Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
                    mail.To         = _Recipient;
                    mail.Subject    = tbSubject.Text;
                    mail.Body       = tbBody.Text;
                    mail.Importance = Outlook.OlImportance.olImportanceNormal;
                    ((Outlook._MailItem)mail).Send();
                    db.RecordMessage(tbSubject.Text, tbBody.Text, "Email", _CompanyId, int.Parse(_Sender));
                    tbSubject.Text = string.Empty;
                    tbBody.Text    = string.Empty;
                    this.Close();
                }catch (System.Runtime.InteropServices.COMException ex)
                {
                    MessageBox.Show("Error sending email" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Exemple #6
0
 //form실행과 동시에 카티아 실행 & dpcument 실행한다---------------------
 private void Form1_Load(object sender, EventArgs e)
 {
     try
     {
         catia = (INFITF.Application)Marshal.GetActiveObject("CATIA.Application");
     }
     catch (Exception)
     {
         catia         = (INFITF.Application)Activator.CreateInstance(Type.GetTypeFromProgID("CATIA.Application"));
         catia.Visible = true;
     }
     ///*
     //partDOcument 실행하기-----------------
     try
     {
         prtDoc = (PartDocument)catia.ActiveDocument;
     }
     catch (Exception)
     {
         MessageBox.Show("활성된 문서가 없습니다.");
         //PartDocument prtDoc = (PartDocument)catia.Documents.Add("Part");
     }
     //*/
 }
Exemple #7
0
 /// <summary>
 /// 连接并且返回可用的<see cref="_Application"/>,如果连接失败返回null,可能会改变<see cref="App"/>
 /// </summary>
 public static _Application AttachApp()
 {
     if (App.Check())
     {
         return(App);
     }
     else
     {
         do
         {
             try
             {
                 //连接Excel进程
                 App = (_Application)Marshal.GetActiveObject("Excel.Application");
             }
             catch (COMException)
             {
                 App = null;
                 break;
             }
         } while (!App.Check());
         return(App?.ChangeForRPA());
     }
 }
 /// <summary>
 /// Sets the excel objects to their corresponding COM objects.
 /// </summary>
 public void SetExcelObjects()
 {
     // Sets workbook to path specified    .
     try
     {
         myApp   = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
         myBooks = myApp.Workbooks;
         myBook  = myBooks["DG Inventory Management.xlsx"];
         mySheet = myBook.Sheets["Marlin Steel"];
         setRange();
         excelObjSet = true;
         Console.WriteLine("Excel Objects Set.");
     }
     catch (NullReferenceException e)
     {
         // If file is not found
         Console.WriteLine(e.Message);
     }
     catch (Exception e)
     {
         // Other problemsW
         Console.WriteLine(e.Message);
     }
 }
Exemple #9
0
        /// <summary>
        /// Создание нового документа.
        /// </summary>
        public void CreateNewDocument()
        {
            _invApp = null;
            try
            {
                _invApp = (Application)Marshal.GetActiveObject("Inventor.Application");
            }
            catch (Exception)
            {
                try
                {
                    //Если не получилось перехватить приложение - выкинется ексепшн на то,
                    //что такого активного приложения нет. Попробуем создать приложение вручную.
                    Type invAppType = Type.GetTypeFromProgID("Inventor.Application");

                    _invApp         = (Application)Activator.CreateInstance(invAppType);
                    _invApp.Visible = true;
                }
                catch (Exception)
                {
                    //MessageBox.Show(ex2.ToString());
                    System.Windows.Forms.MessageBox.Show(@"Не получилось запустить инвентор.");
                }
            }

            _partDoc = (PartDocument)_invApp.Documents.Add //В открытом приложении создаем документ
                           (DocumentTypeEnum.kPartDocumentObject,
                           _invApp.FileManager.GetTemplateFile
                               (DocumentTypeEnum.kPartDocumentObject,
                               SystemOfMeasureEnum.kMetricSystemOfMeasure));

            PartDefinition = _partDoc.ComponentDefinition; //Описание документа
            //  AssemblyDocument assDoc = (AssemblyDocument)_invApp.ActiveDocument;
            //_assemblyDef = assDoc.ComponentDefinition;
            TransientGeometry = _invApp.TransientGeometry; //инициализация метода геометрии
        }
Exemple #10
0
        public static TSD.TSDDocument TSDDocument()
        {
            TSD.TSDDocument tSDDocument = null;

            try
            {
                object aObject = Marshal.GetActiveObject("Document");

                if (aObject != null)
                {
                    tSDDocument = aObject as TSD.TSDDocument;
                    Core.Modify.ReleaseCOMObject(aObject);
                    tSDDocument = null;
                }
            }
            catch (Exception exception)
            {
                string message = exception.Message;
            }

            tSDDocument = new TSD.TSDDocument();

            return(tSDDocument);
        }
        private void Open()
        {
            const string strProgId = "AutoCAD.Application";

            //获取正在运行的AutoCAD实例;
            try
            {
                acAppComObj = (AcadApplication)Marshal.GetActiveObject(strProgId);
            }
            catch //没有正在运行的实例时出错;
            {
                try
                {
                    //创建新的AutoCAD实例;
                    acAppComObj = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgId), true);
                }
                catch
                {
                    //创建新实例不成功就显示信息并退出;
                    //MessageBox.Show("创建新实例不成功");
                    return;
                }
            }
        }
Exemple #12
0
        private static NameSpace GetMapiNamespace()
        {
            NameSpace nameSpace;

            Application application;

            // Check whether there is an Outlook process running.
            if (Process.GetProcessesByName("OUTLOOK").Any())
            {
                // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                application = (Application)Marshal.GetActiveObject("Outlook.Application");
                nameSpace   = application.GetNamespace("MAPI");
            }
            else
            {
                // If not, create a new instance of Outlook and log on to the default profile.
                application = new Application();
                nameSpace   = application.GetNamespace("MAPI");
                nameSpace.Logon("", "", Missing.Value, Missing.Value);
            }

            // Return the Outlook Application object.
            return(nameSpace);
        }
Exemple #13
0
        /// <summary>
        /// Constructor
        /// </summary>
        public static AcadApplication GetApplication()
        {
            // "AutoCAD.Application.17" uses 2007 or 2008, whichever was most recently run
            // "AutoCAD.Application.17.1" uses 2008, specifically
            const string progID = "AutoCAD.Application.17";

            AcadApplication acApp = null;

            try
            {
                acApp = (AcadApplication)Marshal.GetActiveObject(progID);
            }
            catch
            {
                try
                {
                    Type acType = Type.GetTypeFromProgID(progID);
                    acApp = (AcadApplication)Activator.CreateInstance(acType, true);
                }
                catch { }
            }

            return(acApp);
        }
Exemple #14
0
        public AutoCadConnector()
        {
            try
            {
                // Upon creation, attempt to retrieve running instance

                _application = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application.16");
            }

            catch (COMException)
            {
                // Create an instance and set flag to indicate this

                _application = new AcadApplicationClass();

                _initialized = true;
            }
            catch (Exception)
            {
                MessageBox.Show(@"调用CAD程序出错!", @"批量打印", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _application = null;
                _initialized = false;
            }
        }
Exemple #15
0
        public static Application RegisterAndGetApp()
        {
            Application excel = null;

            // get excel, throw exception if it is not
            var officeType = Type.GetTypeFromProgID("Excel.Application");

            if (officeType == null)
            {
                throw new Exception("Excel is not installed.");
            }

            try
            {
                excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            }
            catch (COMException)
            {
            }

            if (excel == null)
            {
                excel = new Microsoft.Office.Interop.Excel.Application();
            }

            if (excel == null)
            {
                throw new Exception("Excel could not be opened.");
            }

            dynSettings.Controller.DynamoModel.CleaningUp += DynamoModelOnCleaningUp;

            excel.Visible = ShowOnStartup;

            return(excel);
        }
        /// <summary>
        /// Get already active Kompas application
        /// </summary>
        /// <returns>true if operation successful, false in case of error</returns>
        private bool GetActiveApp()
        {
            if (KompasObject == null)
            {
                try
                {
                    KompasObject = (KompasObject)Marshal.GetActiveObject("KOMPAS.Application.5");
                }
                catch
                {
                    return(false);
                }
            }

            if (KompasObject == null)
            {
                return(false);
            }

            KompasObject.Visible = true;
            KompasObject.ActivateControllerAPI();

            return(true);
        }
Exemple #17
0
        internal static bool ExportToOutlookNote(string text)
        {
            dynamic outlook = null;

            try
            {
                try
                {
                    // if Outlook already runs
                    outlook = Marshal.GetActiveObject("Outlook.Application");
                }
                catch
                {
                    PNMessageBox.Show(PNLang.Instance.GetMessageText("outlook_not_running", "MS Outlook application is not running. Please, start the application and try again."), PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return(false);
                }

                var note = outlook.CreateItem(5);
                note.Body = text;
                note.Save();
                return(true);
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
                return(false);
            }
            finally
            {
                if (outlook != null)
                {
                    Marshal.ReleaseComObject(outlook);
                    GC.GetTotalMemory(true);
                }
            }
        }
Exemple #18
0
        private static void InitSolidWorks()
        {
            Console.WriteLine("InitSolidWorks");
            try
            {
                sldWoksApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            }
            catch
            {
                if (sldWoksApp == null)
                {
                    Process[] processes = Process.GetProcessesByName("SLDWORKS");
                    foreach (var process in processes)
                    {
                        process.Kill();
                    }

                    sldWoksApp = new SldWorks()
                    {
                        Visible = true
                    };
                }
            }
        }
Exemple #19
0
            private static object GetAcadApplication(IProcess process)
            {
                Stopwatch stopwatch = Stopwatch.StartNew();

                process.WaitForInputIdle(ReadyTimeout.Milliseconds);
                while (stopwatch.Elapsed < ReadyTimeout)
                {
                    try
                    {
                        var application = Marshal.GetActiveObject("AutoCAD.Application");
                        if (application != null)
                        {
                            return(application);
                        }
                    }
                    catch (COMException)
                    {
                    }

                    Thread.Sleep(ReadyPollInterval);
                }

                throw new TimeoutException("Unable to acquire the AutoCAD automation object from the running object table.");
            }
Exemple #20
0
        private Window GetSpecificWordWindow(string targetName)
        {
            Window window = null;

            try
            {
                if (_wordInstance == null)
                {
                    _wordInstance = (Application)Marshal.GetActiveObject("Word.Application") ?? null;
                }

                // If there are any open windows (documents), get their names.
                if (_wordInstance.Windows.Count > 0)
                {
                    Window wordWindow;

                    for (int i = 0; i < _wordInstance.Windows.Count; i++)
                    {
                        object a = i + 1;
                        wordWindow = _wordInstance.Windows.get_Item(ref a);

                        if (wordWindow.Document.FullName == targetName)
                        {
                            window = wordWindow;
                            break;
                        }
                    }
                }
            }
            catch (COMException ex)
            {
                //throw new COMException(ex.Message);
                _wordInstance = CreateNewWordInstance();
            }
            return(window);
        }
Exemple #21
0
 private void ManulInputLine_Click(object sender, EventArgs e)
 {
     tAcadApplication = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application");
     Console.Write("AAA");
     CadOprator.ReadSingeLine();
 }
Exemple #22
0
 private void ManulInputPoint_Click(object sender, EventArgs e)
 {
     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
             {
                 do
                 {
                     double[] point = new double[3];
                     caddocument.Utility.Prompt("请选择一个点:");
                     try
                     {
                         point = caddocument.Utility.GetPoint();
                         caddocument.Utility.Prompt("如果取消继续输入请按ESC,");
                     }
                     catch (System.Exception)
                     {
                         break;
                     }
                     try
                     {
                         double[] Tpoint = CadOprator.TackAix(point, RefPoint, ApplyPlantAix.Checked);
                         if (Tpoint.Length == 3)
                         {
                             DataRow        = datatable.NewRow();
                             DataRow["序号"]  = index;
                             DataRow["X坐标"] = Convert.ToString(Tpoint[0]);
                             DataRow["Y坐标"] = Convert.ToString((Tpoint[1]));
                             DataRow["Z坐标"] = Convert.ToString((Tpoint[2]));
                             DataRow["R角"]  = Convert.ToString(0);
                             String Ttrack = string.Empty;
                             if (SingeRoadSelected.Checked)
                             {
                                 Ttrack = "SingerTrack";
                             }
                             else
                             {
                                 Ttrack = "DoubleTrack";
                             }
                             DataRow["TrackType"] = Ttrack;
                             datatable.Rows.Add(DataRow);
                             dataview            = new DataView(datatable);
                             DataGrid.DataSource = dataview;
                             DataGrid.Update();
                             index += 1;
                         }
                     }
                     catch (System.Exception)
                     {
                         throw;
                     }
                 }while (index != 99999);
                 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!");
     }
 }
Exemple #23
0
 public void test()
 {
     Excel.Application excelApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); //获取打开了的Excel应用程序
 }
Exemple #24
0
 public PropsToParentPart()
 {
     swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
 }
Exemple #25
0
        protected override void StartLoop(NativeActivityContext context)
        {
            var filename   = Filename.Get(context);
            var maxresults = MaxResults.Get(context);

            filename = Environment.ExpandEnvironmentVariables(filename);
            Application activeObject = null;
            object      missing      = Type.Missing;
            Document    document     = null;

            try
            {
                activeObject = (Application)Marshal.GetActiveObject("Word.Application");
                foreach (Document current in activeObject.Documents)
                {
                    if (current.FullName == filename)
                    {
                        document = current;
                        break;
                    }
                }
            }
            catch
            {
                activeObject = null;
            }
            finally
            {
                if (activeObject == null)
                {
                    activeObject = (Application)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("000209FF-0000-0000-C000-000000000046")));
                }
                activeObject.Visible = true;
            }
            object ofilename = filename;

            if (document == null)
            {
                document = activeObject.Documents.Open(ref ofilename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            }
            var    p     = document.Content.Paragraphs;
            string text  = "";
            int    index = Index.Get(context);

            Count.Set(context, p.Count);
            var result = new List <string>();

            if (Index.Expression == null)
            {
                for (var i = 0; i < p.Count; i++)
                {
                    result.Add(p[i + 1].Range.Text);
                    text += p[i + 1].Range.Text;
                    if (maxresults > 0 && maxresults == result.Count)
                    {
                        break;
                    }
                }
            }
            else
            {
                if (p.Count < index)
                {
                    throw new Exception("filename only contains " + p.Count + " Paragraphs");
                }
                for (var i = (index - 1); i < p.Count; i++)
                {
                    result.Add(p[i + 1].Range.Text);
                    text += p[i + 1].Range.Text;
                    if (maxresults > 0 && maxresults == result.Count)
                    {
                        break;
                    }
                }

                //text = p[index].Range.Text;
            }
            Text.Set(context, text);
            IEnumerator <string> _enum = result.ToList().GetEnumerator();

            _elements.Set(context, _enum);
            bool more = _enum.MoveNext();

            if (more)
            {
                if (Body != null)
                {
                    context.ScheduleAction(Body, _enum.Current, OnBodyComplete);
                }
            }
        }
Exemple #26
0
        private void ДобавитьТаблицуВидов_Click(object sender, RoutedEventArgs e)
        {
            // MessageBox.Show("Откройте чертеж и выделете основной вид модели!\n Затем нажмите 'OK'");

            try
            {
                var swApp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                var swModel = (IModelDoc2)swApp.IActiveDoc;

                var swDraw = (DrawingDoc)swModel;

                //Select View
                swModel.ClearSelection2(true);
                var getFirstView = swDraw.GetCurrentSheet().GetViews()[0];

                //swDraw.GetFirstView();
                //var getFirstView = swDraw.IActiveDrawingView;

                var referencedDocument = (IModelDoc2)getFirstView.ReferencedDocument;


                #region From swApp

                var docName     = referencedDocument.GetTitle();
                var configNames = referencedDocument.GetConfigurationNames();
                var обозначения = new List <string>();
                //foreach (var configName in configNames)
                //{
                //    if (configName == "00")
                //    {
                //        обозначения.Add(docName);
                //    }
                //    else
                //    {
                //        обозначения.Add("-" + configName);
                //    }
                //}

                #endregion

                #region VentsMaterials dll

                var vm    = new VentsMaterials.SetMaterials();
                var tosql = new VentsMaterials.ToSQL();
                VentsMaterials.ToSQL.Conn = Settings.Default.ConnectionToSQL;

                swApp.ActivateDoc(referencedDocument.GetTitle());
                var configNamesDll = vm.GetConfigurationNames();
                swApp.CloseDoc(Path.GetFileName(referencedDocument.GetPathName()));


                foreach (var configName in configNamesDll)
                {
                    if (configName == "00")
                    {
                        обозначения.Add(docName);
                    }
                    else
                    {
                        обозначения.Add("-" + configName);
                    }
                }

                #endregion

                InsertTableImg(swModel, обозначения);

                //  MessageBox.Show("Готово.");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
Exemple #27
0
 /// <summary>
 /// Initializes this instance.
 /// </summary>
 public void Init()
 {
     _swApp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
     _swModel = (IModelDoc2)_swApp.IActiveDoc;
     _swDraw  = (DrawingDoc)_swModel;
 }
Exemple #28
0
        private void ДобавитьТаблицуРазмеров_Click(object sender, RoutedEventArgs e)
        {
            var classf = new SizesClass();

            ТаблицаВидов.ItemsSource = classf.SheetSizes("DRW1");

            return;


            var swApp   = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
            var swModel = (IModelDoc2)swApp.IActiveDoc;

            var swDraw = (DrawingDoc)swModel;

            //Select View
            swModel.ClearSelection2(true);

            var getFirstView = (View)swDraw.GetCurrentSheet().GetViews()[0];

            var views = swDraw.GetCurrentSheet().GetViews();

            // Получить виды

            var getFirstView2 = (View)swDraw.get_Sheet("DRW1").GetViews()[Convert.ToInt32(getFirstView.get_IPosition())];

            MessageBox.Show(getFirstView2.Name);



            foreach (View view in views)
            {
                MessageBox.Show(view.Name + " - " + view.GetDimensionCount());

                var dimensionsForView = (string[])view.GetDimensionIds4();
                foreach (var d in dimensionsForView)
                {
                    MessageBox.Show(d);
                }

                //var dimensionsForView = (string[])view.GetDimensionDisplayString4();
                //foreach (var d in dimensionsForView)
                //{
                //    MessageBox.Show(d);
                //}

                //var dimensionsForView = (double[])view.GetDimensionDisplayInfo5();
                //foreach (var d in dimensionsForView)
                //{
                //    MessageBox.Show(d.ToString());
                //}
            }

            // ТаблицаВидов.ItemsSource = (View[])swDraw.GetCurrentSheet().GetViews();

            // Выделить размер
            swModel.Extension.SelectByID2("RD2@Чертежный вид11", "DIMENSION", 0, 0, 0, false, 0, null, 0);

            // Проставить букву
            swModel.EditDimensionProperties2(0, 0, 0, "", "", true, 9, 2, true, 12, 12, "M", "", false, "", "", false);

            // Проставить размер
            swModel.EditDimensionProperties2(0, 0, 0, "", "", false, 0, 2, true, 12, 12, "", "", true, "", "", false);
        }
Exemple #29
0
        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            try
            {
                new PropsToParentPart().CopyProperties();

                return;

                new CopyPropsToParentPart().CopyProperties();

                return;

                var swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");

                //var item = ExternalFileReferences.Get(swApp);
                //MessageBox.Show(item.ModelPathName + "\n" + item.ConfigName);

                var swModel = (IModelDoc2)swApp.IActiveDoc;
                //var swPart = (IPartDoc)swModel;
                var swFeat = (IFeature)swModel.FirstFeature();
                while ((swFeat != null))
                {
                    var FeatName = swFeat.Name;
                    try
                    {
                        if (swFeat.GetTypeName() == "Stock")
                        {
                            swFeat.Select2(false, -1);
                            MessageBox.Show("Before");
                            var copm = (IComponent2)swFeat;//.GetSpecificFeature2();

                            MessageBox.Show("After");
                            MessageBox.Show((copm == null).ToString());
                            MessageBox.Show("After 2");
                            //MessageBox.Show(copm.Visible.ToString());

                            return;

                            swModel.Extension.SelectByID2(FeatName, "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                            swModel.FeatEdit();
                            var editStatus = swFeat.GetEditStatus();
                            MessageBox.Show($"EditStatus - {editStatus}");

                            var swEnt = (Entity)swFeat;

                            MessageBox.Show($"{swEnt == null}\n{FeatName}\n\n{swEnt.GetType()}");

                            #region to delete

                            //{swEnt.Select(true)}

                            // var sdfvb = new AttributeDef(); sdfvb.AddParameter
                            // MessageBox.Show(swEnt.IFindAttribute(new AttributeDef()));

                            //MessageBox.Show(FeatName);
                            //int longstatus = 0;
                            //var model = swApp.ActivateDoc2(FeatName, false, ref longstatus);
                            //MessageBox.Show(model.GetType());
                            //MessageBox.Show(model.GetTitle() + "\n" + model.GetActiveConfiguration().Name);

                            //swModel.ClearSelection2(true);
                            //swModel.Extension.SelectByID2(FeatName, "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                            //swModel.ActivateSelectedFeature();

                            ////swModel.EntityProperties();

                            #endregion

                            swModel.Extension.SelectByID2(FeatName, "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                            var newDoc = swModel.Extension.Document;
                            MessageBox.Show(newDoc.GetTitle());

                            #region to delete

                            //var swCustProp = swModel.Extension.CustomPropertyManager["00"];
                            //string valOut;
                            //string materialId;
                            //swCustProp.Get4("Обозначение", true, out valOut, out materialId);

                            //MessageBox.Show(materialId);

                            //var swEnt = (Entity)swFeat;
                            //MessageBox.Show($"{swEnt == null}\n{FeatName}\n{swEnt.Select(true)}\n{swEnt.GetType()}");
                            //MessageBox.Show(swEnt.IGetComponent().GetType().ToString());

                            #endregion
                        }

                        #region To Delete

                        // swModel.ClearSelection2(true);
                        //   swModel.SelectByName(0, FeatName);

                        //var swSelMgr = (SelectionMgr)swModel.SelectionManager;
                        //var swEnt = (Entity)swSelMgr.GetSelectedObject6(1, -1);
                        //MessageBox.Show(component.GetImportedFileName());


                        //MessageBox.Show(swEnt.ModelName);

                        //var compone = swEnt.IGetComponent2();
                        //MessageBox.Show(compone.Name, compone.GetPathName());

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.StackTrace + "\n" + ex.Message);
                    }

                    #region To Delete

                    //if (swFeat.GetTypeName() == "Stock")
                    //{
                    //    var swEnt = (Entity)swFeat;
                    //    var compone = swEnt.IGetComponent2();

                    //    MessageBox.Show(compone.Name, compone.GetPathName());


                    //    swModel.ClearSelection2(true);
                    //    swModel.SelectByName(0, FeatName);

                    //    ////swModel.Extension.SelectByID2(FeatName, "BODYFEATURE", 0, 0, 0, false, 0, null, 0);
                    //    //var swSelMgr = (SelectionMgr)swModel.SelectionManager;
                    //    ////var component = (Feature)swSelMgr.GetSelectedObject6(1, -1);
                    //    ////MessageBox.Show(component.GetImportedFileName());

                    //    //var component = (Feature)swSelMgr.GetSelectedObject6(1, -1);
                    //    //var swEnt = (Entity)swFeat;
                    //    //var compone = (Component2)swEnt.GetComponent();

                    //    //MessageBox.Show(compone.GetPathName());
                    //}

                    #endregion

                    #region To Delete

                    //if (swFeat.GetTypeName() == "Stock")
                    //{

                    //   //Component2 comp = swFeat.Select(false);



                    //    var swSubFeat = swFeat.IGetFirstSubFeature();

                    //    while ((swSubFeat != null))
                    //    {
                    //        MessageBox.Show($"Name - {swSubFeat.Name}\nTypeName - {swSubFeat.GetTypeName()}");

                    //        //if (swSubFeat.GetTypeName() == "OneBend" || swSubFeat.GetTypeName() == "SketchBend")
                    //        //{
                    //        //    swSubFeat.Select(false);
                    //        //}
                    //        swSubFeat = (Feature)swSubFeat.GetNextSubFeature();
                    //    }

                    //}


                    // var swSubFeat = swFeat.IGetFirstSubFeature();

                    // while ((swSubFeat != null))
                    //   {
                    //MessageBox.Show($"Name - {swSubFeat.Name}\nTypeName - {swSubFeat.GetTypeName()}");

                    //if (swSubFeat.GetTypeName() == "OneBend" || swSubFeat.GetTypeName() == "SketchBend")
                    //{
                    //    swSubFeat.Select(false);
                    //}
                    //swSubFeat = (Feature)swSubFeat.GetNextSubFeature();
                    //  }

                    #endregion

                    swFeat = (Feature)swFeat.GetNextFeature();
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
Exemple #30
0
        private void button1_Click(object sender, EventArgs e)
        {
            INFITF.Application Catia;


            try
            {
                Catia = (INFITF.Application)Marshal.GetActiveObject("CATIA.Application");
            }


            catch
            {
                Catia         = (INFITF.Application)Activator.CreateInstance(Type.GetTypeFromProgID("CATIA.Application"));
                Catia.Visible = true;
            }
            INFITF.Documents Docts = Catia.Documents;

            MECMOD.PartDocument PrtDoc = (MECMOD.PartDocument)Docts.Add("Part");

            MECMOD.Part Prt = PrtDoc.Part;

            MECMOD.Bodies Bodis = Prt.Bodies;

            MECMOD.Body PartBody = Bodis.Item(1);

            MECMOD.Body Body = Bodis.Add();

            MECMOD.Sketches Skts = Body.Sketches;


            INFITF.Reference plane = (INFITF.Reference)Prt.OriginElements.PlaneXY;

            MECMOD.Sketch Skt = Skts.Add(plane);

            MECMOD.Factory2D Fac2D = Skt.OpenEdition();



            Point2D Pt1 = Fac2D.CreatePoint(50, 50);
            Point2D Pt2 = Fac2D.CreatePoint(50, 100);
            Point2D Pt3 = Fac2D.CreatePoint(100, 100);
            Point2D Pt4 = Fac2D.CreatePoint(100, 50);


            //  <<  Create Line >>
            Line2D Lin1 = Fac2D.CreateLine(50, 50, 50, 100);

            Line2D Lin2 = Fac2D.CreateLine(50, 100, 100, 100);

            Line2D Lin3 = Fac2D.CreateLine(100, 100, 100, 50);

            Line2D Lin4 = Fac2D.CreateLine(100, 50, 50, 50);

            //     Line2D Lin22 = MCreateLine(Fac2d, Pt1, Pt2);



            //라인의 시작점부터 마지막점을 결정

            Lin1.StartPoint = Pt1;
            Lin1.EndPoint   = Pt2;
            Lin2.StartPoint = Pt2;
            Lin2.EndPoint   = Pt3;
            Lin3.StartPoint = Pt3;
            Lin3.EndPoint   = Pt4;
            Lin4.StartPoint = Pt4;
            Lin4.EndPoint   = Pt1;

            INFITF.Reference rline1 = Prt.CreateReferenceFromGeometry(Lin1);
            INFITF.Reference rline2 = Prt.CreateReferenceFromGeometry(Lin2);
            INFITF.Reference rline3 = Prt.CreateReferenceFromGeometry(Lin3);
            INFITF.Reference rline4 = Prt.CreateReferenceFromGeometry(Lin4);
            INFITF.Reference rlineH = Prt.CreateReferenceFromGeometry(Skt.AbsoluteAxis.HorizontalReference);
            INFITF.Reference rlineV = Prt.CreateReferenceFromGeometry(Skt.AbsoluteAxis.VerticalReference);

            MECMOD.Constraint d1 = Skt.Constraints.AddBiEltCst(CatConstraintType.catCstTypeDistance, rline1, rline3);
            MECMOD.Constraint d2 = Skt.Constraints.AddBiEltCst(CatConstraintType.catCstTypeDistance, rline2, rline4);
            MECMOD.Constraint d3 = Skt.Constraints.AddBiEltCst(CatConstraintType.catCstTypeDistance, rlineH, rline4);
            MECMOD.Constraint d4 = Skt.Constraints.AddBiEltCst(CatConstraintType.catCstTypeDistance, rlineV, rline1);

            Skt.CloseEdition();//Skech조건 끝 //

            //PAD를 하기 위해서 조건문을 만든다.//
            PARTITF.ShapeFactory ShpFac = (PARTITF.ShapeFactory)Prt.ShapeFactory;
            //그 shapeFactory를 돌출하기 위해서 AddNewPad를 사용해서 50만큼 돌출한다.//
            ShpFac.AddNewPad(Skt, 50);



            //새로운 Body2를 만들기 //
            MECMOD.Body Body2 = Bodis.Add();
            //planed을 기준으로 Skt2를 만든다.//
            MECMOD.Sketch Skt2 = (MECMOD.Sketch)Body2.Sketches.Add(plane);
            //스켓이 시작 //
            Fac2D = Skt2.OpenEdition();
            //  X=75,Y=75 를 중심으로 D=20의  원을  만들기//
            Circle2D Cir2D = Fac2D.CreateClosedCircle(75, 75, 20);

            //스켓을 끝내기//
            Skt2.CloseEdition();
            //PAD  80만큼 //
            ShpFac.AddNewPad(Skt2, 80);

            //Body3 만들기 //
            Body Body3 = Prt.Bodies.Add();
            //Skt3를 Body2 안에 plane면을 기준으로  Sketche를 한다.
            Sketch Skt3 = Body2.Sketches.Add(plane);

            //스킷을 시작//
            Fac2D = Skt3.OpenEdition();
            //  X=75,Y=75 를 중심으로 D=5의  원을  만들기//
            Fac2D.CreateClosedCircle(75, 75, 5);
            //스켓3을 끝내기//
            Skt3.CloseEdition();
            //스켓3을 80만큼 PAD를 한다.
            ShpFac.AddNewPad(Skt3, 80);
            /////////////////
            //PartBody에 Prat In Work Object를 사용해서 조건을 만든다.
            Prt.InWorkObject = PartBody;

            ShpFac.AddNewAdd(Body);     //PartBody에 Body를추가
            ShpFac.AddNewAdd(Body2);    //PartBody에 Body2를추가
            ShpFac.AddNewRemove(Body3); //PartBody에 Body3를 제거한다


            Prt.Update();
        }