[英]How to detect my application is idle in c# (form covered)?
我今天有這個問題,我看到了這個解決方案:
我嘗試過,但是我的表單覆蓋了userControls和其他元素,並且mouseover或keydown事件僅在這些元素的空白處觸發。
有沒有更好的辦法?
無需與計時器和鼠標事件一起破解解決方案。 只需處理Application.Idle事件。
Application.Idle += Application_Idle;
private void Application_Idle(object sender, EventArgs e)
{
// The application is now idle.
}
如果您想要一種更動態的方法,則可以訂閱Form
所有事件,因為最終如果用戶空閑,則永遠不會引發任何事件。
private void HookEvents()
{
foreach (EventInfo e in GetType().GetEvents())
{
MethodInfo method = GetType().GetMethod("HandleEvent", BindingFlags.NonPublic | BindingFlags.Instance);
Delegate provider = Delegate.CreateDelegate(e.EventHandlerType, this, method);
e.AddEventHandler(this, provider);
}
}
private void HandleEvent(object sender, EventArgs eventArgs)
{
lastInteraction = DateTime.Now;
}
您可以聲明一個全局變量private DateTime lastInteraction = DateTime.Now;
並從事件處理程序分配給它。 然后,您可以編寫一個簡單的屬性來確定自上次用戶交互以來已過去了幾秒鍾。
private TimeSpan LastInteraction
{
get { return DateTime.Now - lastInteraction; }
}
然后按照原始解決方案中所述,使用Timer
輪詢屬性。
private void timer1_Tick(object sender, EventArgs e)
{
if (LastInteraction.TotalSeconds > 90)
{
MessageBox.Show("Idle!", "Come Back! I need You!");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.