trap {}在winforms中不起作用

时间:2014-05-10 15:22:56

标签: winforms powershell error-handling powershell-trap

我的所有脚本中都有一个trap{}来处理和记录所有无法预料的异常,我没有通过Try / catch处理这些异常。

这很有效。

但是,当我有一个带有Windows窗体的脚本时,所有异常都将自动显示为.Net-popup,并且trap{}内的代码不会被执行,因此错误永远不会被记录。

简单示例:

trap { Write-Host "This is written from inside the trap" }

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

$form1 = New-Object 'System.Windows.Forms.Form'
$form1.ClientSize = '200, 150'
$button1 = New-Object 'System.Windows.Forms.Button' 
$button1.Location = '54, 45'
$button1.Size = '75, 23'
$form1.Controls.Add($button1)
$button1.add_mouseclick({ Testfunction })

function TestFunction { 
    $button1.falseproperty = 1  # this causes an exception  
}


TestFunction   ## this call of the faulty function gets trapped by the trap, the call from the button does not
$form1.ShowDialog()      

为什么忽略陷阱?
如果出现异常,如何让表单执行陷阱? 特别是在具有100多个函数的脚本中,我不想为每个函数添加trap{}(它可以工作)。

1 个答案:

答案 0 :(得分:1)

WinForms通常会处理UI线程上的异常,但您可以订阅一个事件来自行处理:

[Windows.Forms.Application]::add_ThreadException({ ... })
相关问题