Pouria Sharif Pouria Sharif - 4 days ago 6
C# Question

How can I fire event for system variables?

I am trying to make event that fire when

Application.OpenForms.Count
changed?

Answer

Here is how to do this very simply with Rx. First, NuGet "System.Reactive.Windows.Forms", and then you can do this:

IDisposable subscription =
    Observable
        .Interval(TimeSpan.FromMilliseconds(100.0))
        .Select(n => Application.OpenForms.Count)
        .DistinctUntilChanged()
        .Subscribe(count =>
        {
            /* Changed so do something here */
            Console.WriteLine(count);
        });

This is obviously a polling-based solution so you need to choose an appropriate TimeSpan for your needs.

To stop the subscription, when closing down your application, you just call subscription.Dispose();.

Comments