using log4net;
|
using log4net.Appender;
|
using log4net.Config;
|
using log4net.Core;
|
using PdmSwPlugin.Common;
|
using PdmSwPlugin.Common.Setting;
|
using PdmSwPlugin.Main;
|
using PdmSwPlugin.Main.EventHandler;
|
using SolidWorks.Interop.sldworks;
|
using SolidWorks.Interop.swconst;
|
using SolidWorks.Interop.swpublished;
|
using SolidWorksTools;
|
using SolidWorksTools.File;
|
using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Reflection;
|
using System.Runtime.InteropServices;
|
using System.Windows.Forms;
|
using System.Windows.Forms.Integration;
|
|
namespace PdmSw
|
{
|
/// <summary>
|
/// ...
|
/// </summary>
|
[Guid("DF23E96F-A469-4302-8367-7FA2F798CD09"), ComVisible(true)]
|
[SwAddin(
|
Description = "SolidWorks²å¼þ",
|
Title = "PdmSwPlugin",
|
LoadAtStartup = true
|
)]
|
public partial class SwAddin : ISwAddin
|
{
|
static SwAddin()
|
{
|
// AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
|
// AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_AssemblyResolve;
|
/// ÉèÖÃlog4netÅäÖÃ
|
string dllLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
string file = Path.Combine(dllLocation, "log4net.config");
|
FileInfo info = new FileInfo(file);
|
XmlConfigurator.Configure(info);
|
var curPath = LogManager.GetRepository();
|
var appenders = curPath.GetAppenders();
|
if (appenders == null)
|
return;
|
foreach (var appender in appenders)
|
{
|
var rollingFileAppender = appender as RollingFileAppender;
|
if (rollingFileAppender == null)
|
continue;
|
rollingFileAppender.File = dllLocation + "/Log/";
|
rollingFileAppender.ActivateOptions();
|
}
|
}
|
|
/// <summary>
|
/// ÍüÁË
|
/// </summary>
|
/// <param name="sender"></param>
|
/// <param name="args"></param>
|
/// <returns></returns>
|
/// <exception cref="DllNotFoundException"></exception>
|
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
|
{
|
string dir = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName;
|
dir = Path.Combine(dir, @"Libs");
|
if (args.Name.Contains(".resources"))
|
{
|
return default;
|
}
|
//if (AppDomain.CurrentDomain.GetAssemblies()
|
// .Where(x => !x.IsDynamic)
|
// .First(x => x.FullName == args.Name) is Assembly alreadyLoaded)
|
//{
|
// return alreadyLoaded;
|
//}
|
string s = null;
|
string name = new AssemblyName(args.Name).Name;
|
foreach (var ss in Directory.EnumerateFiles(dir))
|
{
|
string sss = Path.GetFileNameWithoutExtension(ss);
|
if (sss == name)
|
{
|
s = ss;
|
break;
|
}
|
}
|
if (s != null)
|
{
|
return Assembly.LoadFile(s);
|
}
|
throw new DllNotFoundException();
|
}
|
|
#region Local Variables ÊôÐÔ
|
|
ICommandManager iCmdMgr = null;
|
int addinID = 0;
|
BitmapHandler iBmp;
|
|
public const int mainCmdGroupID = 5;
|
public const int mainItemID1 = 0;
|
public const int mainItemID2 = 1;
|
public const int mainItemID3 = 2;
|
public const int flyoutGroupID = 91;
|
|
/// <summary>
|
/// ÉϴεĻÎĵµ
|
/// </summary>
|
private ModelDoc2 lastActiveDoc = null;
|
|
private ILog Logger;
|
|
/// <summary>
|
/// ²å¼þÖ÷Ìå
|
/// </summary>
|
private MainControl mainControl = null;
|
|
private PluginSetting GlobalConfig;
|
|
#region Property Manager Variables
|
UserPMPage ppage = null;
|
#endregion
|
|
private BaseAttacher attacher;
|
private ISldWorks swApp;
|
private TaskpaneView panel;
|
private Form mainForm;
|
// Public Properties
|
public ISldWorks SwApp
|
{
|
get => swApp;
|
}
|
|
public ICommandManager CmdMgr
|
{
|
get { return iCmdMgr; }
|
}
|
#endregion
|
|
#region SolidWorks Registration ×¢²á±íÏà¹Ø
|
/// <summary>
|
/// дע²á±í
|
/// </summary>
|
/// <param name="t"></param>
|
[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;
|
string keyId = t.GUID.ToString();
|
string keyname = $"SOFTWARE\\SolidWorks\\Addins\\{{{keyId}}}";
|
Microsoft.Win32.RegistryKey addinkey = hklm.CreateSubKey(keyname);
|
addinkey.SetValue(null, 0);
|
addinkey.SetValue("Description", SWattr.Description);
|
addinkey.SetValue("Title", SWattr.Title);
|
|
Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;
|
keyname = $"Software\\SolidWorks\\AddInsStartup\\{{{keyId}}}";
|
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 + "\"");
|
}
|
}
|
|
/// <summary>
|
/// ɾע²á±í
|
/// </summary>
|
/// <param name="t"></param>
|
[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 keyId = t.GUID.ToString();
|
string keyname = $"SOFTWARE\\SolidWorks\\Addins\\{{{keyId}}}";
|
hklm.DeleteSubKey(keyname);
|
|
keyname = $"Software\\SolidWorks\\AddInsStartup\\{{{keyId}}}";
|
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()
|
{
|
Logger = BaseAttacher.Logger;
|
// Çл»ÅäÖÃÎļþµØÖ·
|
// ChangeAppConfig();
|
GlobalConfig = PluginSetting.Instance;
|
}
|
|
public bool ConnectToSW(object ThisSW, int cookie)
|
{
|
swApp = (ISldWorks)ThisSW;
|
addinID = cookie;
|
|
//Setup callbacks
|
SwApp.SetAddinCallbackInfo2(0, this, addinID);
|
|
#region Setup the Command Manager
|
iCmdMgr = SwApp.GetCommandManager(cookie);
|
// AddCommandMgr();
|
#endregion
|
|
// ¼ÓÔØ²å¼þ
|
SetPlugins();
|
|
attacher = new BaseAttacher(swApp, mainControl);
|
attacher.AttachEventHandlers();
|
|
#region Setup Sample Property Manager
|
AddPMP();
|
#endregion
|
|
// GlobalExceptionHandler();
|
|
//LoadPlugins();
|
return true;
|
}
|
|
private void SetPlugins()
|
{
|
// ¶Áͼ£¬¹À¼ÆÊÇpanelµÄͼ±ê
|
string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
string imageFolder = Path.Combine(location, @"Images");
|
string[] bitmaps = new string[]
|
{
|
Path.Combine(imageFolder, @"MatChooser_20X20.png"),
|
Path.Combine(imageFolder, @"MatChooser_32X32.png"),
|
Path.Combine(imageFolder, @"MatChooser_40X40.png"),
|
Path.Combine(imageFolder, @"MatChooser_64X64.png"),
|
Path.Combine(imageFolder, @"MatChooser_96X96.png"),
|
Path.Combine(imageFolder, @"MatChooser_128X128.png")
|
};
|
// ´´½¨Panel
|
panel = SwApp.CreateTaskpaneView3(bitmaps, "PdmSwPlugin" + PluginConst.Version);
|
|
mainControl = new MainControl((SldWorks)SwApp);
|
// Ö»ÄÜÓÃwinform£¬´úÀíwpf
|
ElementHost host = new ElementHost
|
{
|
Child = mainControl,
|
AutoSize = true,
|
Dock = DockStyle.Fill
|
};
|
mainForm = new Form
|
{
|
Text = "PdmSwPlugin",
|
ControlBox = false,
|
FormBorderStyle = FormBorderStyle.None,
|
KeyPreview = true,
|
Dock = DockStyle.Fill
|
};
|
mainForm.FormClosed += MainForm_FormClosed;
|
mainForm.Controls.Add(host);
|
IntPtr ptr = mainForm.Handle;
|
// IntPtr ptr = WindowIntPtrUtil.FindWindow(null, "Window1");
|
panel.DisplayWindowFromHandlex64(ptr.ToInt64());
|
mainForm.WindowState = FormWindowState.Maximized;
|
}
|
|
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
|
{
|
/// ¹Ø±ÕʱÏÈÖ´ÐÐDeActiveHandler£¬È»ºóÖ´ÐÐÕâ¸ö
|
|
}
|
|
private void LoadPlugins()
|
{
|
// ¶Áͼ£¬¹À¼ÆÊÇpanelµÄͼ±ê
|
string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
string imageFolder = Path.Combine(location, @"Images");
|
string[] bitmaps = new string[]
|
{
|
Path.Combine(imageFolder, @"MatChooser_20X20.png"),
|
Path.Combine(imageFolder, @"MatChooser_32X32.png"),
|
Path.Combine(imageFolder, @"MatChooser_40X40.png"),
|
Path.Combine(imageFolder, @"MatChooser_64X64.png"),
|
Path.Combine(imageFolder, @"MatChooser_96X96.png"),
|
Path.Combine(imageFolder, @"MatChooser_128X128.png")
|
};
|
// ´´½¨Panel
|
TaskpaneView panel = SwApp.CreateTaskpaneView3(bitmaps, "ÎïÁϲéѯ" + PluginConst.Version);
|
|
PluginLoader pl = new PluginLoader("ms");
|
long res = (long)pl.ExecuteMothod("PdmSwPlugin.MaterialSelect.MaterialSelectControl", "GetWindowHandle",
|
new object[] { (SldWorks)SwApp });
|
panel.DisplayWindowFromHandlex64(res);
|
}
|
|
/// <summary>
|
/// ¶Ï¿ªÓëSolidWorksÁ¬½Ó
|
/// </summary>
|
/// <returns></returns>
|
public bool DisconnectFromSW()
|
{
|
try
|
{
|
RemoveCommandMgr();
|
RemovePMP();
|
mainControl.StopTcpServer();
|
mainControl.DeActiveHandler();
|
attacher.DetachEventHandlers();
|
attacher = null;
|
|
mainForm.Close();
|
mainForm = null;
|
mainControl = null;
|
panel.DeleteView();
|
panel = null;
|
|
Marshal.ReleaseComObject(iCmdMgr);
|
iCmdMgr = null;
|
Marshal.ReleaseComObject(SwApp);
|
swApp = null;
|
//The addin _must_ call GC.Collect() here in order to retrieve all managed code pointers
|
GC.Collect();
|
GC.WaitForPendingFinalizers();
|
|
//GC.Collect();
|
//GC.WaitForPendingFinalizers();
|
}
|
catch (Exception ex)
|
{
|
Logger.Error("DisconnectFromSW Failed!", ex);
|
}
|
return true;
|
}
|
#endregion
|
|
#region Ä£°å×Ô´øµÄÓò»µ½µÄ·½·¨£¬±ðɾÍòÒ»ÓÐÓÃ
|
#region UI Methods
|
public void AddCommandMgr()
|
{
|
ICommandGroup cmdGroup;
|
if (iBmp == null)
|
iBmp = new BitmapHandler();
|
Assembly thisAssembly;
|
int cmdIndex0, cmdIndex1;
|
string Title = "LHJ²å¼þ", ToolTip = "LHJ²å¼þ";
|
|
|
int[] docTypes = new int[]{(int)swDocumentTypes_e.swDocASSEMBLY,
|
(int)swDocumentTypes_e.swDocDRAWING,
|
(int)swDocumentTypes_e.swDocPART};
|
|
thisAssembly = System.Reflection.Assembly.GetAssembly(this.GetType());
|
|
|
int cmdGroupErr = 0;
|
bool ignorePrevious = false;
|
|
object registryIDs;
|
//get the ID information stored in the registry
|
bool getDataResult = iCmdMgr.GetGroupDataFromRegistry(mainCmdGroupID, out registryIDs);
|
|
int[] knownIDs = new int[2] { mainItemID1, mainItemID2 };
|
|
if (getDataResult)
|
{
|
if (!CompareIDs((int[])registryIDs, knownIDs)) //if the IDs don't match, reset the commandGroup
|
{
|
ignorePrevious = true;
|
}
|
}
|
|
cmdGroup = iCmdMgr.CreateCommandGroup2(mainCmdGroupID, Title, ToolTip, "", -1, ignorePrevious, ref cmdGroupErr);
|
cmdGroup.LargeIconList = iBmp.CreateFileFromResourceBitmap("PdmSw.Images.ToolbarLarge.bmp", thisAssembly);
|
cmdGroup.SmallIconList = iBmp.CreateFileFromResourceBitmap("PdmSw.Images.ToolbarSmall.bmp", thisAssembly);
|
cmdGroup.LargeMainIcon = iBmp.CreateFileFromResourceBitmap("PdmSw.Images.MainIconLarge.bmp", thisAssembly);
|
cmdGroup.SmallMainIcon = iBmp.CreateFileFromResourceBitmap("PdmSw.Images.MainIconSmall.bmp", thisAssembly);
|
|
int menuToolbarOption = (int)(swCommandItemType_e.swMenuItem | swCommandItemType_e.swToolbarItem);
|
cmdIndex0 = cmdGroup.AddCommandItem2("CreateCube", -1, "Create a cube", "Create cube", 0, "CreateCube", "", mainItemID1, menuToolbarOption);
|
cmdIndex1 = cmdGroup.AddCommandItem2("Show PMP", -1, "Display sample property manager", "Show PMP", 2, "ShowPMP", "EnablePMP", mainItemID2, menuToolbarOption);
|
|
cmdGroup.HasToolbar = true;
|
cmdGroup.HasMenu = true;
|
cmdGroup.Activate();
|
|
bool bResult;
|
|
|
|
FlyoutGroup flyGroup = iCmdMgr.CreateFlyoutGroup(flyoutGroupID, "Dynamic Flyout", "Flyout Tooltip", "Flyout Hint",
|
cmdGroup.SmallMainIcon, cmdGroup.LargeMainIcon, cmdGroup.SmallIconList, cmdGroup.LargeIconList, "FlyoutCallback", "FlyoutEnable");
|
|
|
flyGroup.AddCommandItem("FlyoutCommand 1", "test", 0, "FlyoutCommandItem1", "FlyoutEnableCommandItem1");
|
|
flyGroup.FlyoutType = (int)swCommandFlyoutStyle_e.swCommandFlyoutStyle_Simple;
|
|
|
foreach (int type in docTypes)
|
{
|
CommandTab cmdTab;
|
|
cmdTab = iCmdMgr.GetCommandTab(type, Title);
|
|
if (cmdTab != null & !getDataResult | ignorePrevious)//if tab exists, but we have ignored the registry info (or changed command group ID), re-create the tab. Otherwise the ids won't matchup and the tab will be blank
|
{
|
bool res = iCmdMgr.RemoveCommandTab(cmdTab);
|
cmdTab = null;
|
}
|
|
//if cmdTab is null, must be first load (possibly after reset), add the commands to the tabs
|
if (cmdTab == null)
|
{
|
cmdTab = iCmdMgr.AddCommandTab(type, Title);
|
|
CommandTabBox cmdBox = cmdTab.AddCommandTabBox();
|
|
int[] cmdIDs = new int[3];
|
int[] TextType = new int[3];
|
|
cmdIDs[0] = cmdGroup.get_CommandID(cmdIndex0);
|
|
TextType[0] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;
|
|
cmdIDs[1] = cmdGroup.get_CommandID(cmdIndex1);
|
|
TextType[1] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;
|
|
cmdIDs[2] = cmdGroup.ToolbarId;
|
|
TextType[2] = (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] = flyGroup.CmdID;
|
TextType[0] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow | (int)swCommandTabButtonFlyoutStyle_e.swCommandTabButton_ActionFlyout;
|
|
bResult = cmdBox1.AddCommands(cmdIDs, TextType);
|
|
cmdTab.AddSeparator(cmdBox1, cmdIDs[0]);
|
|
}
|
|
}
|
thisAssembly = null;
|
|
}
|
|
public void RemoveCommandMgr()
|
{
|
iBmp?.Dispose();
|
iCmdMgr?.RemoveCommandGroup(mainCmdGroupID);
|
iCmdMgr?.RemoveFlyoutGroup(flyoutGroupID);
|
}
|
|
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[i] != storedList[i])
|
{
|
return false;
|
}
|
}
|
}
|
return true;
|
}
|
|
public Boolean AddPMP()
|
{
|
ppage = new UserPMPage(this);
|
return true;
|
}
|
|
public Boolean RemovePMP()
|
{
|
ppage = null;
|
return true;
|
}
|
|
#endregion
|
|
#region UI Callbacks
|
public void CreateCube()
|
{
|
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 ShowPMP()
|
{
|
if (ppage != null)
|
ppage.Show();
|
}
|
|
public int EnablePMP()
|
{
|
if (SwApp.ActiveDoc != null)
|
return 1;
|
else
|
return 0;
|
}
|
|
public void FlyoutCallback()
|
{
|
FlyoutGroup flyGroup = iCmdMgr.GetFlyoutGroup(flyoutGroupID);
|
flyGroup.RemoveAllCommandItems();
|
|
flyGroup.AddCommandItem(System.DateTime.Now.ToLongTimeString(), "test", 0, "FlyoutCommandItem1", "FlyoutEnableCommandItem1");
|
|
}
|
public int FlyoutEnable()
|
{
|
return 1;
|
}
|
|
public void FlyoutCommandItem1()
|
{
|
SwApp.SendMsgToUser("Flyout command 1");
|
}
|
|
public int FlyoutEnableCommandItem1()
|
{
|
return 1;
|
}
|
#endregion
|
#endregion
|
}
|
|
}
|