Disabling Alt+F4 in a Powershell form

落爺英雄遲暮 提交于 2021-02-08 11:57:54

问题


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

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