Hide Table of Contents

Add .NET Controls to SolidWorks using an Add-in Example (C#)

This example shows how to add .NET controls to SolidWorks' FeatureManager, PropertyManager, Task Pane, and model view using a C# add-in.

//----------------------------------------------------------------------------

// Preconditions:

// 1. In Microsoft Visual Studio 2008 or later, create a project using

//    Other Languages > Visual C# > My Templates > SwCSharpAddin.

// 2. Name the project DotNetControlsDemo.

// 3. Copy and paste this into SwAddin.cs of your C# add-in.

//    Copy and paste this into UserPMPage.cs.

//    Copy and paste this into PMPHandler.cs.

// 4. Select Debug in the Solution Configurations dropdown in the toolbar.

// 5. Select Project > DotNetControlsDemo Properties.

// 6. On the Application tab, ensure that the Target Framework is

//    .NET Framework 3.0.

// 7. On the Debug tab select Start external program and type in the

//    pathname of your SolidWorks executable.

// 8. Save the project.

// 9. In Solution Explorer add the following .NET Framework 3.0 references:

//    PresentationCore.dll

//    PresentationFramework.dll

//    UIAutomationProvider.dll

//    WindowsBase.dll

//    WindowsFormsIntegration.dll

// 10. Add a Windows Presentation Foundation User Control to the project:

//     a. In Solution Explorer, right-click the project and select

//         Add > User Control.

//     b. In Name type WPFControl.xaml.

//     c. Select the User Control (WPF) template.

//     d. Click Add.

//     e. Copy and paste this into WPFControl.xaml.

//     f. Copy and paste this into WPFControl.xaml.cs.

// 11. Add a Windows Forms User Control to the project:

//     a. In Solution Explorer, right-click the project and select

//        Add > User Control.

//     b. In Name type UserControl1.cs.

//     c. Click Add.

//     d. Copy and paste this into UserControl1.Designer.cs.

// 12. Create a Windows Form:

//     a. In Solution Explorer, right-click the project and select

//        Add > Windows Form.

//     b. In Name type Form1.cs.

//     c. Copy and paste this into Form1.Designer.cs.     

// 13. Save the project.

//

// Postconditions:

// 1. In SolidWorks, select DotNetControlsDemo > WinFormInTaskPane.

//    A new tab with .NET controls appears in the Task Pane.

// 2. Select DotNetControlsDemo > UserControlInModelView.

//    .NET User Control1 tab appears below the model view.

// 3. Select DotNetControlsDemo > WPFInModelView.

//    .NET WPF Control tab appears below the model view.

// 4. Select DotNetControlsDemo > WinFormInFeatureMgr.

//    A new design tree appears in a split window of FeatureManager.

// 5. Select DotNetControlsDemo > Show PMP.

//    Click OK in three dialog boxes.

//    A new tab with .NET controls appears in PropertyManager.

//---------------------------------------------------------------------------

SwAddin.cs:

using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Reflection;
using System.Diagnostics;

using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swpublished;
using SolidWorks.Interop.swconst;
using SolidWorksTools;
using SolidWorksTools.File;
using System.Windows.Forms;
using System.Windows.Forms.Integration;


namespace DotNetControlsDemo
{
    
/// <summary>
    /// Summary description for DotNetControlsDemo.
    /// </summary>
    [Guid("4ca45de8-6831-4a4c-83ac-d9d968803794"), ComVisible(true)]
    [
SwAddin(
        Description =
"DotNetControlsDemo description",
        Title =
"DotNetControlsDemo",
        LoadAtStartup =
true
        )]
    
public class SwAddin : ISwAddin
    {
        #region Local Variables
        
ISldWorks iSwApp;
        
ICommandManager iCmdMgr;
        
ICommandGroup cmdGroup;
        
int addinID;
        
Form1 TaskPanWinFormControl;
        
UserControl1 TaskPanUserControl;
        
Form1 FeatureMgrControl;
        
UserControl1 ModelView1Control;
        
WPFControl WpfModelView1Control;
        
ElementHost ModelViewelhost;

        #region Event Handler Variables
        
Hashtable openDocs;
        SolidWorks.Interop.sldworks.
SldWorks SwEventPtr;
        #endregion

        #region
Property Manager Variables
        
UserPMPage ppage;
        #endregion


        // Public Properties
        public ISldWorks SwApp
        {
            
get { return iSwApp; }
        }
        
public ICommandManager CmdMgr
        {
            
get { return iCmdMgr; }
        }

        
public Hashtable OpenDocs
        {
            
get { return openDocs; }
        }

        #endregion

        #region
SolidWorks Registration
        [
ComRegisterFunctionAttribute]
        
public static void RegisterFunction(Type t)
        {

            #region Get Custom Attribute: SwAddinAttribute
            
SwAddinAttribute SWattr = null;
            
Type type = typeof(SwAddin);
            
foreach (System.Attribute attr in type.GetCustomAttributes(false))
            {
                
if (attr is SwAddinAttribute)
                {
                    SWattr = attr
as SwAddinAttribute;
                    
break;
                }
            }
            #endregion

            Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
            Microsoft.Win32.
RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;

            
string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}";
            Microsoft.Win32.
RegistryKey addinkey = hklm.CreateSubKey(keyname);
            addinkey.SetValue(
null, 0);

            addinkey.SetValue(
"Description", SWattr.Description);
            addinkey.SetValue(
"Title", SWattr.Title);

            keyname =
"Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}";
            addinkey = hkcu.CreateSubKey(keyname);
            addinkey.SetValue(
null, Convert.ToInt32(SWattr.LoadAtStartup), Microsoft.Win32.RegistryValueKind.DWord);
        }

        [
ComUnregisterFunctionAttribute]
        
public static void UnregisterFunction(Type t)
        {
            Microsoft.Win32.
RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
            Microsoft.Win32.
RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;

            
string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID.ToString() + "}";
            hklm.DeleteSubKey(keyname);

            keyname =
"Software\\SolidWorks\\AddInsStartup\\{" + t.GUID.ToString() + "}";
            hkcu.DeleteSubKey(keyname);
        }

        #endregion

        #region
ISwAddin Implementation
        
public SwAddin()
        {
        }

        
public bool ConnectToSW(object ThisSW, int cookie)
        {
            iSwApp = (
ISldWorks)ThisSW;
            addinID = cookie;

            
//Setup callbacks
            iSwApp.SetAddinCallbackInfo(0, this, addinID);

            #region Setup the Command Manager
            iCmdMgr = iSwApp.GetCommandManager(cookie);
            AddCommandMgr();
            #endregion

            #region
Setup the Event Handlers
            SwEventPtr = (SolidWorks.Interop.sldworks.
SldWorks)iSwApp;
            openDocs =
new Hashtable();
            AttachEventHandlers();
            #endregion

            #region
Setup Sample Property Manager
            AddPMP();
            #endregion

            return true;
        }

        
public bool DisconnectFromSW()
        {
            RemoveCommandMgr();
            RemovePMP();
            DetachEventHandlers();

            iSwApp =
null;
            
//The addin _must_ call GC.Collect() here in order to retrieve all managed code pointers
            GC.Collect();
            
return true;
        }
        #endregion

        #region
UI Methods
        
public void AddCommandMgr()
        {
            
            
BitmapHandler iBmp = new BitmapHandler();
            
            
Assembly thisAssembly;
            
int cmdIndex0, cmdIndex1, cmdIndex2, cmdIndex3, cmdIndex4;
            
string Title = "DotNetControlsDemo", ToolTip = "DotNetControlsDemo";


            
int[] docTypes = new int[]{(int)swDocumentTypes_e.swDocASSEMBLY,
                                       (
int)swDocumentTypes_e.swDocDRAWING,
                                       (
int)swDocumentTypes_e.swDocPART};

            thisAssembly = System.Reflection.
Assembly.GetAssembly(this.GetType());

            cmdGroup = iCmdMgr.CreateCommandGroup(1, Title, ToolTip,
"", -1);
            cmdGroup.LargeIconList = iBmp.CreateFileFromResourceBitmap(
"DotNetControlsDemo.ToolbarLarge.bmp", thisAssembly);
            cmdGroup.SmallIconList = iBmp.CreateFileFromResourceBitmap(
"DotNetControlsDemo.ToolbarSmall.bmp", thisAssembly);
            cmdGroup.LargeMainIcon = iBmp.CreateFileFromResourceBitmap(
"DotNetControlsDemo.MainIconLarge.bmp", thisAssembly);
            cmdGroup.SmallMainIcon = iBmp.CreateFileFromResourceBitmap(
"DotNetControlsDemo.MainIconSmall.bmp", thisAssembly);

            cmdIndex0 = cmdGroup.AddCommandItem(
"WinFromInTaskPane", -1, "Add Windows Form In Task Pane", "WinFormInTaskPane", 0, "WinFormInTaskPane", "EnableWinFormInTaskPane", 0);
            cmdIndex1 = cmdGroup.AddCommandItem(
"UserControlInModelView", -1, "Add User Control In Model View", "UserControlInModelView", 1, "UserControlInModelView", "EnableUserControlInModelView", 1);
            cmdIndex2 = cmdGroup.AddCommandItem(
"WPFInModelView", -1, "Add WPF In ModelView", "WPFInModelView", 2, "WPFInModelView", "EnableWPFInModelView", 2);
            cmdIndex3 = cmdGroup.AddCommandItem(
"WinFormInFeatureMgr", -1, "Add Windows Form In FeatureManager", "WinFormInFeatureMgr", 3, "WinFormInFeatureMgr", "EnableWinFormInFeatureMgr", 3);
            cmdIndex4 = cmdGroup.AddCommandItem(
"Show PMP", -1, "Display PropertyManager with .NET Controls", "Show PMP", 4, "ShowPMP", "EnablePMP", 4);

            cmdGroup.HasToolbar =
true;
            cmdGroup.HasMenu =
true;
            cmdGroup.Activate();

            
bool bResult;

            
foreach (int type in docTypes)
            {
                
ICommandTab cmdTab;

                cmdTab = iCmdMgr.GetCommandTab(type, Title);

                
if (cmdTab == null)
                {
                    cmdTab = (
ICommandTab)iCmdMgr.AddCommandTab(type, Title);

                    
CommandTabBox cmdBox = cmdTab.AddCommandTabBox();

                    
int[] cmdIDs = new int[6];
                    
int[] TextType = new int[6];


                    cmdIDs[0] = cmdGroup.get_CommandID(cmdIndex0);
                    System.Diagnostics.
Debug.Print(cmdGroup.get_CommandID(cmdIndex0).ToString());
                    TextType[0] = (
int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;

                    cmdIDs[1] = cmdGroup.get_CommandID(cmdIndex1);
                    System.Diagnostics.
Debug.Print(cmdGroup.get_CommandID(cmdIndex1).ToString());
                    TextType[1] = (
int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;

                    cmdIDs[2] = cmdGroup.get_CommandID(cmdIndex2);
                    System.Diagnostics.
Debug.Print(cmdGroup.get_CommandID(cmdIndex2).ToString());
                    TextType[2] = (
int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;

                    cmdIDs[3] = cmdGroup.get_CommandID(cmdIndex3);
                    System.Diagnostics.
Debug.Print(cmdGroup.get_CommandID(cmdIndex3).ToString());
                    TextType[3] = (
int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;


                    cmdIDs[4] = cmdGroup.get_CommandID(cmdIndex4);
                    System.Diagnostics.
Debug.Print(cmdGroup.get_CommandID(cmdIndex4).ToString());
                    TextType[4] = (
int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;

                    cmdIDs[5] = cmdGroup.ToolbarId;
                    System.Diagnostics.
Debug.Print(cmdIDs[5].ToString());
                    TextType[5] = (
int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal | (int)swCommandTabButtonFlyoutStyle_e.swCommandTabButton_ActionFlyout;

                    bResult = cmdBox.AddCommands(cmdIDs, TextType);



                    
CommandTabBox cmdBox1 = cmdTab.AddCommandTabBox();
                    cmdIDs =
new int[1];
                    TextType =
new int[1];

                    cmdIDs[0] = cmdGroup.ToolbarId;
                    TextType[0] = (
int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow | (int)swCommandTabButtonFlyoutStyle_e.swCommandTabButton_ActionFlyout;

                    bResult = cmdBox1.AddCommands(cmdIDs, TextType);

                    cmdTab.AddSeparator(cmdBox1, cmdGroup.ToolbarId);

                }

            }
            thisAssembly =
null;
            iBmp.Dispose();
        }


        
public void RemoveCommandMgr()
        {
            iCmdMgr.RemoveCommandGroup(1);
        }

        
public Boolean AddPMP()
        {
            ppage =
new UserPMPage(this);
            
return true;
        }

        
public Boolean RemovePMP()
        {
            ppage =
null;
            
return true;
        }

        #endregion

        #region
UI Callbacks
        
public void WinFormInTaskPane()
        {
              
ITaskpaneView pTaskPanView;
              pTaskPanView = iSwApp.CreateTaskpaneView2(
"", "C# .NET Control");
              TaskPanWinFormControl =
new Form1();
              pTaskPanView.DisplayWindowFromHandle(TaskPanWinFormControl.Handle.ToInt64());
              TaskPanUserControl = (
UserControl1)pTaskPanView.GetControl();
              
Debug.Print(TaskPanUserControl.Name);

        }

        
        
public int EnableWinFromInTaskPane()
        {
            
return 1;

        }

        
public void UserControlInModelView()
        {
            
IModelDoc2 pDoc;
            pDoc = (
IModelDoc2)iSwApp.ActiveDoc;
            
IModelViewManager swModelViewMgr;
            swModelViewMgr = pDoc.ModelViewManager;
            ModelView1Control =
new UserControl1();
            swModelViewMgr.DisplayWindowFromHandle(
".NET User Control1", ModelView1Control.Handle.ToInt64(), false);
        }

        
public int EnableUserControlInModelView()
        {
            
if (iSwApp.ActiveDoc != null)
                
return 1;
            
else
                return 0;
        }

      
public void  WPFInModelView()
       {
          
IModelDoc2 pDoc;
           pDoc = (
IModelDoc2)iSwApp.ActiveDoc;
          
IModelViewManager swModelViewMgr;
           swModelViewMgr = pDoc.ModelViewManager;
           WpfModelView1Control =
new WPFControl();

           ModelViewelhost =
new ElementHost();
           ModelViewelhost.Child = WpfModelView1Control;

           swModelViewMgr.DisplayWindowFromHandle(
".NET WPF Control", ModelViewelhost.Handle.ToInt64(), true);

       }

        
public int EnableWPFInModelView()
        {
            
if (iSwApp.ActiveDoc != null)
                
return 1;
            
else
                return 0;
        }

        
public void WinFormInFeatureMgr()
        {
            
IModelDoc2 pDoc;
            pDoc = (
IModelDoc2)iSwApp.ActiveDoc;
            
IModelViewManager swModelViewMgr;
            swModelViewMgr = pDoc.ModelViewManager;
            
IFeatMgrView swFeatMgrTabTop;
            FeatureMgrControl =
new Form1();
            swFeatMgrTabTop = swModelViewMgr.CreateFeatureMgrWindowFromHandle(cmdGroup.SmallIconList, (
int)FeatureMgrControl.Handle.ToInt64(), "MyDotNetControl", (int)swFeatMgrPane_e.swFeatMgrPaneTop);
            pDoc.FeatureManagerSplitterPosition = 0.5;
            swFeatMgrTabTop.ActivateView();
        }

      
public int EnableWinFormInFeatureMgr()
       {
              
if (iSwApp.ActiveDoc != null)
                
return 1;
            
else
                return 0;
       }

        
public void ShowPMP()
        {
            
if (ppage != null)
                ppage.Show();
        }

        
public int EnablePMP()
        {
            
if (iSwApp.ActiveDoc != null)
                
return 1;
            
else
                return 0;
        }
        #endregion

        #region
Event Methods
        
public bool AttachEventHandlers()
        {
            AttachSwEvents();
            
//Listen for events on all currently open docs
            AttachEventsToAllDocuments();
            
return true;
        }

        
private bool AttachSwEvents()
        {
            
try
            {
                SwEventPtr.ActiveDocChangeNotify +=
new DSldWorksEvents_ActiveDocChangeNotifyEventHandler(OnDocChange);
                SwEventPtr.DocumentLoadNotify2 +=
new DSldWorksEvents_DocumentLoadNotify2EventHandler(OnDocLoad);
                SwEventPtr.FileNewNotify2 +=
new DSldWorksEvents_FileNewNotify2EventHandler(OnFileNew);
                SwEventPtr.ActiveModelDocChangeNotify +=
new DSldWorksEvents_ActiveModelDocChangeNotifyEventHandler(OnModelChange);
                SwEventPtr.FileOpenPostNotify +=
new DSldWorksEvents_FileOpenPostNotifyEventHandler(FileOpenPostNotify);
                
return true;
            }
            
catch (Exception e)
            {
                
Console.WriteLine(e.Message);
                
return false;
            }
        }



        
private bool DetachSwEvents()
        {
            
try
            {
                SwEventPtr.ActiveDocChangeNotify -=
new DSldWorksEvents_ActiveDocChangeNotifyEventHandler(OnDocChange);
                SwEventPtr.DocumentLoadNotify2 -=
new DSldWorksEvents_DocumentLoadNotify2EventHandler(OnDocLoad);
                SwEventPtr.FileNewNotify2 -=
new DSldWorksEvents_FileNewNotify2EventHandler(OnFileNew);
                SwEventPtr.ActiveModelDocChangeNotify -=
new DSldWorksEvents_ActiveModelDocChangeNotifyEventHandler(OnModelChange);
                SwEventPtr.FileOpenPostNotify -=
new DSldWorksEvents_FileOpenPostNotifyEventHandler(FileOpenPostNotify);
                
return true;
            }
            
catch (Exception e)
            {
                
Console.WriteLine(e.Message);
                
return false;
            }

        }

        
public void AttachEventsToAllDocuments()
        {
            
ModelDoc2 modDoc = (ModelDoc2)iSwApp.GetFirstDocument();
            
while (modDoc != null)
            {
                
if (!openDocs.Contains(modDoc))
                {
                    AttachModelDocEventHandler(modDoc);
                }
                modDoc = (
ModelDoc2)modDoc.GetNext();
            }
        }

        
public bool AttachModelDocEventHandler(ModelDoc2 modDoc)
        {
            
if (modDoc == null)
                
return false;

            
DocumentEventHandler docHandler = null;

            
if (!openDocs.Contains(modDoc))
            {
                
switch (modDoc.GetType())
                {
                    
case (int)swDocumentTypes_e.swDocPART:
                        {
                            docHandler =
new PartEventHandler(modDoc, this);
                            
break;
                        }
                    
case (int)swDocumentTypes_e.swDocASSEMBLY:
                        {
                            docHandler =
new AssemblyEventHandler(modDoc, this);
                            
break;
                        }
                    
case (int)swDocumentTypes_e.swDocDRAWING:
                        {
                            docHandler =
new DrawingEventHandler(modDoc, this);
                            
break;
                        }
                    
default:
                        {
                            
return false; //Unsupported document type
                        }
                }
                docHandler.AttachEventHandlers();
                openDocs.Add(modDoc, docHandler);
            }
            
return true;
        }

        
public bool DetachModelEventHandler(ModelDoc2 modDoc)
        {
            
DocumentEventHandler docHandler;
            docHandler = (
DocumentEventHandler)openDocs[modDoc];
            openDocs.Remove(modDoc);
            modDoc =
null;
            docHandler =
null;
            
return true;
        }

        
public bool DetachEventHandlers()
        {
            DetachSwEvents();

            
//Close events on all currently open docs
            DocumentEventHandler docHandler;
            
int numKeys = openDocs.Count;
            
object[] keys = new Object[numKeys];

            
//Remove all document event handlers
            openDocs.Keys.CopyTo(keys, 0);
            
foreach (ModelDoc2 key in keys)
            {
                docHandler = (
DocumentEventHandler)openDocs[key];
                docHandler.DetachEventHandlers();
//This also removes the pair from the hash
                docHandler = null;
            }
            
return true;
        }
        #endregion

        #region
Event Handlers
        
//Events
        public int OnDocChange()
        {
            
return 0;
        }

        
public int OnDocLoad(string docTitle, string docPath)
        {
            
return 0;
        }

        
int FileOpenPostNotify(string FileName)
        {
            AttachEventsToAllDocuments();
            
return 0;
        }

        
public int OnFileNew(object newDoc, int docType, string templateName)
        {
            AttachEventsToAllDocuments();
            
return 0;
        }

        
public int OnModelChange()
        {
            
return 0;
        }

        #endregion
    }

}

 

UserPMPage.cs:

using System;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swpublished;
using SolidWorks.Interop.swconst;
using System.Windows.Forms;

using System.Windows.Forms.Integration;

namespace DotNetControlsDemo
{
    
public class UserPMPage
    {
        
//Local Objects
        IPropertyManagerPage2 swPropertyPage;
        
PMPHandler handler;
        
ISldWorks iSwApp;
        
SwAddin userAddin;

        
WPFControl MyWPFControl;
        
ElementHost elhost;
        
UserControl1 MyUserControl;
        
Form1 MyWinFormControl;

        #region Property Manager Page Controls
        
//Groups
        IPropertyManagerPageGroup group1;
        
IPropertyManagerPageGroup group2;
        
IPropertyManagerPageGroup group3;

        
//Controls
        IPropertyManagerPageWindowFromHandle dotnet1;
        
IPropertyManagerPageWindowFromHandle dotnet2;
        
IPropertyManagerPageWindowFromHandle dotnet3;

        
//Control IDs
        public const int group1ID = 0;
        
public const int group2ID = 1;
        
public const int group3ID = 2;

        
public const int DotNet1ID = 3;
        
public const int DotNet2ID = 4;
        
public const int DotNet3ID = 5;
    
        #endregion

        public UserPMPage(SwAddin addin)
        {
            userAddin = addin;
            iSwApp = (
ISldWorks)userAddin.SwApp;
            CreatePropertyManagerPage();
        }


        
protected void CreatePropertyManagerPage()
        {
            
int errors = -1;
            
int options = (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_OkayButton |
                (
int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_CancelButton;

            handler =
new PMPHandler(userAddin);
            swPropertyPage = (
IPropertyManagerPage2)iSwApp.CreatePropertyManagerPage(".Net Control Disply PMP", options, handler, ref errors);
            
if (swPropertyPage != null && errors == (int)swPropertyManagerPageStatus_e.swPropertyManagerPage_Okay)
            {
                
try
                {
                    AddControls();
                }
                
catch (Exception e)
                {
                    iSwApp.SendMsgToUser2(e.Message, 0, 0);
                }
            }
        }


        
//Controls are displayed on the page top to bottom in the order
        //in which they are added to the object.
        protected void AddControls()
        {
            
short controlType = -1;
            
short align = -1;
            
int options = -1;


            
//Add the groups
            options = (int)swAddGroupBoxOptions_e.swGroupBoxOptions_Expanded |
                      (
int)swAddGroupBoxOptions_e.swGroupBoxOptions_Visible;

            group1 = (
IPropertyManagerPageGroup)swPropertyPage.AddGroupBox(group1ID, "Window Form", options);

            options = (
int)swAddGroupBoxOptions_e.swGroupBoxOptions_Checkbox |
                      (
int)swAddGroupBoxOptions_e.swGroupBoxOptions_Visible;

            group2 = (
IPropertyManagerPageGroup)swPropertyPage.AddGroupBox(group2ID, "User Control", options);

            options =  (
int)swAddGroupBoxOptions_e.swGroupBoxOptions_Checkbox |
                        (
int)swAddGroupBoxOptions_e.swGroupBoxOptions_Visible;

            group3 = (
IPropertyManagerPageGroup)swPropertyPage.AddGroupBox(group3ID, "WPF Control", options);

            
//Add the controls to group1`
            controlType = (int)swPropertyManagerPageControlType_e.swControlType_WindowFromHandle;
            align = (
int)swPropertyManagerPageControlLeftAlign_e.swControlAlign_LeftEdge;
            options = (
int)swAddControlOptions_e.swControlOptions_Enabled |
                      (
int)swAddControlOptions_e.swControlOptions_Visible;

            dotnet1 = (
IPropertyManagerPageWindowFromHandle )group1.AddControl(DotNet1ID, controlType, ".Net Windows Form Control", align, options, "This Control is added without COM");
            dotnet1.Height = 150;

            controlType = (
int)swPropertyManagerPageControlType_e.swControlType_WindowFromHandle;
            align = (
int)swPropertyManagerPageControlLeftAlign_e.swControlAlign_LeftEdge;
            options = (
int)swAddControlOptions_e.swControlOptions_Enabled |
                      (
int)swAddControlOptions_e.swControlOptions_Visible;

            dotnet2 = (
IPropertyManagerPageWindowFromHandle )group2.AddControl(DotNet2ID, controlType, ".Net User Form Control", align, options, "This Control is added without COM");
            dotnet2.Height = 150;

            dotnet3 = (
IPropertyManagerPageWindowFromHandle )group3.AddControl(DotNet3ID, controlType, ".Net WPF Control", align, options, "This Control is added without COM");
            dotnet3.Height = 50;

    
        }

        
public void Show()
        {

            
// For Dot net control user need to create object at every Display

            //WinForm Control
            MyWinFormControl = new Form1();
            
//If you are adding Winform in Property Page need to set TopLevel Property to false
            MyWinFormControl.TopLevel = false;
            MyWinFormControl.Show(); 

            dotnet1.SetWindowHandle(MyWinFormControl.Handle.ToInt64());
            

            
//User Control
             MyUserControl = new UserControl1();
            dotnet2.SetWindowHandle(MyUserControl.Handle.ToInt64());


            
//WPF control
            elhost = new ElementHost();
            MyWPFControl =
new WPFControl();
            elhost.Child = MyWPFControl;
            dotnet3.SetWindowHandle(elhost.Handle.ToInt64());

            
//Show Proppety page
            swPropertyPage.Show();
            
        }
    }
}

PMPHandler.cs:

 

using System;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swpublished;
using System.Windows.Forms;

namespace DotNetControlsDemo
{

    
public class PMPHandler : IPropertyManagerPage2Handler8
    {
        
ISldWorks iSwApp;
        
SwAddin userAddin;

        
public PMPHandler(SwAddin addin)
        {
            userAddin = addin;
            iSwApp = (
ISldWorks)userAddin.SwApp;
        }

        
//Implement these methods from the interface
        public void AfterClose()
        {
            
//This function must contain code, even if it does nothing, to prevent the
            //.NET runtime environment from doing garbage collection at the wrong time.
            int IndentSize;
            IndentSize = System.Diagnostics.
Debug.IndentSize;
            System.Diagnostics.
Debug.WriteLine(IndentSize);
        }

        
public void OnCheckboxCheck(int id, bool status)
        {

        }

        
public void OnClose(int reason)
        {
            
//This function must contain code, even if it does nothing, to prevent the
            //.NET runtime environment from doing garbage collection at the wrong time.
            int IndentSize;
            IndentSize = System.Diagnostics.
Debug.IndentSize;
            System.Diagnostics.
Debug.WriteLine(IndentSize);
        }

        
public void OnComboboxEditChanged(int id, string text)
        {

        }

        
public int OnActiveXControlCreated(int id, bool status)
        {
            
return -1;
        }

        
public void OnButtonPress(int id)
        {

        }

        
public void OnComboboxSelectionChanged(int id, int item)
        {

        }

        
public void OnGroupCheck(int id, bool status)
        {

        }

        
public void OnGroupExpand(int id, bool status)
        {

        }

        
public bool OnHelp()
        {
            
return true;
        }

        
public void OnListboxSelectionChanged(int id, int item)
        {

        }

        
public bool OnNextPage()
        {
            
return true;
        }

        
public void OnNumberboxChanged(int id, double val)
        {

        }

        
public void OnOptionCheck(int id)
        {

        }

        
public bool OnPreviousPage()
        {
            
return true;
        }

        
public void OnSelectionboxCalloutCreated(int id)
        {

        }

        
public void OnSelectionboxCalloutDestroyed(int id)
        {

        }

        
public void OnSelectionboxFocusChanged(int id)
        {

        }

        
public void OnSelectionboxListChanged(int id, int item)
        {

        }

        
public void OnTextboxChanged(int id, string text)
        {

        }

        
public void AfterActivation()
        {
            
        }

        
public bool OnKeystroke(int Wparam, int Message, int Lparam, int Id)
        {
            
return true;
        }

        
public void OnPopupMenuItem(int Id)
        {

        }

        
public void OnPopupMenuItemUpdate(int Id, ref int retval)
        {

        }

        
public bool OnPreview()
        {
            
return true;
        }

        
public void OnSliderPositionChanged(int Id, double Value)
        {

        }

        
public void OnSliderTrackingCompleted(int Id, double Value)
        {

        }

        
public bool OnSubmitSelection(int Id, object Selection, int SelType, ref string ItemText)
        {
            
return true;
        }

        
public bool OnTabClicked(int Id)
        {
            
return true;
        }

        
public void OnUndo()
        {

        }

        
public void OnWhatsNew()
        {

        }

        
public void OnRedo()
        {

        }

        
public void OnGainedFocus(int Id)
        {

        }

        
public void OnLostFocus(int Id)
        {

        }

        
public int OnWindowFromHandleControlCreated(int id, bool status)
        {
            System.Windows.Forms.
MessageBox.Show("Dot Net Control Created");
            
return -1;
        }

        void OnListboxRMBUp(int Id, int PosX, int PosY)
        {
            throw new Exception("The method or operation is not implemented.");
        }



    }
}

 

Form1.Designer.cs:

namespace DotNetControlsDemo
{
    
partial class Form1
    {
        
/// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        
/// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            
if (disposing && (components != null))
            {
                components.Dispose();
            }
            
base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        
/// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            
this.listBox1 = new System.Windows.Forms.ListBox();
            
this.comboBox1 = new System.Windows.Forms.ComboBox();
            
this.textBox1 = new System.Windows.Forms.TextBox();
            
this.button1 = new System.Windows.Forms.Button();
            
this.SuspendLayout();
            
//
            // listBox1
            //
            this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.
AnchorStyles.Right)));
            
this.listBox1.FormattingEnabled = true;
            
this.listBox1.Items.AddRange(new object[] {
            
"Help",
            
"Whats New"});
            
this.listBox1.Location = new System.Drawing.Point(25, 160);
            
this.listBox1.Name = "listBox1";
            
this.listBox1.Size = new System.Drawing.Size(304, 43);
            
this.listBox1.TabIndex = 10;
            
//
            // comboBox1
            //
            this.comboBox1.DisplayMember = "Monday";
            
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            
this.comboBox1.FormattingEnabled = true;
            
this.comboBox1.Items.AddRange(new object[] {
            
"Monday ",
            
"Tuesday",
            
"Wednesday",
            
"Thursday",
            
"Friday",
            
"Saturday",
            
"Sunday"});
            
this.comboBox1.Location = new System.Drawing.Point(25, 122);
            
this.comboBox1.Name = "comboBox1";
            
this.comboBox1.Size = new System.Drawing.Size(140, 21);
            
this.comboBox1.TabIndex = 9;
            
this.comboBox1.ValueMember = "Monday";
            
//
            // textBox1
            //
            this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.
AnchorStyles.Left)
                        | System.Windows.Forms.
AnchorStyles.Right)));
            
this.textBox1.Location = new System.Drawing.Point(25, 86);
            
this.textBox1.Name = "textBox1";
            
this.textBox1.Size = new System.Drawing.Size(321, 20);
            
this.textBox1.TabIndex = 8;
            
//
            // button1
            //
            this.button1.Location = new System.Drawing.Point(25, 12);
            
this.button1.Name = "button1";
            
this.button1.Size = new System.Drawing.Size(140, 57);
            
this.button1.TabIndex = 7;
            
this.button1.Text = "Say Hello";
            
this.button1.UseVisualStyleBackColor = true;
            
this.button1.Click += new System.EventHandler(this.button1_Click);
            
//
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            
this.ClientSize = new System.Drawing.Size(382, 215);
            
this.ControlBox = false;
            
this.Controls.Add(this.listBox1);
            
this.Controls.Add(this.comboBox1);
            
this.Controls.Add(this.textBox1);
            
this.Controls.Add(this.button1);
            
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            
this.MaximizeBox = false;
            
this.MinimizeBox = false;
            
this.Name = "Form1";
            
this.ShowIcon = false;
            
this.ShowInTaskbar = false;
            
this.Text = "Form1";
            
this.ResumeLayout(false);
            
this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ListBox listBox1;
        
private System.Windows.Forms.ComboBox comboBox1;
        
private System.Windows.Forms.TextBox textBox1;
        
private System.Windows.Forms.Button button1;
    }
}

 

UserControl1.Designer.cs:

namespace DotNetControlsDemo
{
    
partial class UserControl1
    {
        
/// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        
/// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            
if (disposing && (components != null))
            {
                components.Dispose();
            }
            
base.Dispose(disposing);
        }

        #region Component Designer generated code

        
/// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            
this.radioButton1 = new System.Windows.Forms.RadioButton();
            
this.textBox1 = new System.Windows.Forms.TextBox();
            
this.button1 = new System.Windows.Forms.Button();
            
this.tabControl1 = new System.Windows.Forms.TabControl();
            
this.TabPage1 = new System.Windows.Forms.TabPage();
            
this.TabPage2 = new System.Windows.Forms.TabPage();
            
this.TabPage3 = new System.Windows.Forms.TabPage();
            
this.tabControl1.SuspendLayout();
            
this.SuspendLayout();
            
//
            // radioButton1
            //
            this.radioButton1.Anchor = System.Windows.Forms.AnchorStyles.Left;
            
this.radioButton1.AutoSize = true;
            
this.radioButton1.Location = new System.Drawing.Point(23, 113);
            
this.radioButton1.Name = "radioButton1";
            
this.radioButton1.Size = new System.Drawing.Size(85, 17);
            
this.radioButton1.TabIndex = 5;
            
this.radioButton1.TabStop = true;
            
this.radioButton1.Text = "radioButton1";
            
this.radioButton1.UseVisualStyleBackColor = true;
            
//
            // textBox1
            //
            this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.
AnchorStyles.Right)));
            
