Hide Table of Contents

Add Component and Mate Example (C#)

This example shows how to add and mate a component to an assembly.

//---------------------------------------------------------------------------
// Preconditions: Open
// install_dir\Program Files\SolidWorks\samples\tutorial\toolbox\lens_mount.sldasm
//
// Postconditions:
// 1. The specified component, camtest.sldprt, and a mate,
//    top_coinc_camtest-1, are added to the assembly.
//    * AddItemNotify event fires.
// 2. The specified component is made virtual by saving it 
//    to the assembly with a new name.
//    * RenameItemNotify event fires.
// 3. Observe the new name of the virtual component in 
//    the FeatureManager design tree.
// 4. Inspect the Immediate window for event notifications.
//
// NOTE: Because the models are used elsewhere, 
// do not save any changes when closing them.
//----------------------------------------------------------------------------
 
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
using System.Collections;
using System.Windows.Forms;
 
namespace MakeVirtualCSharp.csproj
{
 
    partial class SolidWorksMacro
    { 
 
        public AssemblyDoc swAssemblyDoc;
        ModelDoc2 swModel;
        ModelDocExtension swDocExt;
        Hashtable openAssem;
        string tmpPath;
        ModelDoc2 tmpObj;
        bool boolstat;
        bool stat;
        Component2 swComponent;
        Feature matefeature;
        string MateName;
        string FirstSelection;
        string SecondSelection;
        string strCompName;
        string AssemblyTitle;
        string AssemblyName;
        int errors;
        int warnings;
 
        int mateError;
 
        public void Main()
        {
            swModel = (ModelDoc2)swApp.ActiveDoc;
 
            // Set up event
            swAssemblyDoc = (AssemblyDoc)swModel;
            openAssem = new Hashtable();
            AttachEventHandlers();
 
            // Get title of assembly document
            AssemblyTitle = swModel.GetTitle();
 
            // Split the title into two strings using the period (.) as the delimiter
            string[] strings = AssemblyTitle.Split(new Char[] { '.' });
 
            // Use AssemblyName when mating the component with the assembly
            AssemblyName = (string)strings[0]; 
 
 
            Debug.Print("Name of assembly: " + AssemblyName);
 
            boolstat = true;
            string strCompModelname = null;
            strCompModelname = "camtest.sldprt";
 
            // Because the component resides in the same folder as the assembly, get
            // the assembly's path and use it when opening the component
            tmpPath = swModel.GetPathName();
            int idx;
            idx = tmpPath.LastIndexOf("lens_mount.sldasm");
            string compPath;
            tmpPath = tmpPath.Substring(0, (idx));
            compPath = string.Concat(tmpPath, strCompModelname); 
 
 
            // Open the component
            tmpObj = (ModelDoc2)swApp.OpenDoc6(compPath, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, ""ref errors, ref warnings);
 
            // Check to see if the file is read only or cannot be found; display error
            // messages if either
            if (warnings == (int)swFileLoadWarning_e.swFileLoadWarning_ReadOnly)
            {
                MessageBox.Show("This file is read only.");
                boolstat = false;
            }
 
            if (tmpObj == null)
            {
                MessageBox.Show("Cannot locate the file.");
                boolstat = false;
            }
 
            // Re-activate the assembly so that you can add the component to it
            swModel = (ModelDoc2)swApp.ActivateDoc3(AssemblyTitle, true, (int)swRebuildOnActivation_e.swUserDecision, ref errors);
 
            // Add the camtest part to the assembly document.
            //
            // Currently only one option, swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig,
            // works for adding a part using IComponent2::AddComponent5
            // The other options, swAddComponentConfigOptions_e.swAddComponentConfigOptions_NewConfigWithAllReferenceModels
            // and swAddComponentConfigOptions_e.swAddComponentConfigOptions_NewConfigWithAsmStructure,
            // work only for adding assemblies
            swComponent = (Component2)swAssemblyDoc.AddComponent5(strCompModelname, (int)swAddComponentConfigOptions_e.swAddComponentConfigOptions_CurrentSelectedConfig, ""false"", -1, -1, -1);
 
            // Make the component virtual
            stat = swComponent.MakeVirtual();
 
            // Get the name of the component for the mate
            strCompName = swComponent.Name2;
 
            // Create the name of the mate and the names of the planes to use for the mate
            MateName = "top_coinc_" + strCompName;
            FirstSelection = "Top@" + strCompName + "@" + AssemblyName;
            SecondSelection = "Front@" + AssemblyName;
 
            swModel.ClearSelection2(true);
            swDocExt = (ModelDocExtension)swModel.Extension;
 
            // Select the planes for the mate
            boolstat = swDocExt.SelectByID2(FirstSelection, "PLANE", 0, 0, 0, true, 1, null, (int)swSelectOption_e.swSelectOptionDefault);
            boolstat = swDocExt.SelectByID2(SecondSelection, "PLANE", 0, 0, 0, true, 1, null, (int)swSelectOption_e.swSelectOptionDefault);
 
            // Add the mate
            matefeature = (Feature)swAssemblyDoc.AddMate3((int)swMateType_e.swMateCOINCIDENT, (int)swMateAlign_e.swMateAlignALIGNED, false, 0, 0, 0, 0, 0, 0, 0, 0, falseout mateError);
            matefeature.Name = MateName;
 
            swModel.ViewZoomtofit2();
 
        }
 
        public void AttachEventHandlers()
        {
            AttachSWEvents();
        }
 
 
        public void AttachSWEvents()
        {
            swAssemblyDoc.AddItemNotify += this.swAssemblyDoc_AddItemNotify;
            swAssemblyDoc.RenameItemNotify += this.swAssemblyDoc_RenameItemNotify;
        }
 
        private int swAssemblyDoc_AddItemNotify(int EntityType, string itemName)
        {
            Debug.Print("Component added: " + itemName);
            return 1;
        }
 
        private int swAssemblyDoc_RenameItemNotify(int EntityType, string oldName, string NewName)
        {
            Debug.Print("Virtual component name: " + NewName);
            return 1;
        }
 
 
        /// <summary>
        /// The SldWorks swApp variable is pre-assigned for you
        /// </summary>
 
        public SldWorks swApp;
 
    }
}
 
 


Provide feedback on this topic

SOLIDWORKS welcomes your feedback concerning the presentation, accuracy, and thoroughness of the documentation. Use the form below to send your comments and suggestions about this topic directly to our documentation team. The documentation team cannot answer technical support questions. Click here for information about technical support.

* Required

 
*Email:  
Subject:   Feedback on Help Topics
Page:   Add Component and Mate Example (C#
*Comment:  
*   I acknowledge I have read and I hereby accept the privacy policy under which my Personal Data will be used by Dassault Systèmes

Print Topic

Select the scope of content to print:



x

We have detected you are using a browser version older than Internet Explorer 7. For optimized display, we suggest upgrading your browser to Internet Explorer 7 or newer.

 Never show this message again
x

Web Help Content Version: API Help (English only) 2013 SP05

To disable Web help from within SOLIDWORKS and use local help instead, click Help > Use SOLIDWORKS Web Help.

To report problems encountered with the Web help interface and search, contact your local support representative. To provide feedback on individual help topics, use the “Feedback on this topic” link on the individual topic page.