簡體   English   中英

在n秒不活動后關閉WPF應用程序

[英]Shutdown WPF application after n seconds of inactivity

如何在'n'秒不活動后關閉WPF應用程序?

有點晚了,但是我想出了這個代碼,它會在任何輸入事件上重啟一個計時器:

  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;
    }
  }

你需要定義“活動”,但基本上你想要啟動一個計時器。 然后每次有一些“活動”(無論是鼠標點擊還是鼠標移動等),計時器都會重置。

然后在計時器達到極限時,只需發布​​一個事件來調用應用程序關閉方法。

msdn社交中有關於此問題的討論。 檢查一下,請發布適合你的內容....

我粘貼了討論中的代碼(我認為它會做你需要的代碼):

public partial class Window1 : Window
{
    private EventHandler handler;
    public Window1()
    {
        InitializeComponent();

        handler = delegate
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(4);
            timer.Tick += delegate
            {
                if (timer != null)
                {
                    timer.Stop();
                    timer = null;
                    System.Windows.Interop.ComponentDispatcher.ThreadIdle -= handler;
                    MessageBox.Show("You get caught!");
                    System.Windows.Interop.ComponentDispatcher.ThreadIdle += handler;
                }

            };

            timer.Start();

            //System.Windows.Interop.ComponentDispatcher.ThreadIdle -= handler;
            Dispatcher.CurrentDispatcher.Hooks.OperationPosted += delegate
            {
                if (timer != null)
                {
                    timer.Stop();
                    timer = null;
                }
            };
        };

        ComponentDispatcher.ThreadIdle += handler;
    }
}
public MainWindow()
    {
        InitializeComponent();
        var timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(10)};
        timer.Tick += delegate
        {
            timer.Stop();
            MessageBox.Show("Logoff trigger");
            timer.Start();
        };
        timer.Start();
        InputManager.Current.PostProcessInput += delegate(object s,  ProcessInputEventArgs r)
        {
            if (r.StagingItem.Input is MouseButtonEventArgs || r.StagingItem.Input is KeyEventArgs)
                timer.Interval = TimeSpan.FromSeconds(10);
        };
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM