using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
using SolidWorksTools;
using SolidWorksTools.File;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
namespace Sw_Code_From_Scratch_Test
{
[Guid("AB3F8214-9501-425D-8B8B-A2ABB15923C9"), ComVisible(true)]
[SwAddin(
Description = "Testing if all functions/features work from my own code",
Title = "Solidworks_add_in_code_from_scratch",
LoadAtStartup = true
)]
public class SwAddin : ISwAddin
{
#region Local Variables
ISldWorks iSwApp = null;
ICommandManager iCmdMgr = null;
int addinID = 0;
BitmapHandler iBmp;
int registerID;
public const int mainCmdGroupID = 1;
public const int mainItemID1 = 1;
string[] icons = new string[1];
#region Event Handler Variables
Hashtable openDocs = new Hashtable();
SolidWorks.Interop.sldworks.SldWorks SwEventPtr = null;
#endregion
#region Property Manager Variables
public UserPMPage ppage = null;
#endregion
#region 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
try
{
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);
}
catch (System.NullReferenceException nl)
{
Console.WriteLine("There was a problem registering this dll: SWattr is null. \n\"" + nl.Message + "\"");
System.Windows.Forms.MessageBox.Show("There was a problem registering this dll: SWattr is null.\n\"" + nl.Message + "\"");
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
System.Windows.Forms.MessageBox.Show("There was a problem registering the function: \n\"" + e.Message + "\"");
}
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type t)
{
try
{
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);
}
catch (System.NullReferenceException nl)
{
Console.WriteLine("There was a problem unregistering this dll: " + nl.Message);
System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + nl.Message + "\"");
}
catch (System.Exception e)
{
Console.WriteLine("There was a problem unregistering this dll: " + e.Message);
System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + e.Message + "\"");
}
}
#endregion
#region ISwAddin Implementation
public SwAddin()
{
}
public bool ConnectToSW(object ThisSW, int cookie)
{
iSwApp = (ISldWorks)ThisSW;
addinID = cookie;
//Set up callbacks
iSwApp.SetAddinCallbackInfo2(0, this, addinID);
#region Set up the CommandManager
iCmdMgr = iSwApp.GetCommandManager(cookie);
AddCommandMgr();
#endregion
return true;
}
public bool DisconnectFromSW()
{
RemoveCommandMgr();
System.Runtime.InteropServices.Marshal.ReleaseComObject(iCmdMgr);
iCmdMgr = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(iSwApp);
iSwApp = null;
// The add-in must call GC.Collect() here in order to retrieve all managed code pointers
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
return true;
}
#endregion
#region UI Methods
public void AddCommandMgr()
{
ICommandGroup cmdGroup;
int cmdIndex0;
string Title = "C# Addin", ToolTip = "C# Addin";
// Define the document types where the tab should appear
int[] docTypes = new int[] {
(int)swDocumentTypes_e.swDocASSEMBLY,
(int)swDocumentTypes_e.swDocDRAWING,
(int)swDocumentTypes_e.swDocPART
};
int cmdGroupErr = 0;
bool ignorePrevious = false;
object registryIDs;
bool getDataResult = iCmdMgr.GetGroupDataFromRegistry(mainCmdGroupID, out registryIDs);
int[] knownIDs = new int[1] { mainItemID1 };
if (getDataResult)
{
if (!CompareIDs((int[])registryIDs, knownIDs))
{
// If the IDs don't match, reset the command group
ignorePrevious = true;
}
}
cmdGroup = iCmdMgr.CreateCommandGroup2(
mainCmdGroupID,
Title,
ToolTip,
"",
-1,
ignorePrevious,
ref cmdGroupErr
);
// Set the custom icon for the command group
string pathToIcon = @"C:\Users\Beauvais\Desktop\Sw Code From Scratch Test\Sw Code From Scratch Test\CadCylinderIcon32.png";
if (!System.IO.File.Exists(pathToIcon))
{
System.Windows.Forms.MessageBox.Show($"Icon file not found: {pathToIcon}");
return;
}
// Assign icon paths for both 16x16 and 32x32 (using the same icon here)
cmdGroup.IconList = new string[] { pathToIcon, pathToIcon };
cmdGroup.MainIconList = new string[] { pathToIcon, pathToIcon };
int menuToolbarOption = (int)(swCommandItemType_e.swMenuItem | swCommandItemType_e.swToolbarItem);
// Add a button with the custom icon
cmdIndex0 = cmdGroup.AddCommandItem2(
"CreateCylinder",
0,
"Creates a Cylinder With a o/d of 50mm and length of 100m",
"Create a Cylinder",
0,
nameof(CreateCylinder), // Method name as string for callback
"",
mainItemID1,
menuToolbarOption
);
cmdGroup.HasToolbar = true;
cmdGroup.HasMenu = true;
cmdGroup.Activate();
// Add the command tab
foreach (int type in docTypes)
{
CommandTab cmdTab;
cmdTab = iCmdMgr.GetCommandTab(type, Title);
if (cmdTab != null && (!getDataResult || ignorePrevious))
{
// If the tab exists but registry info was ignored, recreate it
bool res = iCmdMgr.RemoveCommandTab(cmdTab);
cmdTab = null;
}
if (cmdTab == null)
{
cmdTab = iCmdMgr.AddCommandTab(type, Title);
CommandTabBox cmdBox = cmdTab.AddCommandTabBox();
int[] cmdIDs = new int[1];
int[] TextType = new int[1];
cmdIDs[0] = cmdGroup.get_CommandID(cmdIndex0);
TextType[0] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow;
cmdBox.AddCommands(cmdIDs, TextType);
}
}
}
public void RemoveCommandMgr()
{
iCmdMgr.RemoveCommandGroup(mainCmdGroupID);
}
public bool CompareIDs(int[] storedIDs, int[] addinIDs)
{
List<int> storedList = new List<int>(storedIDs);
List<int> addinList = new List<int>(addinIDs);
addinList.Sort();
storedList.Sort();
if (addinList.Count != storedList.Count)
{
return false;
}
else
{
for (int i = 0; i < addinList.Count; i++)
{
if (addinList != storedList)
{
return false;
}
}
}
return true;
}
#endregion
#region ui callbacks
public void CreateCylinder()
{
//make sure we have a part open
string partTemplate = iSwApp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);
if ((partTemplate != null) && (partTemplate != ""))
{
IModelDoc2 modDoc = (IModelDoc2)iSwApp.NewDocument(partTemplate, (int)swDwgPaperSizes_e.swDwgPaperA2size, 0.0, 0.0);
ISketchManager sketchMgr = modDoc.SketchManager;
sketchMgr.InsertSketch(true);
sketchMgr.CreateCircle(0, 0, 0, 0.025, 0, 0);
//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);
}
else
{
System.Windows.Forms.MessageBox.Show("There is no part template available. Please check your options and make sure there is a part template selected, or select a new part template.");
}
}
public void PopupCallbackFunction()
{
bool bRet;
bRet = iSwApp.ShowThirdPartyPopupMenu(registerID, 500, 500);
}
public int PopupEnable()
{
if (iSwApp.ActiveDoc == null)
return 0;
else
return 1;
}
public void TestCallback()
{
Debug.Print("Test Callback, CSharp");
}
public int EnableTest()
{
if (iSwApp.ActiveDoc == null)
return 0;
else
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);
}
else if (openDocs.Contains(modDoc))
{
bool connected = false;
DocumentEventHandler docHandler = (DocumentEventHandler)openDocs[modDoc];
if (docHandler != null)
{
connected = docHandler.ConnectModelViews();
}
}
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
}
}
#endregion