C#通过窗口句柄获取textbox
时间: 2023-10-19 18:14:54 浏览: 147
可以通过以下代码通过窗口句柄获取指定窗口中的TextBox控件:
```csharp
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, StringBuilder lParam);
private const int WM_GETTEXT = 0x000D;
public static string GetTextBoxText(IntPtr parentHandle, string textBoxClassName, string textBoxTitle)
{
IntPtr textBoxHandle = FindWindowEx(parentHandle, IntPtr.Zero, textBoxClassName, textBoxTitle);
if (textBoxHandle == IntPtr.Zero)
{
return string.Empty;
}
StringBuilder sb = new StringBuilder(256);
SendMessage(textBoxHandle, WM_GETTEXT, (IntPtr)sb.Capacity, sb);
return sb.ToString();
}
```
调用示例:
```csharp
IntPtr parentHandle = // 父窗口句柄
string textBoxClassName = "TextBox"; // TextBox控件的类名
string textBoxTitle = "TextBox1"; // TextBox控件的标题
string text = GetTextBoxText(parentHandle, textBoxClassName, textBoxTitle);
```
阅读全文