How to detect which block instance a selected sketch segment belongs to?

I’m trying to detect when the user selects and deletes a block instance from a drawing. The problem is that, when you select a line in a block, the selected object is a SketchSegment and not a block instance. So I am now trying to find which block instance that sketch segment belongs to.

But SketchBlockInstance seemingly has no way of getting the lines in that block:
https://help.solidworks.com/2021/English/api/sldworksapi/SolidWorks.Interop.sldworks~SolidWorks.Interop.sldworks.ISketchBlockInstance_members.html

I’ve tried getting the sketch that contains the sketch segment, which returns the sketch of the view that the block instance is in. Each view has a sketch that can contain blocks and other sketch segments. If that view contains two identical block instances, you don’t know which one is selected.

Any ideas?

Hi @PeterBrinkhuis

This is an interesting problem. I wasn’t able to find a way to get to the sketch block instance directly via API, however it appears that ISketchSegment::GetName provides the fully qualified name of the segment including the block instance name.

My feature tree is set up like this:
image

And the output of the console for GetName of the currently selected SketchSegment is this:
image

Then, using the ISketchSegment, you can obtain the ISketch object with ISketchSegment::GetSketch and then get a list of its sketch block instances with ISketch::GetSketchBlockInstances. If you loop through those and compare names then you can get your block instance object.

1 Like

Interesting approach! Just as creative as I thought we needed to become :slight_smile:

I’ll test it soon and report back.