Search code examples
c#wpfdispatchertimer

WPF app inactivity


I want my app do something when it is idling. For that I wrote this code, which works properly only when DispatcherTimer interval is less than 30 seconds, or my app is not active window.

    static DispatcherTimer mIdle;
    public static void HandleWithTimeout(int timeout, Action handler)
    {            
        InputManager.Current.PreProcessInput += delegate(object sender, PreProcessInputEventArgs args)
        {
            mIdle.IsEnabled = false;
            mIdle.IsEnabled = true;
        };
        mIdle = new DispatcherTimer
        {
            Interval = TimeSpan.FromSeconds(timeout),
            IsEnabled = true
        };
        mIdle.Tick += delegate { handler(); };
    }

So how can I make this work in cases when app is active window, and why does this not work properly when timeout >=30 seconds?


Solution

  • I found the answer: instead

    InputManager.Current.PreProcessInput += delegate(object sender, PreProcessInputEventArgs args)
        {
            mIdle.IsEnabled = false;
            mIdle.IsEnabled = true;
        };
    

    I wrote

    InputManager.Current.PreNotifyInput += delegate
            {
                mIdle.IsEnabled = false;
                mIdle.IsEnabled = true;
            };
    

    Here are the differences between PreProcessInput, PreNotifyInput and other InputManager evnets: https://msdn.microsoft.com/en-us/library/system.windows.input.inputmanager(v=vs.110).aspx