2011-10-12 1677 views
13

我想获得一个应用程序的控制/手柄的内容..C#如何使用WM_GETTEXT/GetWindowText函数API

这里的实验代码..

Process[] processes = Process.GetProcessesByName("Notepad"); 
     foreach (Process p in processes) 
     { 
      StringBuilder sb = new StringBuilder(); 
      IntPtr pFoundWindow = p.MainWindowHandle; 
      List <IntPtr> s = GetChildWindows(pFoundWindow); 
      // function that returns a 
      //list of handle from child component on a given application. 

      foreach (IntPtr test in s) 
      { 
       // Now I want something here that will return/show 
       the text on the notepad.. 


      } 


      GetWindowText(pFoundWindow, sb,256); 
      MessageBox.Show(sb.ToString()); // this shows the title.. no problem with that 

     } 

什么想法? 我提前阅读像GetWindowText函数或WM_GETTEXT一些API方法,但我不知道如何使用它或把它在我的代码.. 我需要一个教程或示例代码...

感谢:)

回答

15
public class Class1 
     { 
     [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] 
     public static extern int RegisterWindowMessage(string lpString); 

     [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = System.Runtime.InteropServices.CharSet.Auto)] // 
     public static extern bool SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam); 
      [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] 
     public static extern IntPtr SendMessage(int hWnd, int Msg, int wparam, 
     int lparam); 

     const int WM_GETTEXT = 0x000D; 
     const int WM_GETTEXTLENGTH = 0x000E; 

     public void RegisterControlforMessages() 
     { 
      RegisterWindowMessage("WM_GETTEXT"); 
     } 
     public string GetControlText(IntPtr hWnd) 
     { 

      StringBuilder title = new StringBuilder(); 

      // Get the size of the string required to hold the window title. 
      Int32 size = SendMessage((int)hWnd, WM_GETTEXTLENGTH, 0, 0).ToInt32(); 

      // If the return is 0, there is no title. 
      if (size > 0) 
      { 
     title = new StringBuilder(size + 1); 

     SendMessage(hWnd,(int)WM_GETTEXT, title.Capacity, title); 


      } 
      return title.ToString(); 
     } 
    } 

对不起代码格式化花了很长时间,仍然得到使用它。

+0

哇,它的工作原理上的记事本。 。但它不适用于其他应用程序,但我想问题是,我需要控制子组件..也许我需要研究更多;) – user848682

+1

是的,如果你以后的控件是一个子控件在一个给定的窗口,那么你需要迭代地获取控件,并在标题匹配所需的时候停止。 –

+0

uhmm,samra如果你有空闲时间,你能给我一个方法来接受一个句柄并返回一个子控件列表吗?提前致谢。我从网上获得的方法有问题.. – user848682

3

GetWindowText不会为您提供其他应用程序的编辑窗口的内容 - it only supports default-managed text [像标签的标题]跨过程以防止挂起...您必须发送WM_GETTEXT。

你需要使用SendMessage函数的一个StringBuilder版本:

[DllImport("user32.dll", CharSet = CharSet.Auto)] 
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [Out] StringBuilder lParam); 

const int WM_GETTEXT = 0xD; 
StringBuilder sb = new StringBuilder(65535); 
// needs to be big enough for the whole text 
SendMessage(hWnd_of_Notepad_Editor, WM_GETTEXT, sb.Length, sb);