Event listener and document opening

Hello. I’m trying to make a component that listens for change events on the DocumentUserText. When the event fires, the Value of the “RedLineGuids” key is read from the DocumentUserText and output from the component. The change listener does work, but I also want the Value to be read automatically when the Rhino document open event occurs and when the Grasshopper document open event occurs. The first one works, but I still don’t understand how to implement the second one.

    protected override void SolveInstance(IGH_DataAccess DA)
    {
        bool go = false;

        this.activeDoc = Rhino.RhinoDoc.ActiveDoc;
        this.ghDocument = this.OnPingDocument();

        DA.GetData(0, ref go);

        if (!go)
        {
            UnsubscribeAll();
            return;
        }

        Subscribe();

        DA.SetData(0, actualString);
    }

    private string GetDUT()
    {
        var allStrings = activeDoc.Strings.GetValue("RedLineGuids");

        if (allStrings != null)
        {
            return allStrings;
        }
        return null;
    }

    private void Subscribe()
    {
        RhinoDoc.UserStringChanged += OnUserStringChanged;
        RhinoDoc.EndOpenDocument += OnEndOpenDocument;
    }

    private void UnsubscribeAll()
    {
        RhinoDoc.UserStringChanged -= OnUserStringChanged;
        RhinoDoc.EndOpenDocument -= OnEndOpenDocument;
    }

    private void OnUserStringChanged(object sender, RhinoDoc.UserStringChangedArgs e)
    {
        RhinoApp.Idle += OnRhinoIdleRecompute;
    }

    private void OnEndOpenDocument(object sender, DocumentOpenEventArgs e)
    {
        this.activeDoc = Rhino.RhinoDoc.ActiveDoc;

        RhinoApp.Idle += OnRhinoIdleRecompute;
    }

    private void OnRhinoIdleRecompute(object sender, EventArgs e)
    {
        RhinoApp.Idle -= OnRhinoIdleRecompute;
        actualString = GetDUT();

        ghDocument.ScheduleSolution(5, UpdateComponent);
    }

    private void UpdateComponent(GH_Document doc)
    {
        ExpireSolution(true);
    }

Hi @p-e-t-e-r ,
If you want to get notified when new Grasshopper document opens, you can subscribe to GH_DocumentServer.DocumentAdded event. If you want to be notified when Grasshopper Editor is opened for the first time, subscribe to Instances.CanvasCreated event. (Subscribe to these events inside the constructor of your Component)

        Grasshopper.Instances.CanvasCreated += OnCanvasCreated;
        Grasshopper.Instances.DocumentServer.DocumentAdded += OnDocumentAdded;
        private void OnDocumentAdded(GH_DocumentServer sender, GH_Document doc)
        {
            
        }

        private void OnCanvasCreated(GH_Canvas canvas)
        {

        }
1 Like

Thanks Derryl. Your answer helped me.