在PowerShell中输入模拟(Win + A)

问题描述 投票:0回答:1

我有一个Python脚本可以使用输入模拟来启用/禁用

Airplane mode
,效果很好:

  • Win + A:打开操作中心
  • 右箭头(两次):导航至飞机切换
  • 空格:按确定
  • Win + A:离开行动中心
import pyautogui
pyautogui.hotkey('win', 'a')
pyautogui.press('right', presses=2)
pyautogui.press('space')
pyautogui.hotkey('win', 'a')

我尝试使用 PowerShell 来做到这一点:

$shell = New-Object -ComObject WScript.Shell
$shell.SendKeys("^{ESC}")
$shell.SendKeys("{RIGHT}")
$shell.SendKeys("{RIGHT}")
$shell.SendKeys(" ")
$shell.SendKeys("^{ESC}")

不过,好像没啥作用。
因为

$shell.SendKeys("^{ESC}")
打开
Start Menu
,不是我想要的
Action Center

正确的命令是什么?

Win + A

ap

windows powershell input sendkeys wscript.shell
1个回答
0
投票

GUI 脚本,即交互式用户输入的编程模拟,始终是脆弱(可能会失败),因此最好寻找其他解决方案:

  • 这个答案显示了用于切换飞行模式的 C# 代码,您可以通过

    Add-Type

    在 PowerShell 中进行调整和使用
  • 这个 SU 答案展示了一种

    wmic.exe
    方法,通过启用或禁用 Wi-Fi 网络适配器来模拟打开或关闭飞行模式,但请注意,它需要 elevation(以管理员身份运行);由于语法原因,PowerShell 中需要稍作调整:

    # REQUIRES ELEVATION
    # Disables the Wi-Fi adapte; to enable, use "enable"
    wmic.exe path win32_networkadapter where --% NetConnectionID="Wi-fI" call disable
    

如果您无法避免 GUI 脚本解决方案:

  • 上面链接的 SU 答案提供了一种 GUI 脚本方法,不需要需要 WinKey(Windows 键)按键;适应PowerShell(未经测试):

     # Start the Settings app and open the relevant page.
     Start-Process ms-settings:network-airplanemode
     # Give the app some time to open.
     Start-Sleep -Milliseconds 1000 
     # Send a <space> char. to toggle, then Alt+F4 to close the window.
     (New-Object -ComObject WScript.Shell).SendKeys(" %{F4}")
    
    • 缺点是这种方法在视觉上更具破坏性并且比您尝试做的更慢。
  • 否则:

    • 如果您可以假设已安装 Python,请通过 Python CLI 调用您的 Python 代码:

      python -c 'import pyautogui; pyautogui.hotkey('win', 'a'); ...'

    • 否则或替代地,编译一个使用 P/Invoke 的帮助程序类以允许发送基于 WinKey 的键和弦:请参阅这个答案

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.