2010-08-25 72 views
2

我在寫一個相對簡單的C#項目。認爲「公共Web終端」。從本質上來說,它有一個最大化的形式,其上有一個填充停靠的Web瀏覽器。我使用的Web瀏覽器控件是WebKit的控制在這裏找到:.NET - 通過頑固控制檢測鼠標移動

WebKit Download Page

我試圖通過保持它代表鼠標移動或按鍵被做了最後一次的DateTime檢測系統空閒時間。

我已經設立了事件處理程序(見下面的代碼),並遇到了一個絆腳石。當鼠標移動到Web文檔上時,鼠標(和鍵)事件似乎不會觸發。當我的鼠標觸及Web瀏覽器控件的垂直滾動條部分時,它確實工作正常,所以我知道代碼是可以的 - 這似乎是控件的某種「疏漏」(缺少更好的單詞)。

我想我的問題是 - 對你們所有的編碼者,你將如何去處理這個問題?

this.webKitBrowser1.KeyPress += new KeyPressEventHandler(handleKeyPress); 
this.webKitBrowser1.MouseMove += new MouseEventHandler(handleAction); 
this.webKitBrowser1.MouseClick += new MouseEventHandler(handleAction); 
this.webKitBrowser1.MouseDown += new MouseEventHandler(handleAction); 
this.webKitBrowser1.MouseUp += new MouseEventHandler(handleAction); 
this.webKitBrowser1.MouseDoubleClick += new MouseEventHandler(handleAction); 

void handleKeyPress(object sender, KeyPressEventArgs e) 
{ 
    this.handleAction(sender, null); 
} 

void handleAction(object sender, MouseEventArgs e) 
{ 
    this.lastAction = DateTime.Now; 
    this.label4.Text = this.lastAction.ToLongTimeString(); 
} 

UPDATE

使用喬接受的解決方案,我總結了以下類。感謝所有參與了的人。

class classIdleTime 
{ 
    [DllImport("user32.dll")] 
    static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); 

    internal struct LASTINPUTINFO 
    { 
     public Int32 cbSize; 
     public Int32 dwTime; 
    } 

    public int getIdleTime() 
    { 
     int systemUptime = Environment.TickCount; 
     int LastInputTicks = 0; 
     int IdleTicks = 0; 

     LASTINPUTINFO LastInputInfo = new LASTINPUTINFO(); 
     LastInputInfo.cbSize = (Int32)Marshal.SizeOf(LastInputInfo); 
     LastInputInfo.dwTime = 0; 

     if (GetLastInputInfo(ref LastInputInfo)) 
     { 
      LastInputTicks = (int)LastInputInfo.dwTime; 
      IdleTicks = systemUptime - LastInputTicks; 
     } 
     Int32 seconds = IdleTicks/1000; 
     return seconds; 
    } 

用法

idleTimeObject = new classIdleTime(); 
Int32 seconds = idleTimeObject.getIdleTime(); 
this.isIdle = (seconds > secondsBeforeIdle); 

回答

3

如果用戶空閒,您可以問Windows。你將不得不使用P/Invoke,但它會是最簡單的。查看GetLastInputInfo功能。

+0

實現並像夢一樣工作。我在原文中添加了我放在一起的類的代碼。 – Dutchie432 2010-08-26 12:55:05

2

這看起來像一個WinForms應用程序 - 爲什麼不add an IMessageFilter?您將看到每個通過事件循環傳遞的Windows消息,無論它是針對瀏覽器還是其他地方。

+0

偉大的建議,但因爲這將是一個公共終端,性能是關鍵。在您與我聯繫的頁面上,有一個警告:「嚮應用程序的消息泵添加消息過濾器可能會降低性能」,所以我長期決定反對它。 Upvote爲偉大的建議和努力。 – Dutchie432 2010-08-26 12:54:31

+0

@ Dutchie432當然,嚮應用程序添加任何代碼都會降低性能。添加消息過濾器和檢查鼠標消息的效果與處理鼠標事件相同。與性能考慮一樣,在決定之前進行配置文件測量。 – 2010-08-26 14:10:37

+0

除了在你的鏈接上的謹慎,接受的解決方案似乎比重新發明輪子更容易。它只需要幾行代碼就完成了。如果我需要做某些尚未考慮到其他地方的事情,我絕對會嘗試您的解決方案。再次感謝。 – Dutchie432 2010-08-26 16:37:02