问题
I've written a powershell script which displays a form using System.Windows.Forms
. I've already disabled the control box and all other ways that this form can be closed via the mouse. But I can't find a way of preventing the form closing by pressing Alt+F4.
i.e. Code snippet looks like this:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Restart Required"
$objForm.Size = New-Object System.Drawing.Size(400,300)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Topmost = $True
$objForm.MinimizeBox = $false
$objForm.MaximizeBox = $false
$objForm.FormBorderStyle = "Fixed3d"
$objForm.ControlBox = $false
$objForm.ShowInTaskbar = $false
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
Looking at MSDN, there are articles about overriding the FormClosing
eventhandler in VB, C#, etc and . But I'm not sure how to implement similar logic into Powershell (if it's at all possible).
回答1:
Set forms keypreview to true
$form1_KeyDown=[System.Windows.Forms.KeyEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.KeyEventArgs]
if ($_.Alt -eq $true -and $_.KeyCode -eq 'F4') {
$script:altF4Pressed = $true;
}
}
$form1_FormClosing=[System.Windows.Forms.FormClosingEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.FormClosingEventArgs]
if ($script:altF4Pressed)
{
if ($_.CloseReason -eq 'UserClosing') {
$_.Cancel = $true
$script:altF4Pressed = $false;
}
}
}
来源:https://stackoverflow.com/questions/22547726/disabling-altf4-in-a-powershell-form