2013-09-16 11 views
2

我有一些代碼將採取活動窗口的屏幕截圖。每當活動窗口發生變化時,我的老闆都希望我必須運行的代碼。例如:如何讓我的C#程序在每次當前活動窗口更改時執行一些操作?

  • 打開計算器 - 截圖取
  • 焦點切換到記事本 - 截圖取
  • 焦點切換到瀏覽器 - 截圖取

是來到了第一個想到我頭腦是將當前活動窗口句柄的句柄存儲在變量中,然後不斷檢查當前活動窗口的句柄是否與變量中的值相同。是否有一種方法可以訂閱我的計算機中發生的事件,並在活動窗口更改時告訴我?

+0

我希望你的老闆不打算使用此代碼來監視他的員工!如果是這樣,我很高興我不在那裏工作! :P此外,我認爲已經有商業應用可以做到這一點。 –

+0

我正在網絡安全研究小組工作。從我可以告訴的這實際上將用於研究惡意軟件。至於已經有商業應用可以做到這一點 - 我會想象有。我自己這樣做的原因是,一旦我完成了這個工作,它將被添加到我的老闆正在爲自己設計的一個程序中。 – Clint

回答

4

請看看的Win32 API可用以下方法,

SetWinEventHook() 
    UnhookWinEvent() 

這將幫助您檢測窗口變化事件。

示例代碼

using System; 
using System.Windows; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 

class NameChangeTracker 
{ 
    delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, 
     IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime); 

    [DllImport("user32.dll")] 
    static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr 
     hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, 
     uint idThread, uint dwFlags); 

    [DllImport("user32.dll")] 
    static extern bool UnhookWinEvent(IntPtr hWinEventHook); 

    const uint EVENT_OBJECT_NAMECHANGE = 0x800C; 
    const uint WINEVENT_OUTOFCONTEXT = 0; 

    // Need to ensure delegate is not collected while we're using it, 
    // storing it in a class field is simplest way to do this. 
    static WinEventDelegate procDelegate = new WinEventDelegate(WinEventProc); 

    public static void Main() 
    { 
     // Listen for name change changes across all processes/threads on current desktop... 
     IntPtr hhook = SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, IntPtr.Zero, 
       procDelegate, 0, 0, WINEVENT_OUTOFCONTEXT); 

     // MessageBox provides the necessary mesage loop that SetWinEventHook requires. 
     // In real-world code, use a regular message loop (GetMessage/TranslateMessage/ 
     // DispatchMessage etc or equivalent.) 
     MessageBox.Show("Tracking name changes on HWNDs, close message box to exit."); 

     UnhookWinEvent(hhook); 
    } 

    static void WinEventProc(IntPtr hWinEventHook, uint eventType, 
     IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) 
    { 
     // filter out non-HWND namechanges... (eg. items within a listbox) 
     if(idObject != 0 || idChild != 0) 
     { 
      return; 
     } 
     Console.WriteLine("Text of hwnd changed {0:x8}", hwnd.ToInt32()); 
    } 
} 
+0

非常感謝你!我認爲這正是我需要的。 – Clint

+0

@Clint簽出http://stackoverflow.com/help/someone-answers。 – Tshepang

相關問題