2010-05-04 49 views
5

如何讀取使用C#的任何窗口中高亮顯示/選擇高亮顯示文本從任何窗口中的文本。捕獲使用C#

我試圖2點的方法。

  1. 每當用戶選擇一些東西時發送「^ c」。但在這種情況下,我的剪貼板充斥着大量不必要的數據。有時它也複製密碼。

所以我換我的方法來第二方法,發送消息的方法。

看到此示例代碼

[DllImport("user32.dll")] 
    static extern int GetFocus(); 

    [DllImport("user32.dll")] 
    static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); 

    [DllImport("kernel32.dll")] 
    static extern uint GetCurrentThreadId(); 

    [DllImport("user32.dll")] 
    static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);  

    [DllImport("user32.dll") ] 
    static extern int GetForegroundWindow(); 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] 
    static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam);  

    // second overload of SendMessage 

    [DllImport("user32.dll")] 
    private static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam); 

    const int WM_SETTEXT = 12; 
    const int WM_GETTEXT = 13;  

private string PerformCopy() 
    { 
     try 
     { 
      //Wait 5 seconds to give us a chance to give focus to some edit window, 
      //notepad for example 
      System.Threading.Thread.Sleep(5000); 
      StringBuilder builder = new StringBuilder(500); 

      int foregroundWindowHandle = GetForegroundWindow(); 
      uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0); 
      uint currentThreadId = GetCurrentThreadId(); 

      //AttachTrheadInput is needed so we can get the handle of a focused window in another app 
      AttachThreadInput(remoteThreadId, currentThreadId, true); 
      //Get the handle of a focused window 
      int focused = GetFocus(); 
      //Now detach since we got the focused handle 
      AttachThreadInput(remoteThreadId, currentThreadId, false); 

      //Get the text from the active window into the stringbuilder 
      SendMessage(focused, WM_GETTEXT, builder.Capacity, builder); 

      return builder.ToString(); 
     } 
     catch (System.Exception oException) 
     { 
      throw oException; 
     } 
    } 

這個代碼在記事本中工作正常。但是,如果我嘗試從另一個應用程序(如Mozilla Firefox或Visual Studio IDE)捕獲它,則不會返回文本。

任何人可以幫我,我哪裏做錯了嗎?首先,我選擇了正確的方法?

回答

3

這是因爲Firefox和Visual Studio中都沒有使用內置的Win32用於顯示/編輯文本的控制。

這是不可能的一般能夠獲得「任何」選定文本的值,因爲程序可以重新實現他們自己認爲合適的任何方式的Win32控件的版本,以及你的程序不可能期望與它們一起工作。

但是,您可以使用UI Automation的API,這將讓你與大多數第三方控件交互(至少,所有的好的 - 如Visual Studio和Firefox - 很可能會與UI工作自動化的API,因爲它的可訪問性

+0

Firefox沒有實現UI自動化的要求),我曾試圖3.0版本,並沒有工作,希望它將來可能會支持。 – 2010-05-04 07:50:55

+0

我們可以做些什麼來改善我的第一種方法。這是非常好的工作,除了不必要的拷貝........ – Dinesh 2010-05-04 08:52:43