4

As a back end scripter/devops person I am not all that familiar with .net as much as I once was when I was a jr software engineer. However I love metrics and got the idea to write a network monitor for my vpn and cpu and ram usage because certain sites have caused google to leak memory and I do not notice it until i am at 99% at cpu and ram

So I have this Script that I decided to also try making a gui as you know everyone wants a full stack developer theses days.

I cannot for the life of me able to find out how to get the timer and event objects to fire on form load to create my quasi infinite loop

I have been using this source to learn about event timers and a registered objectevent

########################################################################
# Modified by Derek from source below. All I did was the psexec query and cleaned it up a bit.
# Original basis for gui updating created by:
# Code Generated By: SAPIEN Technologies, Inc., PrimalForms 2009 v1.1.10.0
# Generated On: 23/10/2010 08:37
# Generated By: KST
# http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/780aaa2e-4edf-495b-a63e-d8876eab9b25
########################################################################
function OnApplicationLoad {
    return $true 
}
function OnApplicationExit {
    $script:ExitCode = 0 
}
function Get-ComputerStats {
    process {

        $avg = Get-WmiObject win32_processor | 
            Measure-Object -property LoadPercentage -Average | 
            Foreach {$_.Average}
        $mem = Get-WmiObject win32_operatingsystem |
            Foreach {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory) * 100) / $_.TotalVisibleMemorySize)}
        $free = Get-WmiObject Win32_Volume -Filter "DriveLetter = 'C:'" |
            Foreach {"{0:N2}" -f (($_.FreeSpace / $_.Capacity) * 100)}
        [pscustomobject] [ordered] @{ 
            ComputerName = $env:computername
            AverageCpu   = $avg
            MemoryUsage  = $mem
            PercentFree  = $free
        }
    }
}
function GenerateForm {
    [void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    [void][reflection.assembly]::Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [void][reflection.assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form = New-Object System.Windows.Forms.Form
    $button = New-Object System.Windows.Forms.Button
    $outputBox = New-Object System.Windows.Forms.RichTextBox
    $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState

    $formEvent_Load = {
        $Timer = New-Object -Type Timers.Timer
        $Timer.Interval = 30000
        $timer.AutoReset = $true
        $timeout = 0

        $handler = {
            $pySpeedDir = "C:\Users\CentralTerminal\AppData\Local\Programs\Python\Python36\Scripts\pyspeedtest.exe"
            $speed = & $pySpeedDir
            $table = Get-ComputerStats 
            $outputBox.Text += get-date
            $outputBox.Text += "`n"
            $outputBox.Text += $speed
            $outputBox.Text += $table
            $outputBox.Select()
            $outputBox.SelectionStart = $outputBox.Text.Length
            $outputBox.ScrollToCaret()
            $outputBox.Refresh()
            $Timer.Stop()
            sleep -s 1  
        }

        $start = Register-ObjectEvent -InputObject $timer -SourceIdentifier TimerElapsed -EventName Elapsed -Action $handler
        $Timer.Start()
    }


    $form_StateCorrection_Load =
    {
        $form.WindowState = $InitialFormWindowState
    }


    $form.Controls.Add($outputBox)
    $form.Text = "Network and Machine Load"
    $form.Name = "GUM"
    $form.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $form.ClientSize = New-Object System.Drawing.Size(800, 400)
    #$Icon = New-Object system.drawing.icon ("brandimage.ICO")
    #$form.Icon = $Icon
    #$Image = [system.drawing.image]::FromFile("poweredbyit.jpg")
    #$form.BackgroundImage = $Image
    $form.BackgroundImageLayout = "None"
    $form.add_Load($formEvent_Load)


    $outputBox.Name = "outputBox"
    $outputBox.Text = ""
    $outputBox.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $outputBox.Location = New-Object System.Drawing.Point(5, 35)
    $outputBox.Size = New-Object System.Drawing.Size(785, 320) 
    $outputBox.font = "lucida console"
    $outputBox.TabIndex = 0

    $InitialFormWindowState = $form.WindowState
    $form.add_Load($form_StateCorrection_Load)
    return $form.ShowDialog()
} 

if (OnApplicationLoad -eq $true) {
    GenerateForm | Out-Null
    OnApplicationExit
}

It has been a while since I have posted so I apologize for the poor formatting. Thanks for looking

1 Answer 1

6

To register an event for a GUI object, you can use either of following options:

• Option 1

$form.Add_Load({$form.Text = "Form Load Event Handled!"})

• Option 2

$Form_Load = {$form.Text = "Form Load Event Handled!"}    
$form.Add_Load($Form_Load)

• Option 3

$form.Add_Load({Form_Load})
Function Form_Load
{
    $form.Text = "Form Load Event Handled!"
}

Example

If you are going to update GUI from a timer event, use System.Windows.Forms.Timer and handle its Tick event:

Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$form.Size = "400, 400"
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 1000
Function Timer_Tick()
{
    $form.Text = Get-Date -Format "HH:mm:ss"
}
Function Form_Load
{
    $form.Text = "Timer started"
    $timer.Start()
}
$form.Add_Load({Form_Load})
$timer.Add_Tick({Timer_Tick})
$form.ShowDialog()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the good answer. This helped and it is now working. Marked as answered

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.