倒计时器会增加互动吗?

如果没有完成鼠标交互,我有一个表格要在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; } 

问题

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

  • 我该改变什么吗?

  • 如果与我所做的有什么不同,你会怎么做?

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

  • 使用低水平钩?

  • 使用鼠标点击位置并validation我的winform上是否存在?

其他选择

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

我认为你在做什么很好,真正的诀窍是处理鼠标事件。

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

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