How to create a graphical interface, a windows form in powershell command?

How to create a graphical interface, a windows form in powershell command?

here is a tutorial to create and understand how to create a graphical user interface

Unlike other languages ​​such as C or C #, powershell, including powershell ISE (by default on your OS) allows you to simply create a graphical user interface (GUI) with a tool menu (tool panel ) dedicated to graphic creation. Nevertheless, we always have the possibility to create some directly thanks to some functionality such as System.Windows.Forms and System.Drawing.

In this article, I will show you the basics. That is, how to create a button, how to create a textbox, how to add an add on the button, how to display the result in the textbox, how to clear a textbox …

The code below should be an example of a powershell GUI (windows.forms)

 

the complete code of the powershell tutorial and some annotations:

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

#create a windows form
$Form = New-Object system.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(200,200) #the size of form, X , Y
$Form.Text = "test forme"

#create a button 
$BT0 = New-Object System.Windows.Forms.Button
$BT0.Location = New-Object System.Drawing.Point(10,10) #the position of the button, coordinated x, y
$BT0.text = "show" #Button name
$BT0.add_click($BT0_click) #on click, we release the action $ BT0_click see below
$Form.Controls.add($BT0) #Add Button to the form

#create button to clear the 
$BTclear = New-Object System.Windows.Forms.Button
$BTclear.Location = New-Object System.Drawing.Point(100,10) #the position of the text_box, coordinated x, y
$BTclear.text = "Clear text" #Button name
$BTclear.add_click($BT_clear) #on click, we release the action $ BT0_click see below
$Form.Controls.add($BTclear) #Add Button to the form

#create a label
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,40) 
$label.Size = New-Object System.Drawing.Size(100,20) 
$label.Text = 'this is a label:' 
$form.Controls.Add($label)

#create a textbox
$text_box = New-Object System.Windows.Forms.TextBox
$text_box.Location = New-Object System.Drawing.Point(10,80) 
$text_box.Size = New-Object System.Drawing.Size(100,100) 
$Form.Controls.Add($text_box)


$form.startposition ="CenterScreen" #start form a screen center
$Form.ShowDialog() #show the form

#click button action
$BT0_click = {$text_box.text += ("my message :)")}
$BT_clear = {$text_box.Clear()}

 

I hope you understood and that you will succeed your own interface 🙂

Laisser un commentaire