我有一个表单,如果没有完成任何鼠标交互,我想在 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;
}
问题
其他选项
我目前正在考虑的另一个选项是捕获鼠标是否在表单区域内,并在不在该区域内时启用/禁用关闭倒计时,但我不确定如何与鼠标交互,因此以上关于我如何与鼠标交互的问题。
我认为本质上你正在做的事情很好,真正的技巧是处理鼠标事件。
这是一个快速而肮脏的示例,说明如何仅检查鼠标是否位于窗口的工作区中即可执行此操作。基本上,在每个计时器到期时,代码都会获取屏幕上的鼠标位置,并检查该位置是否与窗口的客户区域重叠。您可能还应该检查窗口是否处于活动状态等,但这应该是一个合理的起点。
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);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)