this.textBox1.Location = new System.Drawing.Point(23, 87);
            
this.textBox1.Name = "textBox1";
            
this.textBox1.Size = new System.Drawing.Size(378, 20);
            
this.textBox1.TabIndex = 4;
            
//
            // button1
            //
            this.button1.Location = new System.Drawing.Point(23, 17);
            
this.button1.Name = "button1";
            
this.button1.Size = new System.Drawing.Size(119, 49);
            
this.button1.TabIndex = 3;
            
this.button1.Text = "Say Hello";
            
this.button1.UseVisualStyleBackColor = true;
            
this.button1.Click += new System.EventHandler(this.button1_Click);
            
//
            // tabControl1
            //
            this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.
AnchorStyles.Right)));
            
this.tabControl1.Controls.Add(this.TabPage1);
            
this.tabControl1.Controls.Add(this.TabPage2);
            
this.tabControl1.Controls.Add(this.TabPage3);
            
this.tabControl1.Location = new System.Drawing.Point(23, 148);
            
this.tabControl1.Multiline = true;
            
this.tabControl1.Name = "tabControl1";
            
this.tabControl1.SelectedIndex = 0;
            
this.tabControl1.Size = new System.Drawing.Size(386, 69);
            
this.tabControl1.TabIndex = 6;
            
