AnsweredAssumed Answered

How to get block instances in C#

Question asked by Todd Carpenter on Jan 7, 2019
Latest reply on Jan 7, 2019 by Todd Carpenter

Not sure what I'm doing wrong, but this always generates a casting error, 'System.InvalidCastException'.


Here's my short bit of code:

public void Main()


            ModelDoc2 swDoc = (ModelDoc2)swApp.ActiveDoc;

            BlockInstance swBlkIns;

            BlockDefinition swBlkDef;

            SketchManager swSkMgr = swDoc.SketchManager;


            object[] swBlkDefs = (object[])swSkMgr.GetSketchBlockDefinitions();


            int swBlkCnt = swBlkDefs.GetLength(0);


            for (int i = swBlkDefs.GetLowerBound(0); i <= swBlkDefs.GetUpperBound(0); i ++)


                swBlkDef = (BlockDefinition)swBlkDefs[i]; // Error always happens here,

                swBlkIns = (BlockInstance)swBlkDefs[i];   // or here.


I'm guessing I'm missing a step, I haven't found any C# examples of selecting drawing blocks, just VBA, so I'm guessing I need to something in between?


This is SolidWorks2016, SP5.


Thanks for any help.