如何进入LogIn表单 – 如果我的C#程序中没有按键?

我在C#WinForm程序中有登录表单和主表单。

当我处于主窗体并且用户没有按任何键或移动鼠标5分钟时 – 我想转到登录表单。

如何在C#WinForm中执行此操作?

提前致谢

我做了一个小样本,向您展示如何在完整的应用程序级别上实现用户活动检测。 诀窍是使用应用程序消息filter。

当用户5分钟未激活时,此示例将引发消息。

using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApplication2 { static class Program { private static Timer _idleTimer; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); _idleTimer = new Timer(); _idleTimer.Tick += new EventHandler(_idleTimer_Tick); _idleTimer.Interval = (5 * 60) * 1000; // (5 minutes * seconds) * milliseconds Application.AddMessageFilter(new MouseMessageFilter(UserIsActive)); Application.AddMessageFilter(new KeyboardMessageFilter(UserIsActive)); Application.Run(new Form1()); } static void _idleTimer_Tick(object sender, EventArgs e) { MessageBox.Show("You are idle for " + _idleTimer.Interval.ToString() + " milliseconds"); } static void UserIsActive(object sender, EventArgs e) { _idleTimer.Stop(); _idleTimer.Start(); } public class MouseMessageFilter : IMessageFilter { private EventHandler _callback; public MouseMessageFilter(EventHandler callback) { _callback = callback; } private const int WM_MOUSEMOVE = 0x0200; public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_MOUSEMOVE) { _callback(null, null); } return false; } } private class KeyboardMessageFilter : IMessageFilter { private EventHandler _callback; public KeyboardMessageFilter(EventHandler callback) { _callback = callback; } const int WM_KEYDOWN = 0x100; const int WM_KEYUP = 0x0101; const int WM_SYSKEYDOWN = 0x104; const int WM_SYSKEYUP = 0x0105; #region IMessageFilter Members public bool PreFilterMessage(ref Message m) { if ((m.Msg == WM_KEYDOWN) || (m.Msg == WM_SYSKEYDOWN)) { _callback(null, null); } if ((m.Msg == WM_KEYUP) || (m.Msg == WM_SYSKEYUP)) { _callback(null, null); } return false; } #endregion } } } 

将一个计时器放在表单上并让它做正确的事情,无论是什么(关闭当前forms,清除字段等)

您可以使用Timer并将其设置为5秒钟。 然后你有一个属性,说明用户最后一次按键或移动鼠标的时间(你在适当的事件处理程序中设置了这个属性: Form.KeyPressForm.MouseMove )。 如果计时器计时并且自上次用户操作以来的时间超过5分钟,则可以注销当前用户。

但这对我来说并不是一个非常有用的function,我认为这只是一个烦恼。

为所有应用程序表单创建一个空基类(inheritance自Form类,重写此类中的onkeypress和onmousemove事件),并在基本表单的构造函数中创建一个计时器实例,并将计时器间隔设置为5分钟并执行任何必要的清理,如果可能的话! 确保所有表单都使用计时器从这个基类inheritance,然后就完成了。 否则,您最终会在应用程序中编写/修改所有表单以添加计时器并设置间隔!

注意:如果您的应用程序中有大量表单,这将非常有用! 如果你有几个,那么没关系,如果你去每个并添加一个计时器并设置一个间隔并写一些常用的代码来清理

最好的方法是为输入消息创建Windows Hook。 每次收到鼠标或键盘消息时,请重新启动计时器。 计时器过去后,注销用户。

这篇关于在.NET中使用Windows Hooks的MSDN Mag文章应该有所帮助。