以Powershell形式禁用Alt + F4

时间:2014-03-21 00:10:12

标签: forms powershell keyboard shortcut

我已经编写了一个PowerShell脚本,该脚本使用System.Windows.Forms显示表单。我已经禁用了控制盒以及通过鼠标关闭此表单的所有其他方法。但我无法通过按 Alt + F4 来找到阻止表单关闭的方法。

即。代码段如下所示:

[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()

查看MSDN,有关于在VB,C#等中覆盖FormClosing事件处理程序的文章。但我不确定如何在Powershell中实现类似的逻辑(如果可能的话)。

1 个答案:

答案 0 :(得分:1)

将表格keypreview设为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;
        }
    }
}