//
            // TabPage1
            //
            this.TabPage1.Location = new System.Drawing.Point(4, 22);
            
this.TabPage1.Name = "TabPage1";
            
this.TabPage1.Padding = new System.Windows.Forms.Padding(3);
            
this.TabPage1.Size = new System.Drawing.Size(378, 43);
            
this.TabPage1.TabIndex = 0;
            
this.TabPage1.Text = "TabPage1";
            
this.TabPage1.UseVisualStyleBackColor = true;
            
//
            // TabPage2
            //
            this.TabPage2.Location = new System.Drawing.Point(4, 22);
            
this.TabPage2.Name = "TabPage2";
            
this.TabPage2.Padding = new System.Windows.Forms.Padding(3);
            
this.TabPage2.Size = new System.Drawing.Size(406, 103);
            
this.TabPage2.TabIndex = 1;
            
this.TabPage2.Text = "TabPage2";
            
this.TabPage2.UseVisualStyleBackColor = true;
            
//
            // TabPage3
            //
            this.TabPage3.Location = new System.Drawing.Point(4, 22);
            
this.TabPage3.Name = "TabPage3";
            
this.TabPage3.Padding = new System.Windows.Forms.Padding(3);
            
this.TabPage3.Size = new System.Drawing.Size(406, 103);
            
