0

I have a WPF program that needs to detect if another software is opened or not. If it is opened, my program will connect to it automatically:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    if(!DataModel.IsConnected)
    {
      connect();
    }
}

However, in this way it can only build connection when that software is opened before I run the WPF window. If I want the WPF program can always detect if the software is open - even if the software is opened after I run the WPF window.

water
  • 138
  • 10

1 Answers1

1

You either need to call the connect() method regularly, for example using a timer, or have the other application notify your WPF application at regular intervals.

Here is a basic example that should give you the idea. It calls the connect() method once the window has been loaded and if the method returns false, it starts a timer that calls the method again every 1.5 seconds until the method returns true.

System.Timers.Timer _timer;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    if (!connect())
    {
        //start a timer that calls connect() at regular intervals until it returns true.
        _timer = new System.Timers.Timer(TimeSpan.FromSeconds(1.5).TotalMilliseconds);
        _timer.Elapsed += Timer_Elapsed;
    }

}

private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    if (connect())
    {
        _timer.Stop();
        _timer.Dispose();
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88