如何在PowerShell中向.NET对象添加事件处理程序?

时间:2012-08-09 16:58:33

标签: powershell

我正在编写一个使用第三方库的PowerShell脚本。我正在使用的一个对象要求我添加一个事件处理程序。 The event delegate looks like this

public delegate void TSBPGPCreateOutputStreamEvent(object Sender, 
                                                   string Filename, 
                                                   System.DateTime TimeStamp, 
                                                   ref System.IO.Stream Stream, 
                                                   ref bool FreeOnExit)

在PowerShell中,我尝试过这样做:

$reader.Add_OnCreateOutputStream( {
    param(
        $sender,
        $fileName,
        $timestamp,
        [ref]
        $stream,
        [ref]
        $freeOnExit
    )
    $stream = New-Object IO.MemoryStream
} )

但是我收到了这条错误消息:

 Cannot convert value "
    param(
        $sender,
        $fileName,
        $timestamp,
        [ref]
        $stream,
        [ref]
        $freeOnExit
    )
$stream = New-Object IO.MemoryStream
" to type "SBPGP.TSBPGPCreateOutputStreamEvent". 
Error: "The type 'System.IO.Stream&' may not be used as a type argument."

订阅活动有更好的方法吗?为什么Stream类型不能用作类型参数?我做错了什么?

2 个答案:

答案 0 :(得分:7)

您应该使用Register-ObjectEvent cmdlet,使用以下命令查看您自己系统上的示例:

PS> Get-Help Register-ObjectEvent -full

答案 1 :(得分:-1)

Add-Type -AssemblyName System.Windows.Forms
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form = New-Object Windows.Forms.Form
$form.add_mousedown($handler_form_mousedown)
$handler_form_Mousedown=
{
param([object]$sender, [System.EventArgs]$e)
write-host $e.x
write-host $e.y
$sender.text="if ya think your so noble answer the question"
$sender.text = "Nobles Oblige"
# PS HELP IS USELESS FOR THIS    
}

$App = $form.ShowDialog()