7

I'm writing a PowerShell script which uses a third-party library. One of the objects I'm using requires that I add an event handler. 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)

In PowerShell, I tried doing this:

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

But I get back this error message:

 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."

Is there a better way of subscribing to events? Why can't the Stream type be used as a type argument? What am I doing wrong?

2 Answers 2

10

You should use the Register-ObjectEvent cmdlet, take a look at the examples on your own system by using:

PS> Get-Help Register-ObjectEvent -full
Sign up to request clarification or add additional context in comments.

Comments

4
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()

2 Comments

This is actually the correct, working answer. In my case, I needed to add event handlers to a list of LinkLabel WinForm controls within PowerShell where each LinkLabel needed to access its own Tag property inside the event handler. The info provided in this answer was the only way to accomplish that.
I tried to use this approach to add a handler for SqlConnection.InfoMessage event and it works only partially. By this I mean that the handler is invoked not when the event triggers (on messages coming from the database), but instead all events are handled in the end, after finishing SqlCommand.ExecuteNonQuery(). Any idea why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.