Powershell模拟键盘

标签 powershell powershell-4.0 powershell-ise

我在 Powershell 中使用 sendkeys 时遇到问题。我正在尝试制作一个脚本,将按键:shift、w、a、s、d 发送到游戏。我正在尝试的代码是:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait(+{w}{a}{s}{d});

但是当我使用它时它只会发送“Wasd”。它不会改变 Action ,我可以看到这已在游戏控制台中发送。

有没有办法可以模拟按键?

可以使用鼠标左键完成此操作:

    $signature=@' 
          [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
          public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
    '@ 

    $SendMouseClick = Add-Type -memberDefinition $signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru

$SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);

键盘有类似的东西吗?

最佳答案

sendKeys 方法似乎一次不支持多个字符,因此您需要自动将许多键发送到 sendkeys 方法。

经过一番思考,我得出了这样的结论。

Add-Type -AssemblyName System.Windows.Forms    
timeout 3
'WASD'.ToCharArray() | ForEach-Object {[System.Windows.Forms.SendKeys]::SendWait($_)}

结果如下:

Send keys with PowerShell, awesome![1]

现在,逐行了解正在发生的事情:

  • 像之前一样添加类型。
  • 接下来,出现三秒超时消息,我快速双击并打开记事本。
  • 最后,我创建一个包含字符“WASD”的字符串,然后调用系统字符串 .ToCharArray() 方法,该方法将字符串转换为字符数组。现在我使用 W、A、S、D,而不是 WASD。

对于每个对象(每个字母,W、A、S 和 D),我都调用 SendWait() 静态方法。在 ForEach 脚本 block 中,$_ 符号用于引用当前对象。

这是我能想到的最简洁、最容易理解的方法。

关于Powershell模拟键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34254385/

相关文章:

performance - 提高检查文件定界符的性能

powershell - 如何在另一个 session (Powershell ISE 选项卡)中使用一个变量?

Powershell ISE 中出现 Python 错误

windows - 使用 Powershell 停止/启动 Microsoft Windows 集群角色

function - 调用函数时出错

powershell - 为远程服务器执行 get-acl 时出现问题

powershell - Key Vault 返回 401 和访问 token (MSI PowerShell Function App)

powershell - 将值通过管道传送到 New-Item 以在 PowerShell 中创建目录

PowerShell - 显示父对象和子对象的属性

forms - Windows 窗体在 Powershell 和 Powershell ISE 中看起来不同。为什么?