代码之家  ›  专栏  ›  技术社区  ›  Dinesh

使用C从任何窗口捕获突出显示的文本#

  •  5
  • Dinesh  · 技术社区  · 16 年前

    我试过两种方法。

    所以我换了第二种方法,发送消息的方法。

    请参见此示例代码

     [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或VisualStudioIDE)捕获,它不会返回文本。

    1 回复  |  直到 16 年前
        1
  •  3
  •   Dean Harding    16 年前

    这是不可能的 一般来说 为了能够获得“任意”所选文本的值,因为程序可以以任何他们认为合适的方式重新实现自己版本的Win32控件,并且您的程序不可能期望与所有这些控件一起工作。

    但是,您可以使用 UI Automation 大多数 第三方控件(至少,所有好的控件(比如visualstudio和Firefox)都可能与UI自动化api一起工作,因为这是对可访问性的要求)