Selecting the Topmost Group on Mouse Click in Grasshopper Canvas

Hi everyone,

I’m currently trying to get the topmost group from a mouse click event in Grasshopper. Here’s what I have so far:

var groupsAtCursor = canvas.Document.Objects
    .Where(obj => obj.Attributes.Bounds.IntersectsWith(toleranceRect))
    .OfType<GH_Group>()
    .ToList();

This gives me all the groups under the cursor. However, what I actually need is the group that is visually on top, i.e., the one with the highest Z-order.

I couldn’t find an attribute like ZIndex or anything similar on GH_DocumentObject.Attributes or elsewhere. Am I missing something? Is there a recommended way to determine which object is drawn on top?

Any suggestions or alternative approaches would be appreciated!

Thanks in advance!

Aren’t Document.Objects already sorted by the render order (items in the back come first, in the front come last)?

I did not check on that yet, but this way got me quite reliable results.

    public static T FindDocumentObjectAtMousePosition<T>(GH_Canvas canvas, MouseEventArgs e)
        where T : class, IGH_DocumentObject
    {
        var canvasEvent = new GH_CanvasMouseEvent(canvas.Viewport, e);
        var attribute = canvas.Document.FindAttribute(canvasEvent.CanvasLocation, false);
        return attribute?.DocObject as T;
    }