Hello, I can´t find the thread that is causing the process to remain after exit. Can someone take a look and tell me how to exit properly?
Here is my code:
And this one:
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Timers;
using System.Threading;
using System.IO;
using System.Reflection;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swcommands;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
using SolidWorksTools;
using System.Collections;
namespace Callback_Test
{
[ComVisible(true)]
[ProgId(SWTASKPANE_PROGID)]
public partial class KoppelingTaskpane : UserControl
{
#region variables
Thread thread;
private delegate void RefreshGUI();
private delegate void RefreshGUI2();
private delegate void UpdateGUI();
private delegate void ChooseGrpbox();
public static bool GetProperties = false;
public static bool UpdateProperties = false;
delegate void TextBoxDelegate(string message);
public static SldWorks mSWApplication;
//public static IsahCOMScripting.IIsahApplication IsahApp;
public int mCookie;
public SketchManager swSketchMgr;
public Sketch swSketch;
public static ISldWorks swApp;
public static ModelDoc2 swModel;
public static ModelDoc2 model = default(ModelDoc2);
public ModelDocExtension swModelDocExt;
public CustomPropertyManager swCustProp;
static string val = "";
static string PartNo = "";
static string Artikelnummer = "";
static string Description2 = "";
static string Description = "";
static string Project = "";
public AssemblyDoc swAssembly;
public KoppelingTaskpane mTaskpaneHost;
public int stop = 0;
public SwAddin addin;
public PartDoc doc;
public static bool groupBox2Visable = false;
public static bool groupBox1Visable = false;
public static bool docopen;
public static bool GotType = true;
public static bool DocLoad = false;
static int i = 0;
static int w = 0;
public static string str2 = "1";
public const string SWTASKPANE_PROGID = "Robin.KoppelingTaskpane2_AddInRobin";
public delegate void UpdateLabels(string text);
public bool trui;
public ArrayList s = new ArrayList();
public bool PropertiesChanged = false;
public DataTable table;
public bool CheckedIn = false;
public static bool threadstop = false;
#endregion
public KoppelingTaskpane()
{
InitializeComponent();
thread = new Thread(new ThreadStart(MyThreadLoop));
thread.IsBackground = true;
thread.Start();
ToolTip toolTip1 = new ToolTip();
}
private void MyThreadLoop()
{
while (true)
{
if (threadstop == true)
{
//MessageBox.Show("Applicatie wordt gesloten");
thread.Abort();
Application.Exit();
}
int i = 1000;
SelectGroupBox();
if (DocLoad)
{
try
{
if (swCustProp.Get("Checked In") == "Yes")
{
CheckedIn = true;
}
else
{
CheckedIn = false;
}
}
catch
{
}
}
if (GotType)
{
UpdateTheGuiNow2();
Thread.Sleep(300);
i = i - 300;
GetModelType();
}
if (GetProperties)
{
UpdateTheGuiNow2();
Thread.Sleep(300);
i = i - 300;
GetProps();
}
if (UpdateProperties)
{
UpdateTheGuiNow2();
Thread.Sleep(300);
i = i - 300;
UpdateProps();
UpdateTheGuiNow3();
}
UpdateTheGuiNow2();
Thread.Sleep(i);
}
}
private bool GetProps()
{
try
{
swApp = (SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application"));
}
catch (System.Exception e)
{
MessageBox.Show("geen swApp geladen");
return false;
}
try
{
swModel = swApp.IActiveDoc2;
DocLoad = true;
}
catch (System.Exception e)
{
MessageBox.Show("geen swModel geladen");
return false;
}
try
{
swCustProp = swModel.Extension.get_CustomPropertyManager("");
}
catch (System.Exception e)
{
//MessageBox.Show("geen swCustProp geladen");
return false;
}
try
{
swCustProp.Get4("PartNo", false, out val, out PartNo);
swCustProp.Get4("Artikelnummer", false, out val, out Artikelnummer);
swCustProp.Get4("Description", false, out val, out Description);
swCustProp.Get4("Description 2", false, out val, out Description2);
swCustProp.Get4("Project", false, out val, out Project);
//MessageBox.Show("GetProperties = " + GetProperties);
GetProperties = false;
UpdateProperties = true;
return true;
}
catch (System.Exception e)
{
MessageBox.Show("geen properties geladen");
return false;
}
}
public void RefreshKoppelingTaskpane2()
{
if (this.flowLayoutPanel1.InvokeRequired)
{
this.Invoke(new RefreshGUI2(RefreshKoppelingTaskpane2));
return;
}
this.flowLayoutPanel1.Visible = false;
}
public void RefreshKoppelingTaskpane()
{
if (this.flowLayoutPanel1.InvokeRequired)
{
this.Invoke(new RefreshGUI(RefreshKoppelingTaskpane));
return;
}
//this.flowLayoutPanel1.Refresh();
this.TBPartNo.Refresh();
this.TBPartNoA.Refresh();
this.TBArtikelnummer.Refresh();
this.flowLayoutPanel1.Refresh();
this.Refresh();
this.Hide();
this.Show();
}
public static bool GetModelType()
{
try
{
swApp = (SldWorks)Activator.CreateInstance(
Type.GetTypeFromProgID("SldWorks.Application"));
model = (ModelDoc2)swApp.ActiveDoc;
//MessageBox.Show("GetModelType");
}
catch
{
//MessageBox.Show("try getmodtype");
return false;
}
try
{
switch (model.GetType())
{
case (int)swDocumentTypes_e.swDocPART:
{
//MessageBox.Show("Part");
KoppelingTaskpane.groupBox2Visable = false;
KoppelingTaskpane.groupBox1Visable = true;
//MessageBox.Show("GotType = " + GotType);
GotType = false;
GetProperties = true;
break;
}
case (int)swDocumentTypes_e.swDocASSEMBLY:
{
//MessageBox.Show("Assembly");
KoppelingTaskpane.groupBox2Visable = true;
KoppelingTaskpane.groupBox1Visable = false;
//MessageBox.Show("GotType = " + GotType);
GotType = false;
GetProperties = true;
break;
}
case (int)swDocumentTypes_e.swDocDRAWING:
{
//MessageBox.Show("Drawing");
KoppelingTaskpane.groupBox2Visable = false;
KoppelingTaskpane.groupBox1Visable = false;
//MessageBox.Show("GotType = " + GotType);
GotType = false;
GetProperties = true;
break;
}
default:
{
//MessageBox.Show("geen document");
KoppelingTaskpane.groupBox2Visable = false;
KoppelingTaskpane.groupBox1Visable = false;
GotType = false;
GetProperties = true;
return false; //Unsupported document type
}
}
}
catch
{
return false;
}
return true;
}
private void SelectGroupBox()
{
if (CheckedIn)
{
if (TBArtikelnummer.InvokeRequired)
{
TBArtikelnummer.Invoke(new ChooseGrpbox(SelectGroupBox));
return;
}
TBArtikelnummer.Enabled = false;
TBDescription.Enabled = false;
TBDescription2.Enabled = false;
TBDescriptionA.Enabled = false;
TBDescriptionA2.Enabled = false;
}
else
{
if (TBArtikelnummer.InvokeRequired)
{
TBArtikelnummer.Invoke(new ChooseGrpbox(SelectGroupBox));
return;
}
TBArtikelnummer.Enabled = true;
TBDescription.Enabled = true;
TBDescription2.Enabled = true;
TBDescriptionA.Enabled = true;
TBDescriptionA2.Enabled = true;
}
if (groupBox1Visable == true)
{
if (groupBox1.InvokeRequired)
{
groupBox1.Invoke(new ChooseGrpbox(SelectGroupBox));
return;
}
this.groupBox1.Visible = true;
}
else
{
if (groupBox1.InvokeRequired)
{
groupBox1.Invoke(new ChooseGrpbox(SelectGroupBox));
return;
}
this.groupBox1.Visible = false;
}
if (groupBox2Visable == true)
{
if (groupBox2.InvokeRequired)
{
groupBox2.Invoke(new ChooseGrpbox(SelectGroupBox));
return;
}
this.groupBox2.Visible = true;
}
else
{
if (groupBox2.InvokeRequired)
{
groupBox2.Invoke(new ChooseGrpbox(SelectGroupBox));
return;
}
this.groupBox2.Visible = false;
}
if (groupBox1Visable == false && groupBox2Visable == false)
{
if (button1.InvokeRequired == true || button2.InvokeRequired == true || button3.InvokeRequired == true)
{
button1.Invoke(new ChooseGrpbox(SelectGroupBox));
return;
}
button1.Visible = false;
button2.Visible = false;
button3.Visible = false;
button7.Visible = false;
}
else
{
if (button1.InvokeRequired == true || button2.InvokeRequired == true || button3.InvokeRequired == true)
{
button1.Invoke(new ChooseGrpbox(SelectGroupBox));
return;
}
button1.Visible = true;
button2.Visible = true;
button3.Visible = true;
button7.Visible = true;
}
}
private void UpdateProps()
{
if (TBPartNo.InvokeRequired)
{
TBPartNo.Invoke(new UpdateGUI(UpdateProps));
return;
}
this.TBPartNo.Text = PartNo;
this.TBArtikelnummer.Text = Artikelnummer;
this.TBDescription2.Text = Description2;
this.TBDescription.Text = Description;
this.TBPartNoA.Text = PartNo;
this.TBProject.Text = Project;
this.TBDescriptionA.Text = Description;
this.TBDescriptionA2.Text = Description2;
UpdateProperties = false;
}
private void UpdateTheGuiNow2()
{
if (label3.InvokeRequired)
{
label3.Invoke(new UpdateGUI(UpdateTheGuiNow2));
return;
}
if (PropertiesChanged)
{
button1.Enabled = true;
button2.Enabled = true;
}
else
{
button1.Enabled = false;
button2.Enabled = false;
}
label3.Text = DateTime.Now.ToString("MM-dd-yyyy\nHH:mm:ss");
}
private void UpdateTheGuiNow3()
{
}
public void Init(SldWorks app)
{
mSWApplication = app;
}
public void SetProperties()
{
if (groupBox1Visable == true)
{
if (swCustProp.Get("Artikelnummer") != "")
{
swCustProp.Set("Artikelnummer", "" + TBArtikelnummer.Text);
}
else
{
swCustProp.Add2("Artikelnummer", 30, "" + TBArtikelnummer.Text);
}
if (swCustProp.Get("PartNo") != "")
{
swCustProp.Set("PartNo", "$PRP:\"SW-File Name\"");
}
else
{
swCustProp.Add2("PartNo", 30, "$PRP:\"SW-File Name\"");
}
if (swCustProp.Get("Description") != "")
{
swCustProp.Set("Description", "" + TBDescription.Text);
}
else
{
swCustProp.Add2("Description", 30, "" + TBDescription.Text);
}
if (swCustProp.Get("Description 2") != "")
{
swCustProp.Set("Description 2", "" + TBDescription2.Text);
}
else
{
swCustProp.Add2("Description 2", 30, "" + TBDescription2.Text);
}
}
if (groupBox2Visable == true)
{
if (swCustProp.Get("Artikelnummer") != "")
{
swCustProp.Set("Artikelnummer", "" + TBArtikelnummerA.Text);
}
else
{
swCustProp.Add2("Artikelnummer", 30, "" + TBArtikelnummerA.Text);
}
if (swCustProp.Get("PartNo") != "")
{
swCustProp.Set("PartNo", "$PRP:\"SW-File Name\"");
}
else
{
swCustProp.Add2("PartNo", 30, "$PRP:\"SW-File Name\"");
}
if (swCustProp.Get("Description") != "")
{
swCustProp.Set("Description", "" + TBDescriptionA.Text);
}
else
{
swCustProp.Add2("Description", 30, "" + TBDescriptionA.Text);
}
if (swCustProp.Get("Description 2") != "")
{
swCustProp.Set("Description 2", "" + TBDescriptionA2.Text);
}
else
{
swCustProp.Add2("Description 2", 30, "" + TBDescriptionA2.Text);
}
if (swCustProp.Get("Project") != "")
{
swCustProp.Set("Project", "" + TBProject.Text);
}
else
{
swCustProp.Add2("Project", 30, "" + TBProject.Text);
}
}
Thread.Sleep(1000);
GetProperties = false;
UpdateProperties = true;
PropertiesChanged = false;
string modelpath = swModel.GetPathName();
string modelFileName = Path.GetFileName(modelpath);
int errors = 0;
int warnings = 0;
string convFileName = modelpath + modelFileName;
bool Success = swModel.Extension.SaveAs(modelpath, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref errors, ref warnings);
}
private void KoppelingTaskpane_Load(object sender, EventArgs e)
{
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(this.TBDescription2, "My TBDescription2");
ToolTip toolTip2 = new ToolTip();
toolTip2.AutoPopDelay = 5000;
toolTip2.InitialDelay = 1000;
toolTip2.ReshowDelay = 500;
toolTip2.ShowAlways = true;
toolTip2.SetToolTip(this.TBDescription, "My TBDescription");
ToolTip toolTip3 = new ToolTip();
toolTip3.AutoPopDelay = 5000;
toolTip3.InitialDelay = 1000;
toolTip3.ReshowDelay = 500;
toolTip3.ShowAlways = true;
toolTip3.SetToolTip(this.label3, "My label3");
}
#region button click
private void button1_Click(object sender, EventArgs e)
{
//GetProps();
SetProperties();
}
public void button2_Click(object sender, EventArgs e)
{
FindDrawingWithDocument();
}
private void button3_Click(object sender, EventArgs e)
{
string waarde = "";
if (swCustProp.Get("Checked in") != "")
{
swCustProp.Set("Checked in", "Yes");
}
else
{
swCustProp.Add2("Checked in", 11, "Yes");
}
string Designcode = "";
string Description = "";
string Leeg = "";
string Partcode = "";
string Old_Partcode = "";
string IsahUserCode = "";
string insertdesign = "";
if (groupBox1Visable == true)
{
Designcode = "'" + PartNo + "'";
Description = "'" + TBDescription.Text + "'";
Leeg = "''";
Partcode = "'" + TBArtikelnummer.Text + "'";
Partcode = Partcode.Replace(" ", "");
Old_Partcode = Partcode;
IsahUserCode = "'ROBIN'";
insertdesign = "";
}
if (groupBox2Visable == true)
{
Designcode = "'" + PartNo + "'";
Description = "'" + TBDescriptionA.Text + "'";
Leeg = "''";
Partcode = "'" + TBArtikelnummerA.Text + "'";
Partcode = Partcode.Replace(" ", "");
Old_Partcode = Partcode;
IsahUserCode = "'ROBIN'";
insertdesign = "";
}
MessageBox.Show("groupBox2Visable = " + groupBox2Visable + "\ngroupBox1Visable = " + groupBox1Visable + "\nDesigncode = " + Designcode + "\nDescription = " + Description + "\nLeeg = " + Leeg + "\nPartcode = " + Partcode + "\nOld_Partcode = " + Old_Partcode + "\nIsahUserCode = " + IsahUserCode);
try
{
insertdesign = "EXECUTE IP_ins_Design @Designcode = " + Designcode +
", @CustId = " + Leeg +
", @EmpId = " + Leeg +
", @DesignGrpCode = " + Leeg +
", @Description = " + Description +
", @CustDesignCode = " + Leeg +
", @CreDate = " + Leeg +
", @DesignRevNr = " + Leeg +
", @RevDate = " + Leeg +
", @DesignPath = " + Leeg +
", @DesignStatusCode = " + Leeg +
", @ShortName = " + Leeg +
", @LastUpdatedOn = " + Leeg +
", @IsahUserCode = " + IsahUserCode;
System.Windows.Forms.Clipboard.SetText(insertdesign);
//MessageBox.Show("" + DBConnection.ConnectDatabase.InsertDB(insertdesign).ToString());
waarde = DBConnection.ConnectDatabase.InsertDB(insertdesign).ToString();
}
catch
{
MessageBox.Show("Fout in IP_ins_Design " + waarde);
}
try
{
if (waarde == "13")
{
//MessageBox.Show("1 " + waarde);
//MessageBox.Show("Partcode = " + Partcode);
//MessageBox.Show("Designcode = " + Designcode);
//MessageBox.Show("Leeg = " + Leeg);
//MessageBox.Show("IsahUserCode = " + IsahUserCode);
insertdesign = "EXECUTE IP_ins_PartDesign " +
"@Partcode = " + Partcode +
", @Designcode = " + Designcode +
", @LastUpdatedOn = " + Leeg +
", @IsahUserCode = " + IsahUserCode;
waarde = DBConnection.ConnectDatabase.InsertDB(insertdesign).ToString();
}
else
{
insertdesign = null;
}
}
catch
{
MessageBox.Show("Fout in IP_ins_PartDesign " + waarde);
}
try
{
string LastUpdatedOn = "'" + DBConnection.ConnectDatabase.LastUpdatedOn(Old_Partcode).ToString() + "'";
insertdesign = "EXECUTE IP_upd_Part " +
"@Old_Partcode = " + Partcode +
", @Designcode = " + Designcode +
", @Old_LastUpdatedOn = " + LastUpdatedOn +
", @IsahUserCode = " + IsahUserCode;
waarde = DBConnection.ConnectDatabase.InsertDB(insertdesign).ToString();
}
catch
{
MessageBox.Show("Fout in IP_upd_Part " + waarde);
}
}
private void button1_EnabledChanged(object sender, EventArgs e)
{
var btn = (Button)sender;
btn.ForeColor = btn.Enabled ? Color.Black : Color.Silver;
}
private void button1_Paint(object sender, PaintEventArgs e)
{
var btn = (Button)sender;
var drawBrush = new SolidBrush(System.Drawing.Color.Gray);
if (PropertiesChanged) drawBrush = new SolidBrush(System.Drawing.Color.Black);
var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
e.Graphics.DrawString(btn.Text, btn.Font, drawBrush, e.ClipRectangle, sf);
drawBrush.Dispose();
sf.Dispose();
}
#endregion
#region label click
public void label1_Click(object sender, EventArgs e)
{
}
public void label2_Click(object sender, EventArgs e)
{
try
{
this.textBox4.Text = this.TBDescription.Text;
this.groupBox1.Controls.Add(this.textBox4);
this.groupBox1.Controls.Remove(this.TBDescription);
}
catch
{
MessageBox.Show("asdhflkajshf");
}
}
private void label3_Click(object sender, EventArgs e)
{
}
#endregion
private void groupBox1_Enter(object sender, EventArgs e)
{
}
public void LabeltoTextbox()
{
this.TBDescription.Text = this.textBox4.Text;
this.groupBox1.Controls.Add(this.TBDescription);
this.groupBox1.Controls.Remove(this.textBox4);
}
private void textBox2_Enter(object sender, EventArgs e)
{
}
private void CheckKeys(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
LabeltoTextbox();
}
}
private void TBArtikelnummer_SelectedIndexChanged(object sender, EventArgs e)
{
string zoekstring = "SELECT partcode, description, measure FROM T_part WHERE partcode LIKE '%" + TBArtikelnummer.Text + "%' order by partcode";
table = DBConnection.ConnectDatabase.MakeTable(zoekstring);
TBArtikelnummer.ValueMember = table.Columns[1].ColumnName;
TBDescription.Text = TBArtikelnummer.SelectedValue.ToString();
TBArtikelnummer.ValueMember = table.Columns[2].ColumnName;
TBDescription2.Text = TBArtikelnummer.SelectedValue.ToString();
PropertiesChanged = true;
}
private void TBArtikelnummerA_SelectedIndexChanged(object sender, EventArgs e)
{
string zoekstring = "SELECT partcode, description, measure FROM T_part WHERE partcode LIKE '%" + TBArtikelnummerA.Text + "%' order by partcode";
table = DBConnection.ConnectDatabase.MakeTable(zoekstring);
TBArtikelnummerA.ValueMember = table.Columns[1].ColumnName;
TBDescriptionA.Text = TBArtikelnummerA.SelectedValue.ToString();
TBArtikelnummerA.ValueMember = table.Columns[2].ColumnName;
TBDescriptionA2.Text = TBArtikelnummerA.SelectedValue.ToString();
PropertiesChanged = true;
}
private void TBDescription_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void TBArtikelnummer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
{
}
}
private void TBArtikelnummer_TextChanged(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
MessageBox.Show("button5");
string zoekstring = "SELECT partcode, description, measure FROM T_part WHERE partcode LIKE '%" + TBArtikelnummer.Text + "%' order by partcode";
table = DBConnection.ConnectDatabase.MakeTable(zoekstring);
TBArtikelnummer.DataSource = table;
TBArtikelnummer.DisplayMember = table.Columns[0].ColumnName;
TBArtikelnummer.ValueMember = table.Columns[1].ColumnName;
}
private void button6_Click(object sender, EventArgs e)
{
string zoekstring = "SELECT partcode, description, measure FROM T_part WHERE description LIKE '%" + TBDescription.Text + "%' order by partcode";
table = DBConnection.ConnectDatabase.MakeTable(zoekstring);
if (table != null)
{
TBArtikelnummer.DataSource = table;
TBArtikelnummer.DisplayMember = table.Columns[0].ColumnName;
TBArtikelnummer.ValueMember = table.Columns[1].ColumnName;
}
else
{
MessageBox.Show("Geen resultaten");
}
}
private void button8_Click(object sender, EventArgs e)
{
string zoekstring = "SELECT partcode, description, measure FROM T_part WHERE partcode LIKE '%" + TBArtikelnummerA.Text + "%' order by partcode";
table = DBConnection.ConnectDatabase.MakeTable(zoekstring);
TBArtikelnummerA.DataSource = table;
TBArtikelnummerA.DisplayMember = table.Columns[0].ColumnName;
TBArtikelnummerA.ValueMember = table.Columns[1].ColumnName;
}
private void button9_Click(object sender, EventArgs e)
{
string zoekstring = "SELECT partcode, description, measure FROM T_part WHERE description LIKE '%" + TBDescriptionA.Text + "%' order by partcode";
table = DBConnection.ConnectDatabase.MakeTable(zoekstring);
if (table != null)
{
TBArtikelnummerA.DataSource = table;
TBArtikelnummerA.DisplayMember = table.Columns[0].ColumnName;
TBArtikelnummerA.ValueMember = table.Columns[1].ColumnName;
}
else
{
MessageBox.Show("Geen resultaten");
}
}
private void KoppelingTaskpane_FormClosing(object sender, EventArgs e)
{
Application.Exit();
}
}
}
And this one:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
using System.Reflection;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swpublished;
using SolidWorks.Interop.swconst;
using SolidWorksTools;
using SolidWorksTools.File;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
namespace Callback_Test
{
/// Summary description for Callback_Test.
[Guid("fb500eff-b1df-40fb-bf7d-09cd2fc48309"), ComVisible(true)]
[SwAddin(
Description = "Test CallBack",
Title = "Callback Test",
LoadAtStartup = true
)]
public class SwAddin : ISwAddin
{
#region Local Variables
public ISldWorks iSwApp = null;
ICommandManager iCmdMgr = null;
int addinID = 0;
BitmapHandler iBmp;
public SldWorks mSWApplication2;
public int mSWCookie;
private TaskpaneView mTaskpaneView;
public KoppelingTaskpane mTaskpaneHost;
public SldWorks mSWApplication;
public int mCookie;
public CommandManager mCommandManager;
//public ModelDoc2 swModel;
CustomPropertyManager swCustProp;
bool pathName;
string val = "";
string valout = "";
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;
PartDoc doc;
#region Event Handler Variables
Hashtable openDocs = new Hashtable();
SolidWorks.Interop.sldworks.SldWorks SwEventPtr = null;
#endregion
#region Property Manager Variables
UserPMPage ppage = null;
#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
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)
{
mSWApplication = (SldWorks)ThisSW;
mSWCookie = cookie;
// Set-up add-in call back info
bool result = mSWApplication.SetAddinCallbackInfo(0, this, cookie);
iSwApp = (ISldWorks)ThisSW;
addinID = cookie;
//Setup callbacks
iSwApp.SetAddinCallbackInfo(0, this, addinID);
#region Setup the Event Handlers
SwEventPtr = (SolidWorks.Interop.sldworks.SldWorks)iSwApp;
openDocs = new Hashtable();
AttachEventHandlers();
#endregion
this.UISetup();
return true;
}
public bool DisconnectFromSW()
{
DetachEventHandlers();
System.Runtime.InteropServices.Marshal.ReleaseComObject(iSwApp);
iSwApp = null;
//The addin _must_ call GC.Collect() here in order to retrieve all managed code pointers
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
this.UITeardown();
return true;
}
#endregion
#region UI Methods
public void UISetup()
{
mTaskpaneView = mSWApplication.CreateTaskpaneView2(Assembly.GetExecutingAssembly().Location.Replace(".dll", ".bmp"), "Solidworks <-> Isah Koppeling");
mTaskpaneHost = (KoppelingTaskpane)mTaskpaneView.AddControl(KoppelingTaskpane.SWTASKPANE_PROGID, "");
if (mTaskpaneHost != null)
{
mTaskpaneHost.Init(this.mSWApplication);
}
}
public void UITeardown()
{
KoppelingTaskpane.threadstop = true;
mTaskpaneHost = null;
mTaskpaneView.DeleteView();
Marshal.ReleaseComObject(mTaskpaneView);
mTaskpaneView = null;
Application.ExitThread();
Application.Exit();
}
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;
}
#endregion
#region Event Methods
public bool AttachEventHandlers()
{
AttachSwEvents();
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);
SwEventPtr.DestroyNotify += new DSldWorksEvents_DestroyNotifyEventHandler(OnDocClose);
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);
SwEventPtr.DestroyNotify += new DSldWorksEvents_DestroyNotifyEventHandler(OnDocClose);
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()
{
KoppelingTaskpane.GotType = true;
KoppelingTaskpane.GetProperties = true;
KoppelingTaskpane.UpdateProperties = true;
AttachEventsToAllDocuments();
return 0;
}
public int OnDocLoad(string docTitle, string docPath)
{
AttachEventsToAllDocuments();
return 0;
}
int FileOpenPostNotify(string FileName)
{
AttachEventsToAllDocuments();
return 0;
}
public int OnFileNew(object newDoc, int docType, string templateName)
{
AttachEventsToAllDocuments();
//KoppelingTaskpane.GotType = true;
return 0;
}
public int OnModelChange()
{
AttachEventsToAllDocuments();
return 0;
}
public int OnDocClose()
{
KoppelingTaskpane.GotType = true;
KoppelingTaskpane.GetProperties = true;
KoppelingTaskpane.UpdateProperties = true;
return 0;
}
#endregion
}
}