Listen for Rhino object selection and run a Grasshopper Script

My scenario is I want to have a grasshopper script that processes the currently selected Rhino objects and runs any time this object selection changes.

I know how to get the current selection from the document, e.g. Rhino.RhinoDoc.ActiveDoc.Objects.GetSelectedObjects() but when it comes to the whole problem I don’t know what the best solution is. I am aware of the trigger component but is that the only option without resorting to some sort of plugin (assuming that makes it possible)? I’m hoping there is a way to use the built-in C# or Rhino script components.

Sure this is possible. But be careful with events in scripts:

This script will only count up, when you select something in Rhino. You can basically replace the DoSomething with something you need.

callback.gh (5.7 KB)

  // Inside Runscript
  // Be extremly careful with events in script components
  // As soon as you change the code, you loose access to unsubscribe
  // from the event. This might cause that an event handler executes more than
  // once. As soon as you finialized your code, please restart Rhino
  // and prevent touching the component again! A simple whitespace added
  // can cause an issue. So be careful
  if (isOn)
  {
    RhinoDoc.SelectObjects -= OnObjectsSelected; // only works if the script is 100% the same
    RhinoDoc.SelectObjects += OnObjectsSelected;
  }
  else
  {
    RhinoDoc.SelectObjects -= OnObjectsSelected;
  }
  A = _counter;

// Outside
  int _counter = 0;
  public void DoSomething()
  {
    // Do whatever you need to do
    _counter++;
    // Ensure that you recompute on change, so that the output is recomputed
    Component.ExpireSolution(true);
  }

  public void OnObjectsSelected(object sender, EventArgs args)
  {
    // Threadsafe
    Rhino.RhinoApp.InvokeOnUiThread(new Action(() => DoSomething()), null);
  }


2 Likes

This GhPython script sounds like it might work for you:

There’s also one further down that returns the guids as well.

1 Like