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

C#控制台程序实现第三方程序按键模拟方案咨询

在C#控制台应用中实现第三方程序的按键自动化

类似Python pynput的C#工具

推荐使用InputSimulator,这是一个轻量级开源库,专门用于模拟键盘和鼠标输入,用法和pynput一样直观,完美适配控制台应用。你可以通过NuGet安装它:

  • 包管理器控制台执行:Install-Package InputSimulator
  • 或在Visual Studio的NuGet包管理器中搜索"InputSimulator"完成安装。

整合后的完整代码

以下是修改后的unPirs方法,加入了按键模拟逻辑,同时优化了路径拼接和窗口激活处理:

using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using WindowsInput;

class Program
{
    static void unPirs()
    {
        string homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        string unpackedPath = Path.Combine(homePath, "XBLA_Unpacked");
        string wxPirsPath = Path.Combine(homePath, "wxPirs.exe");

        var files = GetAllFiles(unpackedPath);
        var inputSimulator = new InputSimulator();

        foreach (var file in files)
        {
            Console.WriteLine(file);
            var process = Process.Start(wxPirsPath, $"\"{file}\"");
            
            // 等待程序加载完成(可根据实际情况调整时长)
            Thread.Sleep(7500);
            
            // 等待程序进入空闲状态并激活窗口,确保输入发送到目标程序
            process.WaitForInputIdle();
            SetForegroundWindow(process.MainWindowHandle);

            // 模拟按键序列:Alt+F → 向下箭头 → 回车 ×2
            inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.MENU, VirtualKeyCode.F);
            inputSimulator.Keyboard.KeyPress(VirtualKeyCode.DOWN);
            inputSimulator.Keyboard.KeyPress(VirtualKeyCode.RETURN);
            inputSimulator.Keyboard.KeyPress(VirtualKeyCode.RETURN);

            process.WaitForExit();
        }
    }

    // 获取指定目录下所有文件(递归遍历)
    static string[] GetAllFiles(string path)
    {
        return Directory.GetFiles(path, "*", SearchOption.AllDirectories);
    }

    // 导入Windows API用于激活目标窗口
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);
}

关键说明

  1. 窗口激活:调用SetForegroundWindow确保输入发送到wxPirs.exe的窗口,避免输入到其他前台程序,这一步需要导入user32.dll的对应方法。
  2. 按键模拟细节:
    • ModifiedKeyStroke用于模拟组合键(VirtualKeyCode.MENU对应Alt键)
    • KeyPress用于模拟单次按键操作
  3. 优化等待逻辑:如果wxPirs.exe的加载时长不稳定,可以替换固定的Thread.Sleep为循环检查窗口状态,直到窗口创建完成:
    while (process.MainWindowHandle == IntPtr.Zero)
    {
        Thread.Sleep(100);
        process.Refresh();
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:42:24