7 Replies Latest reply on Dec 7, 2012 3:43 AM by Robin Staes

    C# Solidworks update (run code) on Change. Events and callbacks?

    Robin Staes

      Hello,

       

      I'm trying to make an add-in for Solidworks. I need to update my taskpane when 'Custom properties' are updated. On my taskpane is a button. When I click this button two labels on the taskpane show the value and evaluated value of a property. How can I let Solidwork fire my update? I seached for Caalback and Events but I don't know how to put it in my project. Can someone give me a tip or a good tutorial? Enclosed is my project.

       

      Kind regards,


      Robin

        • Re: C# Solidworks update (run code) on Change. Events and callbacks?
          Artem Taturevych

          Not sure that I fully understand your request.

           

          Anyways to set/get/delete properties use ICustomPropertyManager interface.

           

          To handle the moment when the property is changed/added/deleted by user use the following events of PartDoc, AssemblyDoc and DrawingDoc classes:

           

          ChangeCustomPropertyNotifyEventHandler

          AddCustomPropertyNotifyEventHandler

          DeleteCustomPropertyNotifyEventHandler

          ______________________

          Regards,

          Artem Taturevych

          Application Engineer at Intercad

          http://intercad.com.au/

          Tel: +61 2 9454 4444

          • Re: C# Solidworks update (run code) on Change. Events and callbacks?
            Robin Staes

            Oke, I still have this problem. I solved a bit myself but it still doesn't work. I have SwAddin.cs to register and implement my add in. This works fine. Then I have KoppelingTaskpane.cs which makes the taskpane. On this taskpane I have 2 labels and 2 buttons. Now I want the value of the property 'PartNo' of the active document written to label1. With a button on the taskpane this works fine but when I run the code with the eventhandler it doesn't update the label. I can get the value and I can send it to the label1 but it doesn't show the new value. Do I have to reload the taskpane? I tried to do it with a delegate but I can't get it right... Please help me!

             

            Code:

            SwAddin.cs:

             

            1. namespace Callback_Test
            2. {
            3.     /// Summary description for Callback_Test.
            4.     [Guid("fb500eff-b1df-40fb-bf7d-09cd2fc48309"), ComVisible(true)]
            5.     [SwAddin(
            6.         Description = "Test CallBack",
            7.         Title = "Callback Test",
            8.         LoadAtStartup = true
            9.         )]
            10.     public class SwAddin : ISwAddin
            11.     {
            12.         #region Local Variables
            13.           #endregion
            14.         #region SolidWorks Registration
            15.         #endregion
            16.         #region ISwAddin Implementation
            17.         #endregion
            18.         #region UI Methods
            19.         public void UISetup()
            20.         {
            21.             mTaskpaneView = mSWApplication.CreateTaskpaneView2(string.Empty, "Solidworks <-> Isah Koppeling");
            22.             mTaskpaneHost = (KoppelingTaskpane)mTaskpaneView.AddControl(KoppelingTaskpane.SWTASKPANE_PROGID, "");
            23.             mTaskpaneHost.Init(mSWApplication);
            24.         }
            25.         public void UITeardown()
            26.         {
            27.             mTaskpaneHost = null;
            28.             mTaskpaneView.DeleteView();
            29.             Marshal.ReleaseComObject(mTaskpaneView);
            30.             mTaskpaneView = null;
            31.         }
            32.         public bool CompareIDs(int[] storedIDs, int[] addinIDs)
            33.         {
            34.             List<int> storedList = new List<int>(storedIDs);
            35.             List<int> addinList = new List<int>(addinIDs);
            36.             addinList.Sort();
            37.             storedList.Sort();
            38.             if (addinList.Count != storedList.Count)
            39.             {
            40.                 return false;
            41.             }
            42.             else
            43.             {
            44.                 for (int i = 0; i < addinList.Count; i++)
            45.                 {
            46.                     if (addinList[i] != storedList[i])
            47.                     {
            48.                         return false;
            49.                     }
            50.                 }
            51.             }
            52.             return true;
            53.         }
            54.         #endregion
            55.         #region Event Methods
            56.         public bool AttachEventHandlers()
            57.         {
            58.             AttachSwEvents();
            59.             //Listen for events on all currently open docs
            60.             AttachEventsToAllDocuments();
            61.             return true;
            62.         }
            63.         private bool AttachSwEvents()
            64.         {
            65.             try
            66.             {
            67.                 SwEventPtr.ActiveDocChangeNotify += new DSldWorksEvents_ActiveDocChangeNotifyEventHandler(OnDocChange);
            68.                 SwEventPtr.DocumentLoadNotify2 += new DSldWorksEvents_DocumentLoadNotify2EventHandler(OnDocLoad);
            69.                 SwEventPtr.FileNewNotify2 += new DSldWorksEvents_FileNewNotify2EventHandler(OnFileNew);
            70.                 SwEventPtr.ActiveModelDocChangeNotify += new DSldWorksEvents_ActiveModelDocChangeNotifyEventHandler(OnModelChange);
            71.                 SwEventPtr.FileOpenPostNotify += new DSldWorksEvents_FileOpenPostNotifyEventHandler(FileOpenPostNotify);
            72.                 return true;
            73.             }
            74.             catch (Exception e)
            75.             {
            76.                 Console.WriteLine(e.Message);
            77.                 return false;
            78.             }
            79.         }
            80.        
            81.         private bool DetachSwEvents()
            82.         {
            83.             try
            84.             {
            85.                 SwEventPtr.ActiveDocChangeNotify -= new DSldWorksEvents_ActiveDocChangeNotifyEventHandler(OnDocChange);
            86.                 SwEventPtr.DocumentLoadNotify2 -= new DSldWorksEvents_DocumentLoadNotify2EventHandler(OnDocLoad);
            87.                 SwEventPtr.FileNewNotify2 -= new DSldWorksEvents_FileNewNotify2EventHandler(OnFileNew);
            88.                 SwEventPtr.ActiveModelDocChangeNotify -= new DSldWorksEvents_ActiveModelDocChangeNotifyEventHandler(OnModelChange);
            89.                 SwEventPtr.FileOpenPostNotify -= new DSldWorksEvents_FileOpenPostNotifyEventHandler(FileOpenPostNotify);
            90.                 return true;
            91.             }
            92.             catch (Exception e)
            93.             {
            94.                 Console.WriteLine(e.Message);
            95.                 return false;
            96.             }
            97.         }
            98.              
            99.         public void AttachEventsToAllDocuments()
            100.         {
            101.             ModelDoc2 modDoc = (ModelDoc2)iSwApp.GetFirstDocument();
            102.             while (modDoc != null)
            103.             {
            104.                 if (!openDocs.Contains(modDoc))
            105.                 {
            106.                     AttachModelDocEventHandler(modDoc);
            107.                 }
            108.                 else if (openDocs.Contains(modDoc))
            109.                 {
            110.                     bool connected = false;
            111.                     DocumentEventHandler docHandler = (DocumentEventHandler)openDocs[modDoc];
            112.                     if (docHandler != null)
            113.                     {
            114.                         connected = docHandler.ConnectModelViews();
            115.                     }
            116.                 }
            117.                 modDoc = (ModelDoc2)modDoc.GetNext();
            118.             }
            119.         }
            120.         public bool AttachModelDocEventHandler(ModelDoc2 modDoc)
            121.         {
            122.             if (modDoc == null)
            123.                 return false;
            124.             DocumentEventHandler docHandler = null;
            125.             if (!openDocs.Contains(modDoc))
            126.             {
            127.                 switch (modDoc.GetType())
            128.                 {
            129.                     case (int)swDocumentTypes_e.swDocPART:
            130.                         {
            131.                             docHandler = new PartEventHandler(modDoc, this);
            132.                             break;
            133.                         }
            134.                     case (int)swDocumentTypes_e.swDocASSEMBLY:
            135.                         {
            136.                             docHandler = new AssemblyEventHandler(modDoc, this);
            137.                             break;
            138.                         }
            139.                     case (int)swDocumentTypes_e.swDocDRAWING:
            140.                         {
            141.                             docHandler = new DrawingEventHandler(modDoc, this);
            142.                             break;
            143.                         }
            144.                     default:
            145.                         {
            146.                             return false; //Unsupported document type
            147.                         }
            148.                 }
            149.                 docHandler.AttachEventHandlers();
            150.                 openDocs.Add(modDoc, docHandler);
            151.             }
            152.             return true;
            153.         }
            154.         public bool DetachModelEventHandler(ModelDoc2 modDoc)
            155.         {
            156.             DocumentEventHandler docHandler;
            157.             docHandler = (DocumentEventHandler)openDocs[modDoc];
            158.             openDocs.Remove(modDoc);
            159.             modDoc = null;
            160.             docHandler = null;
            161.             return true;
            162.         }
            163.         public bool DetachEventHandlers()
            164.         {
            165.             DetachSwEvents();
            166.             //Close events on all currently open docs
            167.             DocumentEventHandler docHandler;
            168.             int numKeys = openDocs.Count;
            169.             object[] keys = new Object[numKeys];
            170.             //Remove all document event handlers
            171.             openDocs.Keys.CopyTo(keys, 0);
            172.             foreach (ModelDoc2 key in keys)
            173.             {
            174.                 docHandler = (DocumentEventHandler)openDocs[key];
            175.                 docHandler.DetachEventHandlers(); //This also removes the pair from the hash
            176.                 docHandler = null;
            177.             }
            178.             return true;
            179.         }
            180.         #endregion
            181.         #region Event Handlers
            182.         #endregion
            183.     }
            184. }

             

             

            KoppelingTaskpane.cs:

             

            1. namespace Callback_Test
            2. {
            3.     //Declare a new delegate specific to updating the text of a label        
            4.     delegate void UpdateLabels(string text);
            5.  
            6.     [ComVisible(true)]
            7.     [ProgId(SWTASKPANE_PROGID)]
            8.     public partial class KoppelingTaskpane : UserControl
            9.                
            10.     {
            11.             public SldWorks mSWApplication;
            12.             public int mCookie;
            13.             public CommandManager mCommandManager;
            14.             public ModelDoc2 swModel;
            15.             public ModelDoc2 swModel2;
            16.             SolidWorks.Interop.sldworks.View swView = default(SolidWorks.Interop.sldworks.View);
            17.             public SketchManager swSketchMgr;
            18.             public Sketch swSketch;
            19.             public SldWorks swApp;
            20.             ISldWorks iSwApp;
            21.             bool pathName;
            22.             string val = "";
            23.             string valout = "";
            24.             CustomPropertyManager swCustProp;
            25.             int Melding = 0;
            26.             public AssemblyDoc swAssembly;
            27.             public const string SWTASKPANE_PROGID = "Robin.KoppelingTaskpane2_AddInRobin";
            28.            
            29.             public KoppelingTaskpane()
            30.             {
            31.                 InitializeComponent();
            32.             }
            33.            public void Init(SldWorks app)
            34.             {
            35.                 mSWApplication = app;
            36.             }
            37.             public void button1_Click(object sender, EventArgs e)
            38.             {
            39.               
            40.             }
            41.             public void button2_Click(object sender, EventArgs e)
            42.             {
            43.                 UpdateLabel("Button 2 geklikt");
            44.             }
            45.             public void label1_Click(object sender, EventArgs e)
            46.             {
            47.             }
            48.             public void label2_Click(object sender, EventArgs e)
            49.             {
            50.             }
            51.             private void KoppelingTaskpane_Load(object sender, EventArgs e)
            52.             {
            53.             }
            54.             public void help2()
            55.             {
            56.             this.Invoke(new UpdateLabels(UpdateLabel), new object[] { val });
            57.             }
            58.             public void help()
            59.             {
            60.                     swModel = mSWApplication.IActiveDoc2;
            61.                     swCustProp = swModel.Extension.get_CustomPropertyManager("");
            62.                     pathName = swCustProp.Get4("PartNo", false, out val, out valout);
            63.                     help2();
            64.      
            65.             }
            66.             public void UpdateLabel(String str)
            67.             {
            68.                 string Testtest;
            69.                 Testtest = label1.ToString();
            70.                 MessageBox.Show("str = " + Testtest);
            71.                 label1.Text = str;
            72.                 MessageBox.Show("str = " + str);
            73.             }
            74.             void UpdateLabelText(Label lbl, string text)
            75.             {
            76.               
            77.             }
            78.             //This method is invoked by our delegate and actually updates the label //text        
            79.             void UpdateLabelTextByDelegate(Label lbl, string text)
            80.             {
            81.                 lbl.Text = text;
            82.             }
            83.             public void UpdateProps(Label lbl, string text)
            84.             {
            85.                 MessageBox.Show("", "!?");
            86.                 //MessageBox.Show("Button 2 geklikt. Properties moet nu worden geupdate", "Fout");
            87.                 try
            88.                 {
            89.                     // Code die een exceptie kan opleveren
            90.                     MessageBox.Show("" + swApp, "0");
            91.                     swApp = (SldWorks)Activator.CreateInstance(
            92.                     Type.GetTypeFromProgID("SldWorks.Application"));
            93.                     MessageBox.Show("" + swApp, "1");
            94.                     swModel2 = swApp.IActiveDoc2;
            95.                     MessageBox.Show("" + swModel2, "2");
            96.                     swCustProp = swModel2.Extension.get_CustomPropertyManager("");
            97.                     MessageBox.Show("" + swCustProp, "3");
            98.                     pathName = swCustProp.Get4("PartNo", false, out val, out valout);
            99.                     MessageBox.Show("" + pathName, "4");
            100.                     //PropID = swCustProp.Set("PartNo", "Test");
            101.                     //if (val != "" & valout != "")
            102.                     //{
            103.                         MessageBox.Show("" + val, "5");
            104.                         label1.Text = val;
            105.                         MessageBox.Show("" + valout, "6");
            106.                         label2.Text = valout;
            107.                         //MessageBox.Show(
            108.                         //    "Value:                    " + val +
            109.                         //    "\nEvaluated value:          " + valout +
            110.                         //    "\nUp-to-date data:          " + pathName);
            111.                     //}
            112.                     //else
            113.                     //{
            114.                     //    if (Melding == 0)
            115.                     //    {
            116.                     //        MessageBox.Show("Property 'PartNo' bestaat niet");
            117.                     //        Melding++;
            118.                     //    }
            119.                     //}
            120.                         MessageBox.Show("" + textBox1.ToString(), "7");
            121.                         textBox1.Text = "het lukt tot hier";
            122.                         MessageBox.Show("" + textBox1.ToString(), "8");
            123.                     this.Invalidate();
            124.                     InitializeComponent();
            125.                    
            126.                    
            127.                 }
            128.                 catch (System.Exception e)
            129.                 {
            130.                     //Verwerk een systeemexceptie
            131.                    //label1.BeginInvoke(delegate { label1.Text = "No Document"; });
            132.                     MessageBox.Show("Er is geen document geopend: \n" + e);
            133.                 }
            134.             }
            135.         }
            136.     }

             

            EventHandler.cs

             

            1. public class PartEventHandler : DocumentEventHandler
            2.     {
            3.         PartDoc doc;
            4.         bool pathName;
            5.         string val = "";
            6.         string valout = "";
            7.       
            8.         public PartEventHandler(ModelDoc2 modDoc, SwAddin addin)
            9.             : base(modDoc, addin)
            10.         {
            11.             doc = (PartDoc)document;
            12.             //MessageBox.Show("In PartEventHandler..........." + ":" + doc + ":" + doc.ToString());
            13.         }
            14.         override public bool AttachEventHandlers()
            15.         {
            16.             doc.DestroyNotify += new DPartDocEvents_DestroyNotifyEventHandler(OnDestroy);
            17.             doc.NewSelectionNotify += new DPartDocEvents_NewSelectionNotifyEventHandler(OnNewSelection);
            18.             doc.ChangeCustomPropertyNotify += new DPartDocEvents_ChangeCustomPropertyNotifyEventHandler(PropertyChange);
            19.             ConnectModelViews();
            20.             return true;
            21.         }
            22.         override public bool DetachEventHandlers()
            23.         {
            24.             doc.DestroyNotify -= new DPartDocEvents_DestroyNotifyEventHandler(OnDestroy);
            25.             doc.NewSelectionNotify -= new DPartDocEvents_NewSelectionNotifyEventHandler(OnNewSelection);
            26.             doc.ChangeCustomPropertyNotify += new DPartDocEvents_ChangeCustomPropertyNotifyEventHandler(PropertyChange);
            27.             DisconnectModelViews();
            28.             userAddin.DetachModelEventHandler(document);
            29.             return true;
            30.         }
            31.         //Event Handlers
            32.         public int OnDestroy()
            33.         {
            34.             DetachEventHandlers();
            35.             return 0;
            36.         }
            37.         public int PropertyChange(string propName, string Configuration, string oldValue, string NewValue, int valueType)
            38.         {
            39.             UDProp();
            40.             return 0;
            41.         }
            42.         public void UDProp()
            43.         {
            44.             KoppelingTaskpane mc = new KoppelingTaskpane();
            45.             UpdateLabels UpdateLabel = new UpdateLabels(mc.UpdateLabel);
            46.             CustomPropertyManager swCustProp;
            47.             swApp = (SldWorks)Activator.CreateInstance(
            48.                     Type.GetTypeFromProgID("SldWorks.Application"));
            49.             swModel2 = swApp.IActiveDoc2;
            50.             swCustProp = swModel2.Extension.get_CustomPropertyManager("");
            51.             pathName = swCustProp.Get4("PartNo", false, out val, out valout);
            52.             MessageBox.Show("" + valout);
            53.             UpdateLabel(valout);
            54.         }
            55.            
            56.         public int OnNewSelection()
            57.         {
            58.             return 0;
            59.         }
            60.     }

             

            Sorry for my messy code, I tried a lot of things to make it work....

            • Re: C# Solidworks update (run code) on Change. Events and callbacks?
              Robin Staes

              I updated the code above. How to work with the delegate?