Getting inactivity/idle time in a WPF application

前端 未结 4 1544
花落未央
花落未央 2021-01-02 07:20

I was looking for the best approach to find out the if my users are idle in my WPF application. Currently, I take this idle time from operating system, and if they minimize

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 08:02

    1. For such scenarios, we need a Timer which fires back some event after a timeinterval.

    2. And most importantly, we need a callback / eventhandler which gets called everytime any activity of any kind happens in our application, so that we know that our application is running.

    Point 1 can be handled using DispatcherTimer.

    Point 2 can be handled using public event CanExecuteRoutedEventHandler CanExecute; .

    Putting it altogether :

    MainWindow.xaml

    xmlns:cmd="clr-namespace:System.Windows.Input; assembly=Presentationcore"

        
        
    

    MainWindow.xaml.cs

        public partial class MainWindow: Window
        {
            DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.ApplicationIdle);
            bool running = true;
    
            public MainWindow()
            {
                InitializeComponent();
                timer.Interval = TimeSpan.FromSeconds(5);
                timer.Tick += timer_Tick;
                timer.Start();
            }
    
            private void CommandBinding_CanExecute_1(object sender, CanExecuteRoutedEventArgs e)
            {
                running = true;
                e.CanExecute = true;
            }
    
            void timer_Tick(object sender, EventArgs e)
            {
                if (!running)
                    App.Current.Shutdown();
    
                running = false;
            }
        }
    

    We can easily extend this approach to fit our needs.

提交回复
热议问题