powershell - 将 key 发送到 PowerShell 中打开的窗口

标签 powershell

我制作了一个打开某个程序的程序,然后在 x 时间后 Ctrl+C 它。

我现在正在使用这个 [System.Windows.Forms.SendKeys]::SendWait("^{c}")。 这会针对特定窗口还是随机将其发送到当前窗口?

如何将其更改为特定窗口?

这是我的代码:

Write-Host "Safe Botting V0.1"
Write-Host "Initializing..."
Start-Sleep -s 3
Write-Host "Program started successfully with no errors."

While($true)
{
    Write-Host "Starting bot..."
    Start-Sleep -s 3
    Start-Process -FilePath E:\Documents\bot.exe
    Write-Host "Bot started successfully"
    $rnd = Get-Random -Minimum 1800 -Maximum 10800
    Write-Host "The bot will run for:"
    Write-Host $rnd
    Start-Sleep -s $rnd
    Write-Host "Bot will now stop!"
    [System.Windows.Forms.SendKeys]::SendWait("^{c}") 
    Write-Host "Bot terminated"
    Write-Host "Starting cooldown time"
    $rnb = Get-Random -Minimum 14400 -Maximum 28800
    Write-Host "The bot will cooldown for"
    Write-host $rnb
    Start-Sleep -s $rnb
    Write-Host "Cooldown Finished, Restarting"
    Start-Sleep -s 5
}

最佳答案

如果您有进程 ID,您可以向进程发送 CTRL_C_EVENT 信号。在您的情况下,您可以从 Start-Process 获取它(如果您不知道如何获取进程 ID,请阅读文档)。也可以从窗口句柄获取进程 ID:

Find process id by window's handle

发送信号非常重要,但感谢@Nemo1024、@KindDragon 和 Stack Overflow,它已经解决了:

Can I send a ctrl-C (SIGINT) to an application on Windows?

不幸的是,使用我能找到的最佳方法也终止了调用 PowerShell 进程,我能想到的唯一解决方法是从我启动的新 PowerShell 实例发送信号。

在 PowerShell 中它看起来像这样:

# be sure to set $ProcessID properly. Sending CTRL_C_EVENT signal can disrupt or terminate a process
$ProcessID = 1234
$encodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes("Add-Type -Names 'w' -Name 'k' -M '[DllImport(""kernel32.dll"")]public static extern bool FreeConsole();[DllImport(""kernel32.dll"")]public static extern bool AttachConsole(uint p);[DllImport(""kernel32.dll"")]public static extern bool SetConsoleCtrlHandler(uint h, bool a);[DllImport(""kernel32.dll"")]public static extern bool GenerateConsoleCtrlEvent(uint e, uint p);public static void SendCtrlC(uint p){FreeConsole();AttachConsole(p);GenerateConsoleCtrlEvent(0, 0);}';[w.k]::SendCtrlC($ProcessID)"))
start-process powershell.exe -argument "-nologo -noprofile -executionpolicy bypass -EncodedCommand $encodedCommand"

是的,我知道这很丑。

关于powershell - 将 key 发送到 PowerShell 中打开的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39486647/

相关文章:

Powershell:将唯一字符串转换为唯一整数

powershell - 将Format-Hex PowerShell表转换为原始十六进制转储

powershell - WinSCP ExecuteCommand报告IsSuccess = true,但ExitCode = 1

powershell - 为什么 'invoke-history' 卡在 powershell 中?

带有 2 对引号的 Powershell cmd/c 适用于 Win 7,但不适用于 Win 10

java - 如何在非英语系统中初始化 Gradle 项目?

Powershell:展开存档:无法验证参数 'Path' 上的参数

windows - PowerShell:使用 Invoke-Command 执行命令时出错?

powershell - 刷新 PowerShell DSC 资源

json - JSON 或 XML 形式的 Powershell 系统信息