Home > OS >  How to add_click to a pictureBox in a function in a powershell form?
How to add_click to a pictureBox in a function in a powershell form?

Time:07-14

I am tring to make a form with several images that will open a URL. Is it possible to add the click event to the function itself or do I have to add it after the function has been called?

Add-Type -AssemblyName System.Windows.Forms, System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                                 = New-Object system.Windows.Forms.Form
$Form.StartPosition                   = "CenterScreen"
$Form.Size                            = New-Object System.Drawing.Point(800,800)
$Form.text                            = "Example Form"
$Form.TopMost                         = $false
$Form.MaximumSize                     = $Form.Size
$Form.MinimumSize                     = $Form.Size
$Form.BackColor                       = "#000000"

function pictureBox {
    [CmdletBinding()]
    param (
        [Parameter (Mandatory = $True)]
        [string] $p,

        [Parameter (Mandatory = $True)]
        [int] $lx,

        [Parameter (Mandatory = $True)]
        [int] $ly,

        [Parameter (Mandatory = $True)]
        [string] $url
    )

    
    $img = [Drawing.Image]::Fromfile($PSCmdlet.GetUnresolvedProviderPathFromPSPath($p))
    [Windows.Forms.PictureBox]@{
        Size      = [Drawing.Size]::new($img.Size.Width, $img.Size.Height)
        Location  = [Drawing.Point]::new($lx, $ly)
        Image     = $img
      
    }
    Add_Click ( { start-process $url } )
}

$v1  = pictureBox -p "C:\Users\User\Desktop\t.png" -lx 20  -ly 65 -url **THE-URL**
$v1.Add_Click( { start-process **THE-URL** } )

CodePudding user response:

It's possible to do it from the function itself, first you need to instantiate the PictureBox, in the example below, the object is stored in $pbx. After that you can add the Click event to it.

As you may note there is also a GetNewClosure() method invocation, in this case it is required because the ScriptBlock needs to "remember" the value of $url.

function pictureBox {
    [CmdletBinding()]
    param (
        [Parameter (Mandatory = $True)]
        [string] $p,

        [Parameter (Mandatory = $True)]
        [int] $lx,

        [Parameter (Mandatory = $True)]
        [int] $ly,

        [Parameter (Mandatory = $True)]
        [string] $url
    )


    $img = [Drawing.Image]::Fromfile($PSCmdlet.GetUnresolvedProviderPathFromPSPath($p))
    $pbx = [Windows.Forms.PictureBox]@{
        Size      = [Drawing.Size]::new($img.Size.Width, $img.Size.Height)
        Location  = [Drawing.Point]::new($lx, $ly)
        Image     = $img

    }
    $pbx.Add_Click({ Start-Process $url }.GetNewClosure())
    $pbx
}

$v1 = pictureBox -p "C:\Users\User\Desktop\t.png" -lx 20 -ly 65 -url "https://stackoverflow.com/"
$Form.Controls.Add($v1)
$Form.ShowDialog()
  • Related