在Powershell中捕获Windows窗体关闭事件

时间:2019-07-12 11:43:23

标签: winforms powershell

我有一个Windows窗体。当我单击Windows窗体控制框的关闭(X)按钮时,我想显示一条消息或可能正在执行某些操作。

下面是代码:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Windows.Forms.Application]::EnableVisualStyles() 

$frmTest = New-Object System.Windows.Forms.Form
$frmTest.Size = New-Object System.Drawing.Size(640,480)
$frmTest.MaximizeBox = $False
$frmTest.ShowDialog()

当用户单击关闭(X)按钮时,我要显示一个消息框:

$choice = [System.Windows.Forms.MessageBox]::Show('Are you you want to exit?','TEST','YesNo','Error')
switch($choice)
{
    'Yes'
     {
         $frmTest.Close()

     }
}

我找到了这篇文章:Message on Form Close,但是我不确定如何使用它。请指教。谢谢

1 个答案:

答案 0 :(得分:2)

要捕获的事件是格式为Closing的事件,该事件具有一个事件自变量,可用来取消该事件。要了解如何在PowerShell中使用事件args,您可能需要看一下Windows Forms Controls Events in PowerShell - Use Sender and EventArgs

示例

Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$form.Text ="Test"
$form.Add_Closing({param($sender,$e)
    $result = [System.Windows.Forms.MessageBox]::Show(`
        "Are you sure you want to exit?", `
        "Close", [System.Windows.Forms.MessageBoxButtons]::YesNoCancel)
    if ($result -ne [System.Windows.Forms.DialogResult]::Yes)
    {
        $e.Cancel= $true
    }
})
$form.ShowDialog() | Out-Null
$form.Dispose()