使用UI Automation库改写代码,以确保窗口处于活动状态并将焦点放在文本字段中,然后使用SendKeys.Send方法发送按键输入。
示例代码如下:
using System.Windows.Automation;
using System.Windows.Forms;
// 获取文本字段窗口句柄
IntPtr hwnd = FindWindow(null, "文本字段窗口标题");
// 激活窗口并将焦点放在文本字段上
SetForegroundWindow(hwnd);
AutomationElement textElement = AutomationElement.FromHandle(hwnd);
AutomationElementCollection textFields = textElement.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
if (textFields.Count > 0)
{
AutomationElement textField = textFields[0];
textField.SetFocus();
}
// 发送按键输入
SendKeys.Send("输入的文本");
请注意,此代码需要添加以下命名空间:
using System.Runtime.InteropServices;
using System.Windows;
using System.Diagnostics;
此外,您还需要确保已正确安装UI Automation库。