2012-08-09 54 views
3

我在寫一個使用第三方庫的PowerShell腳本。我正在使用的一個對象要求我添加一個事件處理程序。 The event delegate looks like this如何將事件處理程序添加到PowerShell中的.NET對象?

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類型用作類型參數?我究竟做錯了什麼?

回答

5

您應該使用Register-ObjectEvent cmdlet時,通過使用看看你自己的系統上的例子:

PS> Get-Help Register-ObjectEvent -full 
-3
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() 
+0

好像它被認爲是一個笑話...... – icedwater 2013-09-05 02:11:39

相關問題