Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutdown WPF application after n seconds of inactivity

Tags:

c#

wpf

How do I shutdown a WPF application after 'n' seconds of inactivity?

like image 415
Raj Avatar asked Dec 03 '22 13:12

Raj


2 Answers

A bit late, but I came up with this code, it restarts a timer on any input event:

  public partial class Window1 : Window {
    DispatcherTimer mIdle;
    private const long cIdleSeconds = 3;
    public Window1() {
      InitializeComponent();
      InputManager.Current.PreProcessInput += Idle_PreProcessInput;
      mIdle = new DispatcherTimer();
      mIdle.Interval = new TimeSpan(cIdleSeconds * 1000 * 10000);
      mIdle.IsEnabled = true;
      mIdle.Tick += Idle_Tick;
    }

    void Idle_Tick(object sender, EventArgs e) {
      this.Close();
    }

    void Idle_PreProcessInput(object sender, PreProcessInputEventArgs e) {
      mIdle.IsEnabled = false;
      mIdle.IsEnabled = true;
    }
  }
like image 52
Hans Passant Avatar answered Dec 24 '22 06:12

Hans Passant


You'll need to define "activity", but basically you want to start a timer. Then every time there is some "activity" (whether it's mouse clicks or mouse moves etc.) the timer is reset.

Then in the timer when it reaches your limit just post an event to call the application close method.

like image 28
ChrisF Avatar answered Dec 24 '22 06:12

ChrisF