Form Scoping Woes

This topic contains 1 reply, has 1 voice, and was last updated by Profile photo of Micah Battin Micah Battin 2 years, 1 month ago.

  • Author
    Posts
  • #20420
    Profile photo of Micah Battin
    Micah Battin
    Participant

    Hello Ninja's,

    I have a problem. I am trying to get a function to execute inside of a button click event. I would expect that if it was a scope issue, that it wouldn't event affect the target (in this case, a list box), however, it does! But it comes back with a blank entry addition. Here is a sample to demonstrate what I am talking about.

    Add-type -AssemblyName System.Windows.Forms,System.Drawing
    
    $Main = [Windows.Forms.Form]@{
        ClientSize = "1024,768"
        Text = "AGDLP Master-Tron-O-Matic 9000+"
        MinimumSize = "800,600"
    }
    
    $Script:LogBox = [Windows.Forms.ListBox]@{
        Enabled = $True
        Size = "1004,190"
        Location = "10,568"
        Anchor = "Bottom,Top,Left,Right"
        SelectionMode = "MultiExtended"
    }
    $Main.Controls.Add($Script:LogBox)
    
    
    Function AddLogEntry {
        Param (
            [String]$Input
        )
        
        $VisibleItems = $Script:LogBox.ClientSize.Height / $Script:LogBox.ItemHeight
        $Script:LogBox.TopIndex = [Math]::Max(($Script:LogBox.Items.Count - $VisibleItems + 1), 0)
    
        $Script:LogBox.Items.Add($Input)
    }
    
    $TestButton = [Windows.Forms.Button]@{
        Text = "Text Log Entry"
        Size = "120,20"
        Location = "10,10"
    }
    
    $TestButton_Click = {
        AddLogEntry -Input "This is a random number: $(Get-Random 1000000)"
        $Script:LogBox.Items.Add("This is a random number: $(Get-Random 1000000)")
    }
    
    $TestButton.Add_Click($TestButton_Click)
    
    $Main.Controls.Add($TestButton)
    
    [Windows.Forms.Application]::Run($Main)
    

    Does anyone know what is going on here? I have been beating my head over this for awhile.

  • #20426
    Profile photo of Micah Battin
    Micah Battin
    Participant

    Nevermind, I solved it. $Input already exists in all powershell sessions. Once I changed the parameter in AddLogEntry to a unique variable name, everything worked fine.

You must be logged in to reply to this topic.