2010-05-04 1 views
5

C#을 사용하여 임의의 창에서 강조 표시된/선택한 텍스트를 읽는 방법.C#을 사용하여 임의의 창에서 강조된 텍스트 캡쳐

나는 두 가지 접근법을 시도했다.

  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

파이어 폭스와 비주얼 스튜디오는 모두 텍스트를 표시/편집하기 위해 내장 된 Win32 컨트롤을 사용하지 않기 때문입니다.

일반적으로에 때문에 프로그램이 Win32에서의 자신의 버전을 다시 구현할 수 있다는 사실, "어떤"선택한 텍스트의 값을 얻을 수있을 수 없습니다 그들이 맞는 볼 어떤 방법을 제어하고, 당신의 프로그램은 아마도 그것들 모두로 작업 할 것으로 기대할 수 없다. 같은 Visual Studio 및 Firefox와 같은 - - UI를 작동 전망이다

그러나, 당신은 당신이 적어도, 모든 좋은 것들합니다 (대부분의 타사 컨트롤와 상호 작용할 수 있도록 할 UI Automation API를 사용할 수 있습니다 자동화 API는 접근성 요구 사항이므로

+0

Firefox는 UI 자동화를 구현하지 않습니다. 버전 3.0을 사용해 보았지만 작동하지 않았으므로 향후 지원 될 수 있기를 바랍니다. –

+0

첫 번째 방법을 개선하기 위해 뭔가를 할 수 있습니까? 그것은 불필요한 복사를 제외하고는 매우 효과적입니다 ........ – Dinesh