this.TabPage3.TabIndex = 2;
            
this.TabPage3.Text = "TabPage3";
            
this.TabPage3.UseVisualStyleBackColor = true;
            
//
            // UserControl1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            
this.Controls.Add(this.tabControl1);
            
this.Controls.Add(this.radioButton1);
            
this.Controls.Add(this.textBox1);
            
this.Controls.Add(this.button1);
            
this.Name = "UserControl1";
            
this.Size = new System.Drawing.Size(427, 237);
            
this.tabControl1.ResumeLayout(false);
            
this.ResumeLayout(false);
            
this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.RadioButton radioButton1;
        
private System.Windows.Forms.TextBox textBox1;
        
private System.Windows.Forms.Button button1;
        
private System.Windows.Forms.TabControl tabControl1;
        
private System.Windows.Forms.TabPage TabPage1;
        
private System.Windows.Forms.TabPage TabPage2;
        
private System.Windows.Forms.TabPage TabPage3;
    }
}
 

 

WPFControl.xaml:

<UserControl x:Class="DotNetControlsDemo.WPFControl"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Height="204" Width="314" Loaded="UserControl_Loaded">
    <Grid Height="44" Width="108">
        <ComboBox Text="WPF" Height="44" VerticalAlignment="Top">
            <ComboBoxItem Margin="2">
                <Ellipse Width="20" Height="20" Stroke="Black" />
            </ComboBoxItem>
            <ComboBoxItem Margin="2">
                <Path Stroke="Black" Data="M 0,0 L 20,0 L 10,20 Z" />
            </ComboBoxItem>
            <ComboBoxItem Margin="2">
                <Rectangle Stroke="Black" Width="20" Height="20" />
            </ComboBoxItem>
        </ComboBox>
    </Grid>

</
UserControl>

 

WPFControl.xaml.cs:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DotNetControlsDemo
{
    
/// <summary>
    /// Interaction logic for WPFControl.xaml
    /// </summary>
    public partial class WPFControl : UserControl
    {
        
public WPFControl()
        {
            InitializeComponent();
        }

        
private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }
    }
}

 

 



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 .NET Controls to SolidWorks using an Add-in 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) 2011 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.