Winforms 在Powershell中捕获Windows窗体关闭事件
我有一张windows窗体。当我单击Windows窗体控制框的关闭(X)按钮时,我想显示一条消息或可能正在执行某些操作 代码如下:Winforms 在Powershell中捕获Windows窗体关闭事件,winforms,powershell,Winforms,Powershell,我有一张windows窗体。当我单击Windows窗体控制框的关闭(X)按钮时,我想显示一条消息或可能正在执行某些操作 代码如下: [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") [void] [System.Windows.Form
[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()
}
}
我找到了这篇文章:,但我不知道如何使用它。请给我一些建议。感谢要捕获的事件是具有允许您取消事件的事件参数的事件。要了解如何在PowerShell中使用事件参数,您可能需要查看
示例
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()
代码已经过测试,并按预期工作。是,intellisense不会显示事件的自动完成。但这是处理事件的方法。还有一个问题:如果我有一个名为Cancel的按钮,我如何调用表单关闭事件方法?不用担心。您不调用事件处理程序,而是执行一些导致引发事件处理程序将处理的事件的操作,例如$form.Close()将引发$form.Cool的关闭事件,没问题。当然,我很乐意