【问题标题】:Capture Windows Form close event in Powershell在 Powershell 中捕获 Windows 窗体关闭事件
【发布时间】:2019-07-12 20:13:59
【问题描述】:

我有一个 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,但我不知道如何使用它。请指教。谢谢

【问题讨论】:

    标签: winforms powershell


    【解决方案1】:

    要捕获的事件是Closing 形式的事件,它具有允许您取消事件的事件参数。要了解如何在 PowerShell 中使用事件参数,您可能需要查看 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()
    

    【讨论】:

    • 该代码已经过测试并按预期工作。是的,智能感知不会显示事件的自动完成。但这是处理事件的方式。
    • 再问一个问题:如果我有一个名为“取消”的按钮,如何调用表单关闭事件方法?
    • 不用担心。您不调用事件处理程序,而是执行一些导致引发将由事件处理程序处理的事件的事情,例如 $form.Close() 将引发 $form 的 Closing 事件。
    • 酷,没问题。
    • 当然,我会很高兴?
    猜你喜欢
    • 2015-07-30
    • 2010-11-25
    • 2018-03-17
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多