Countdown timer increase on interaction?

半城伤御伤魂 提交于 2019-12-06 12:21:07

I think in essence what you are doing is fine, the real trick is going to be to handle the mouse events.

Here is a quick and dirty example of how you could do this just checking if the mouse is in the client area of the window. Basically on every timer expiry the code gets the mouse position on the screen and checks if that overlaps with the client area of the window. You should probably also check if the window is active etc. but this should be a reasonable starting point.

using System;
using System.Windows.Forms;
using System.Timers;
using System.Drawing;

namespace WinFormsAutoClose
{
  public partial class Form1 : Form
  {
    int _countDown = 5;
    System.Timers.Timer _timer;

    public Form1()
    {
      InitializeComponent();

      _timer = new System.Timers.Timer(1000);
      _timer.AutoReset = true;
      _timer.Elapsed += new ElapsedEventHandler(ProcessTimerEvent);
      _timer.Start();
    }

    private void ProcessTimerEvent(Object obj, System.Timers.ElapsedEventArgs e) 
    {
      Invoke(new Action(() => { ProcessTimerEventMarshaled(); }));
    }

    private void ProcessTimerEventMarshaled()
    {
      if (!IsMouseInWindow())
      {
        --_countDown;
        if (_countDown == 0)
        {
          _timer.Close();
          this.Close();
        }
      }
      else
      {
        _countDown = 5;
      }
    }

    private bool IsMouseInWindow()
    {
      Point clientPoint = PointToClient(Cursor.Position);
      return ClientRectangle.Contains(clientPoint);
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!