You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

InputSimulator Keyboard.TextEntry失效:记事本无法写入虚拟文本

问题原因及解决方案

核心原因

  1. 窗口未完成初始化且未激活:Process.Start()仅启动记事本进程,但窗口的创建、渲染需要时间,此时记事本窗口既没有完全就绪,也没有成为前台激活窗口。InputSimulator的键盘输入是发送给当前系统聚焦的前台窗口,直接调用输入自然无效。
  2. 移动鼠标的触发逻辑:手动移动鼠标时,若鼠标指针落在记事本窗口区域内,系统会自动将焦点切换到记事本,此时输入就能被正确接收。

修复方案

需要确保两个条件:

  • 等待记事本窗口完全创建完成
  • 将记事本窗口激活为前台窗口

修改后的代码如下:

using System;
using System.Diagnostics;
using System.Threading;
using WindowsInput;
using WindowsInput.Native;
using System.Runtime.InteropServices;

class Program
{
    // 导入Windows API用于激活窗口
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    const int SW_RESTORE = 9;

    static void Main()
    {
        try
        {
            Process notepadProcess = new Process();
            notepadProcess.StartInfo.FileName = "notepad.exe";
            notepadProcess.Start();

            // 等待窗口句柄生成,最多等待5秒
            int waitCount = 0;
            while (notepadProcess.MainWindowHandle == IntPtr.Zero && waitCount < 50)
            {
                Thread.Sleep(100);
                notepadProcess.Refresh(); // 更新进程的窗口信息
                waitCount++;
            }

            if (notepadProcess.MainWindowHandle != IntPtr.Zero)
            {
                // 激活记事本窗口到前台
                ShowWindow(notepadProcess.MainWindowHandle, SW_RESTORE);
                SetForegroundWindow(notepadProcess.MainWindowHandle);
                
                // 给窗口一点激活后的响应时间
                Thread.Sleep(200);

                InputSimulator simulator = new InputSimulator();
                simulator.Keyboard.TextEntry("This is a message that will be written to Notepad");
            }
            else
            {
                Console.WriteLine("记事本窗口初始化超时");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("启动记事本出错: " + ex.Message);
        }
    }
}

关键细节说明

  • Process.Refresh():必须调用这个方法来更新进程的MainWindowHandle,因为进程启动后窗口句柄不会自动同步到Process对象。
  • SetForegroundWindow:通过Windows API强制将记事本窗口设为前台激活窗口,确保输入被发送到正确的目标。
  • 等待时间:添加短时间的Sleep是为了给窗口激活后的系统响应留出时间,避免输入过早发送。

内容的提问来源于stack exchange,提问作者Oscar RoAh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:33:13