繁体   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