Is there a way to catch ctrl-c and ask the user to confirm?

守給你的承諾、 提交于 2019-12-17 20:15:46

问题


Powershell scripts can easily be terminated by the user pressing ctrl-c. Is there a way for a Powershell script to catch ctrl-c and ask the user to confirm whether he really wanted to terminate the script?


回答1:


Checkout this post on the MSDN forums.

[console]::TreatControlCAsInput = $true
while ($true)
{
    write-host "Processing..."
    if ([console]::KeyAvailable)
    {
        $key = [system.console]::readkey($true)
        if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C"))
        {
            Add-Type -AssemblyName System.Windows.Forms
            if ([System.Windows.Forms.MessageBox]::Show("Are you sure you want to exit?", "Exit Script?", [System.Windows.Forms.MessageBoxButtons]::YesNo) -eq "Yes")
            {
                "Terminating..."
                break
            }
        }
    }
}

If you don't want to use a GUI MessageBox for the confirmation, you can use Read-Host instead, or $Host.UI.RawUI.ReadKey() as David showed in his answer.




回答2:


while ($true)
{
    Write-Host "Do this, do that..."

    if ($Host.UI.RawUI.KeyAvailable -and (3 -eq [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))
    {
            Write-Host "You pressed CTRL-C. Do you want to continue doing this and that?" 
            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
            if ($key.Character -eq "N") { break; }
    }
}


来源:https://stackoverflow.com/questions/10733718/is-there-a-way-to-catch-ctrl-c-and-ask-the-user-to-confirm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!