Home > database >  winform clear graphic powershell
winform clear graphic powershell

Time:10-20

I'm trying to figure out a way to clear a graphic from a windows form graphic. I've looked at some C# example that call out using Graphics.clear() but I can't seem to figure out what I'm doing wrong here. I even tried to use $form.visiblity which does appear to reset the graphic, however when I run it in a loop (to draw multiple lines) it creates a whole new form window that doesn't close. Here is a sample of what I'm trying to do:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  

# Create a Form
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(600,600)  
$form.text = "Line Draw Test"

# Get the form's graphics object
$formGraphics = $form.createGraphics()

function New-LineFromOrigin {
    Param ($form)
    $width = $form.Width
    $height = $form.Height
    $greenBrush = new-object Drawing.SolidBrush ("green")
    $formGraphics.FillEllipse($greenBrush, $width/2, $height/2, 5, 5 ) # draw an ellipse using rectangle object
    $formGraphics.DrawLine($greenBrush, $width/2, $height/2, 0, 0 ) # draw an ellipse using rectangle object
}

$Button = New-Object System.Windows.Forms.Button 
$Button.Location = New-Object System.Drawing.Size(30,30) 
$Button.Size = New-Object System.Drawing.Size(90,40) 
$Button.Text = "Draw line" 
$Button.Add_Click(
    {New-LineFromOrigin -form $form}
) 

$form.Controls.Add($Button) 

$Button2 = New-Object System.Windows.Forms.Button 
$Button2.Location = New-Object System.Drawing.Size(200,30) 
$Button2.Size = New-Object System.Drawing.Size(90,40) 
$Button2.Text = "Clear" 
$Button2.Add_Click(
    {$form.graphics.clear()}
) 

$form.Controls.Add($Button2) 
$form.Add_Shown({$form.Activate()})
[void] $form.ShowDialog()

CodePudding user response:

There are a couple of ways to clear the graphic.

Invalidate the form

$form.Invalidate()

Clear the graphics and reset the color

# Clear with a new color on the background
$formGraphics.Clear([System.Drawing.Color]::White)

# Or clear with the form's current background color
$formGraphics.Clear($form.BackColor)

Keep in mind, you're not actually clearing/deleting anything; just re-drawing something on the form that replaces the existing graphic/drawing.

  • Related