Skip to content

Instantly share code, notes, and snippets.

@CannoHarito
Created November 17, 2022 06:09
Show Gist options
  • Save CannoHarito/c273f57668625e6f70abac304535ccfd to your computer and use it in GitHub Desktop.
Save CannoHarito/c273f57668625e6f70abac304535ccfd to your computer and use it in GitHub Desktop.
PowershellからFormを描画した際にコンソールへのCtrl+Cで終了したい。Powershellで[System.Console]::Add_CancelKeyPress({})をすると異常終了する。C#で書けば動いた
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