Page 1 of 1

Is it possible to dynamically generate event code?

Posted: Thu Aug 22, 2019 9:58 am
by matthmsft
Hi folks

I am trying to think through how it would be possible to dynamically generate events for dynamically generated controls.

For example, I would like to have an XML file which has the different options I want to dynamically load into an options page. I have managed to do this and create a Label and a Textbox, I can take input and everything is good. Suppose however, 1 of my options is for a file path. I want to dynamically create a Label and a Textbox, but also a button next to the Text Box which is linked to an FolderBrowserDialog control. The Button needs to have a Click event, that then points to the FolderBrowserDialog and has the necessary code for what to do next.

Is this something that is possible, if so, can someone point me in the right direction for how to approach this, perhaps a blog post or tutorial? Or, If I am getting too carried away and things like this should be statically defined, please let me know!

Thanks!

Re: Is it possible to dynamically generate event code?

Posted: Thu Aug 22, 2019 10:24 am
by jvierra
Events can be added by calling the "add" method of the control.

$button.add_Click({Write-Host 'I was clicked'})

Re: Is it possible to dynamically generate event code?

Posted: Thu Aug 22, 2019 11:34 am
by jvierra
Here is a partial example from another project:

Code: Select all

[xml]$xml = @'
<?xml version="1.0"?>
<Form Name="testForm" Text="Test Generated Form" StartPosition="CenterScreen" Size="600,400">
    <Events>
    	<Event Name="Closing">
       		<![CDATA[
    		Write-Host 'I am closing now' -Fore Green
    		]]>	
    	</Event>
    </Events>
    <Controls>
	    <Control Type="Button" Name="closeutton" Location="10,10" Text="Close" DialogResult="Ok"/>
    </Controls>
</Form>
'@

#create the form
$hash = @{}
$xml.Form.Attributes |
    ForEach-Object{
        $hash.Add($_.Name,$_.Value)
    }
$form = [System.Windows.Forms.Form]$hash

# create the controls and add to the form
$xml.Form.Controls.Control |
    ForEach-Object{
        $button = $_
        Switch ($_.Type){
            Button {
                $hash = @{}
                $button.Attributes
                $button.Attributes | ?{$_.Name -ne 'Type'} |
                    ForEach-Object{
                        $hash.Add($_.Name, $_.Value)
                    }
                $c = [System.Windows.Forms.Button]$hash
                $form.Controls.Add($c)
            }
            Label {}
            TextBox {}
            }
    }
    
 #add the events  (you have to code a loop to find and do all control events
$xml.Form.Events.Event |
    ForEach-Object{
        $script = [scriptblock]::Create($_.'#cdata-section')
        $form.add_closing($script)
    }

$form.ShowDialog()

Re: Is it possible to dynamically generate event code?

Posted: Thu Aug 22, 2019 4:35 pm
by matthmsft
That's awesome, thank you, I will try it out today!