2016-09-14 50 views
0

我做了一個程序,打開某個程序,然後Ctrl + C它在x時間後。發送密鑰到PowerShell中打開的窗口

我現在使用這個[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 
} 
+3

你究竟想在這裏實現什麼?這聽起來像[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem);我懷疑問題有一個更清晰的解決方案,例如使用'Taskkill'命令。另外,請在你的帖子中包含你的實際代碼。 –

+0

正在嘗試運行的程序必須由Ctrl + C停止,否則下次將無法加載。 –

+0

那麼['Stop-Process'](https://technet.microsoft.com/en-us/library/ee177004.aspx)命令怎麼樣? –

回答

0

您可以在CTRL_C_EVENT信號發送到過程中如果有進程ID。在你的情況下,你可以從Start-Process獲得(如果你不知道如何獲得進程ID,請閱讀文檔)。這也可以從一個窗口句柄得到進程ID:

Find process id by window's handle

發送的信號是不平凡的,但感謝@ Nemo1024,@KindDragon和堆棧溢出,它已經制定了:

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" 

是的,我知道這是非常難看。