Insert New Virtual Component Example (C#)
This example shows how to insert a new part as a virtual component in
an assembly and save it to an external file.
//---------------------------------------------------------------------
// Preconditions:
// 1. Open:
//
<SolidWorks_install_dir>\samples\tutorial\smartcomponents\stepped_shaft.sldasm
// 2. A planar face on the assembly is selected.
// 3. Rename the namespace of this macro to match your C# project name.
//
// Postconditions:
// 1. The new part is inserted as a virtual component in the assembly.
// 2. The virtual component is saved to an external file,
// and its name changes in the FeatureManager design tree.
//
// NOTE: Because this assembly is used in a SolidWorks online tutorial, do
not
// save the assembly when you close it.
//---------------------------------------------------------------------
using
SolidWorks.Interop.sldworks;
using
SolidWorks.Interop.swconst;
using
System;
using
System.Diagnostics;
using
Scripting;
namespace
SaveVirtualComponent_CSharp.csproj
{
partial
class
SolidWorksMacro
{
ModelDoc2
swModel;
AssemblyDoc
swAssy;
Component2
swComponent;
SelectionMgr
swSelMgr;
FileSystemObject
objFSO;
string
compName;
object[]
splits;
long
status;
public
void Main()
{
swModel = (ModelDoc2)swApp.ActiveDoc;
swAssy = (AssemblyDoc)swModel;
// Get the pre-selected planar
face
Face2
swFeature = default(Face2);
swSelMgr = (SelectionMgr)swModel.SelectionManager;
swFeature = (Face2)swSelMgr.GetSelectedObject6(1,
0);
// Create the part and insert
it as a virtual component
//
in the assembly
status = swAssy.InsertNewVirtualPart(swFeature,
out
swComponent);
if
(status == 1)
{
Debug.Print("Name
of virtual component: " + swComponent.Name2);
// Check to see if the part
is a virtual component
Debug.Print("Is
component virtual? " + swComponent.IsVirtual);
objFSO = new
Scripting.FileSystemObject();
splits =
swComponent.Name.Split('^');
compName = objFSO.GetParentFolderName(swModel.GetPathName())
+ "\\" +
splits[0];
ModelDoc2
compModel = default(ModelDoc2);
compModel = (ModelDoc2)swComponent.GetModelDoc();
if
(compModel.GetType() == (int)swDocumentTypes_e.swDocPART)
{
compName = compName +
".sldprt";
}
else
{
compName = compName +
".sldasm";
}
Debug.Print("Name
of saved virtual component: " + compName);
swComponent.SaveVirtualComponent(compName);
}
else
{
Debug.Print("Error
code returned when attempting to insert new part as virtual component: "
+ status);
}
swModel.ClearSelection2(true);
}
public
SldWorks
swApp;
}
}