Created
November 17, 2022 06:09
-
-
Save CannoHarito/c273f57668625e6f70abac304535ccfd to your computer and use it in GitHub Desktop.
PowershellからFormを描画した際にコンソールへのCtrl+Cで終了したい。Powershellで[System.Console]::Add_CancelKeyPress({})をすると異常終了する。C#で書けば動いた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type -AssemblyName System.Windows.Forms | |
$CK = Add-Type -ReferencedAssemblies 'System.Windows.Forms' -PassThru -TypeDefinition @" | |
using System; | |
using System.Windows.Forms; | |
public class CancelKey{ | |
public static void Main() { | |
Console.CancelKeyPress += (sender, e) => { | |
// trueにすると、プログラムを終了させない | |
e.Cancel = true; | |
Console.WriteLine("CTRL+C が押されました"); | |
Application.Exit(); | |
}; | |
Console.WriteLine("CancelKeyPressイベントをセットしました"); | |
} | |
} | |
"@ | |
$CK::Main(); | |
try { | |
Write-Host "start" | |
$form = New-Object Windows.Forms.Form | |
[System.Windows.Forms.Application]::Run($form); | |
Write-Host "end"; | |
} | |
catch { | |
Write-Host "An error occurred:" | |
Write-Host $_ | |
} | |
finally { | |
Pause | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment