Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

How to disable Alt-F4 in a powershell form?

$
0
0

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.   Unfortunately there isn't much information in the way of Powershell and overriding the FormClosing event. 

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 = "This is a form"
    $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_KeyDown=[System.Windows.Forms.KeyEventHandler]{
        #Event Argument: $_ = [System.Windows.Forms.KeyEventArgs]

        if ($_.Alt -eq $true -and $_.KeyCode -eq 'F4') {
            $script:altF4Pressed = $true;           
        }
    }

    $objform_FormClosing=[System.Windows.Forms.FormClosingEventHandler]{
        #Event Argument: $_ = [System.Windows.Forms.FormClosingEventArgs]

        if ($script:altF4Pressed)
        {
            if ($_.CloseReason -eq 'UserClosing') {
                $_.Cancel = $true
                $script:altF4Pressed = $false;
            }
        }
    }

    # Add Ok button
    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Size(50,90)
    $OKButton.Size = New-Object System.Drawing.Size(100,23)
    $OKButton.Text = "I am a button"
    $OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
    $objForm.Controls.Add($OKButton)


    $objForm.Add_Shown({$objForm.Activate()})
    [void] $objForm.ShowDialog()

   Any help greatly appreciated.  Thanks.

Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>