2

我有一个表单,如果没有完成鼠标交互,我想在 5 秒后关闭,但如果完成了任何鼠标交互,我希望它关闭countdown + 5 seconds并且每次交互都会增加 5 秒。

到目前为止,这是我想出的:

int countdown = 5;
System.Timers.Timer timer;

启动计时器

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

事件

private void ProcessTimerEvent(Object obj, System.Timers.ElapsedEventArgs e)
{
    --countdown;
    if (countdown == 0)
    {
        timer.Close();
        this.Invoke(new Action(() => { this.Close(); }));
    }
}

只是为了测试,我使用表单 mouseclick 事件将倒计时增加 5,但必须将其更改为不同的事件,因为如果您单击表单上的标签或任何其他控件,它不会增加计时器。

private void NotifierTest_MouseClick(object sender, MouseEventArgs e)
{
    countdown += 5;
}

问题

  • 我是否正在实施倒计时,计数器可以以正确的方式增加?

  • 我应该改变什么吗?

  • 如果与我所做的有任何不同,您将如何做到这一点?

  • 我应该如何处理鼠标点击捕获?

  • 使用低级挂钩?

  • 使用鼠标单击位置并验证它是否在我的 winform 上?

其他选项

我目前正在考虑的另一个选项是捕获鼠标是否在表单区域内,如果鼠标不在该区域内,则启用/禁用关闭倒计时,但我不确定如何与鼠标进行交互,因此以上关于我将如何与鼠标交互的问题。

4

1 回答 1

3

我认为本质上你所做的很好,真正的诀窍是处理鼠标事件。

这是一个快速而肮脏的示例,说明如何仅检查鼠标是否在窗口的客户区域中。基本上在每个计时器到期时,代码都会获取屏幕上的鼠标位置并检查它是否与窗口的客户区重叠。您可能还应该检查窗口是否处于活动状态等,但这应该是一个合理的起点。

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);
    }
  }
}
于 2011-04-25T13:45:44.900 回答