Hide Table of Contents

Create Flyouts in the CommandManager Example (C#)

This example shows how to use an add-in to create flyouts in the CommandManager and in

context-sensitive menus of selected entities.

 

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

// Preconditions:

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

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

// 2. Name the project CommandManager_SwCSharpAddin1.

// 3. Copy and paste this into SwAddin.cs of your C# project.

// 4. Click Project > CommandManager_SwCSharpAddin1 Properties > Debug.

// 5. Select Start external program and type the pathname of your

//    SolidWorks executable.

// 6. Click F5 to start debugging SolidWorks with this add-in.

//

// Postconditions:

// 1. In SolidWorks, select C# Add-in > CreateCube.

// 2. Click C# Flyout in the CommandManager.

//    Inspect the Immediate Window.

// 3. Click a face of the cube.

// 4. Click the flyout icon in the face's context-sensitive menu.

// 5. Select a command item and inspect the Immediate Window.

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

 

// SwAddin.cs:

 

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

using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swpublished;
using SolidWorks.Interop.swconst;
using SolidWorksTools;
using SolidWorksTools.File;


namespace CommandManager_SwCSharpAddin1
{
    
/// <summary>
    /// This addin shows how to add a FlyoutGroup to the CommandManager and
    /// context-sensitive menus of selected faces in a part.
    /// </summary>
    ///
    [Guid("4b7281d1-332c-448f-93a5-7559e36f207e"), ComVisible(true)]
    [SwAddin(
        Description =
"CommandManager_SwCSharpAddin1 description",
        Title =
"CommandManager_SwCSharpAddin1",
        LoadAtStartup =
true
        )]
    
public class SwAddin : ISwAddin
    {
        #region Local Variables
        
ISldWorks iSwApp;
        
ICommandManager iCmdMgr;
        
int addinID;

        #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 updateBtns()
        {
            
IFlyoutGroup flyoutGroup;
            flyoutGroup = iCmdMgr.GetFlyoutGroup(500);
            flyoutGroup.RemoveAllCommandItems();

            flyoutGroup.AddCommandItem(
"FlyoutCommand 1", "FlyoutCommand 1", -1, "FlyoutCommandItem1", "FlyoutEnableCommandItem1");
            flyoutGroup.AddCommandItem(
"FlyoutCommand 2", "FlyoutCommand 2", -1, "FlyoutCommandItem2", "FlyoutEnableCommandItem2");
          
            flyoutGroup.FlyoutType = (
int)swCommandFlyoutStyle_e.swCommandFlyoutStyle_Simple;
            
//flyoutGroup.FlyoutType = (int)swCommandFlyoutStyle_e.swCommandFlyoutStyle_LastUsed;
            //flyoutGroup.FlyoutType = (int)swCommandFlyoutStyle_e.swCommandFlyoutStyle_Favorite;

        }
        
public void AddCommandMgr()
        {
            
ICommandGroup cmdGroup;
            
IFlyoutGroup flyoutGroup;
            
BitmapHandler iBmp = new BitmapHandler();
            
Assembly thisAssembly;
            
int cmdIndex0, cmdIndex1;
    
            
int errors = 0;
            
string Title = "C# Add-in", ToolTip = "C# Add-in";
            
string FlyoutTitle = "C# Flyout", FlyoutToolTip = "C# Flyout";


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

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

            
// Create a CommandGroup

            cmdGroup = iCmdMgr.CreateCommandGroup2(1, Title, ToolTip, "", -1,true,ref errors);

            cmdGroup.LargeIconList = iBmp.CreateFileFromResourceBitmap(
"CommandManager_SwCSharpAddin1.ToolbarLarge.bmp", thisAssembly);
            cmdGroup.SmallIconList = iBmp.CreateFileFromResourceBitmap(
"CommandManager_SwCSharpAddin1.ToolbarSmall.bmp", thisAssembly);
            cmdGroup.LargeMainIcon = iBmp.CreateFileFromResourceBitmap(
"CommandManager_SwCSharpAddin1.MainIconLarge.bmp", thisAssembly);
            cmdGroup.SmallMainIcon = iBmp.CreateFileFromResourceBitmap(
"CommandManager_SwCSharpAddin1.MainIconSmall.bmp", thisAssembly);

            cmdIndex0 = cmdGroup.AddCommandItem2(
"CreateCube", -1, "Create a cube", "Create cube", 0, "CreateCube", "CubeEnable", 1, 3);
            cmdIndex1 = cmdGroup.AddCommandItem2(
"Show PMP", -1, "Display sample property manager", "Show PMP", 1, "ShowPMP", "PMPEnable", 2, 3);

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

            
// Get number of command IDs in the CommandGroup
            Debug.Print("Number of command IDs in the CommandGroup is " + iCmdMgr.GetCommandIDsCount(1).ToString());

            
// Get group data from registry
            int[] userIDs;
            
object objIDs;
            
iCmdMgr.GetGroupDataFromRegistry(1, out objIDs);
            userIDs = (
int[])objIDs;
            
Debug.Print("Command IDs found in the registry:");
            
foreach (int ID in userIDs)
            {
                
Debug.Print( ID.ToString());
            }

            
bool bResult;
            
            
// Create a FlyoutGroup

            flyoutGroup = iCmdMgr.CreateFlyoutGroup(500,
                                                   FlyoutTitle,
                                                   FlyoutToolTip,
                                                   FlyoutTitle,
                                                   cmdGroup.SmallMainIcon,
                                                   cmdGroup.LargeMainIcon,
                                                   cmdGroup.SmallIconList,
                                                   cmdGroup.LargeIconList,
                                                  
"FlyoutCallback",
                                                  
"FlyoutEnable");

            
// Add the FlyoutGroup to the context-sensitive menus of faces in parts
            bResult = flyoutGroup.AddContextMenuFlyout((int)swDocumentTypes_e.swDocPART, (int)swSelectType_e.swSelFACES);
            
Debug.Print("Context menu flyout created for faces in parts: " + bResult.ToString());

            
// Get the total number of FlyoutGroups in CommandManager
            Debug.Print("Number of FlyoutGroups is " + iCmdMgr.NumberOfFlyoutGroups);

            
// Get the FlyoutGroups
            object[] objGroups;
            objGroups = (
object[])iCmdMgr.GetFlyoutGroups();
            
Debug.Print("Find all FlyoutGroups in CommandManager:");
            
int i;
            
for (i = 0; i <= objGroups.GetUpperBound(0); i++)
            {
                
Debug.Print("FlyoutGroup found");

            }

            
// Get a FlyoutGroup by its user-defined ID
            IFlyoutGroup fogrp;
            fogrp = iCmdMgr.GetFlyoutGroup(500);
            
Debug.Print("  CmdID: " + fogrp.CmdID);
            
Debug.Print("  Button count: " + fogrp.ButtonCount);
            
Debug.Print("  Flyout Type: " + fogrp.FlyoutType);
 

            Debug.Print("  SmallMainIcon: " + fogrp.SmallMainIcon);
          
  Debug.Print("  LargeMainIcon: " + fogrp.LargeMainIcon);
           
Debug.Print("  SmallIconList: " + fogrp.SmallIconList);
           
Debug.Print("  LargeIconList: " + fogrp.LargeIconList);
 


            
foreach (int type in docTypes)
            {
                
ICommandTab cmdTab;

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

                
CommandTabBox cmdBox = cmdTab.AddCommandTabBox();

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


                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.ToolbarId;
                System.Diagnostics.
Debug.Print(cmdIDs[2].ToString());
                TextType[2] = (
int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal | (int)swCommandTabButtonFlyoutStyle_e.swCommandTabButton_ActionFlyout;

                bResult = cmdBox.AddCommands(cmdIDs, TextType);

                
// Add another CommandTabBox with the FlyoutGroup

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

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

                cmdIDs[1] = fogrp.CmdID;
                TextType[1] = (
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.RemoveCommandGroup2(1,
false);
            iCmdMgr.RemoveFlyoutGroup(500);

        }

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

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

        #endregion

        #region
UI Callbacks
  
        
public void CreateCube()
        {
            
//make sure we have a part open
            string partTemplate = iSwApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);
            
IModelDoc2 modDoc = (IModelDoc2)iSwApp.NewDocument(partTemplate, (int)swDwgPaperSizes_e.swDwgPaperA2size, 0.0, 0.0);

            modDoc.InsertSketch2(
true);
            modDoc.SketchRectangle(0, 0, 0, .1, .1, .1,
false);

            
//Extrude the sketch
            IFeatureManager featMan = modDoc.FeatureManager;
            featMan.FeatureExtrusion(
true,
                
false, false,
                (
int)swEndConditions_e.swEndCondBlind, (int)swEndConditions_e.swEndCondBlind,
                0.1, 0.0,
                
false, false,
                
false, false,
                0.0, 0.0,
                
false, false,
                
false, false,
                
true,
                
false, false);
        }

        
public void FlyoutCallback() {
            
Debug.Print("Flyout group called");
            updateBtns();
        }
        
public int FlyoutEnable() { return 1; }

        
public void FlyoutCommandItem1() { Debug.Print("Flyout command 1 called"); }
        
public int FlyoutEnableCommandItem1() { return 1; }

        
public void FlyoutCommandItem2() { Debug.Print("Flyout command 2 called"); }
        
public int FlyoutEnableCommandItem2() { return 1; }

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

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

        
public int CubeEnable()
        {
      
                
return 1;
          
        }
        #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
    }

}



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:   Create Flyouts in the CommandManager 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.