C#如何使用WM_GETTEXT / GetWindowText API
我想获得应用程序的控件/句柄的内容..
这是实验代码..
Process[] processes = Process.GetProcessesByName("Notepad"); foreach (Process p in processes) { StringBuilder sb = new StringBuilder(); IntPtr pFoundWindow = p.MainWindowHandle; List 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 }
任何的想法? 我已经阅读了一些API方法,如GetWindowText或WM_GETTEXT,但我不知道如何使用它或将其应用于我的代码..我需要一个教程或示例代码…
提前致谢 : )
public class GetTextTestClass{ [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 string GetControlText(IntPtr hWnd){ // Get the size of the string required to hold the window title (including trailing null.) Int32 titleSize = SendMessage((int)hWnd, WM_GETTEXTLENGTH, 0, 0).ToInt32(); // If titleSize is 0, there is no title so return an empty string (or null) if (titleSize == 0) return String.Empty; StringBuilder title = new StringBuilder(titleSize + 1); SendMessage(hWnd, (int)WM_GETTEXT, title.Capacity, title); return title.ToString(); } }
GetWindowText不会向您提供来自其他应用程序的编辑窗口的内容 – 它只支持跨进程的默认管理文本 [如标签的标题]以防止挂起…您必须发送WM_GETTEXT。
您需要使用StringBuilder版本的SendMessage:
[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);
请查看https://pinvoke.net/default.aspx/user32/GetWindowText.html以及MSDN上的文档。 下面是一个如何使用GetWindowText方法的简短代码示例。
上述就是C#学习教程:C#如何使用WM_GETTEXT / GetWindowText API分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/999879.html