Getting keypress on a Form in Powershell - powershell

Im trying to make a image viewer in powershell using some windows forms libraries, I can already store the images location inside an array, but now I want it to detect the keys Right and Left to change between the locations inside the array
Here is the code I'm using:
param(
[parameter (Mandatory=$false, position=0, ParameterSetName='url')]
[string]$url = ''
)
Add-Type -AssemblyName 'System.Windows.Forms'
[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.Application]::EnableVisualStyles()
Function Load-Images{
param (
[parameter (Mandatory=$true, position=0, ParameterSetName='path')]
$path
)
$screen = [System.Windows.Forms.Screen]::AllScreens
$form = new-object Windows.Forms.Form
$form.Text = "Image Viewer"
$form.Size = New-Object System.Drawing.Size($screen.WorkingArea[0].Width, $screen.WorkingArea[0].Height)
$pictureBox = new-object Windows.Forms.PictureBox
$pictureBox.Size = New-Object System.Drawing.Size($screen.WorkingArea[0].Width, $screen.WorkingArea[0].Height)
$pictureBox.Image = $path
$pictureBox.SizeMode = 'Zoom'
$pictureBox.Anchor = 'Top,Left,Bottom,Right'
$form.controls.add($pictureBox)
$form.Add_Shown( { $form.Activate() } )
$form.ShowDialog()
$img.dispose()
}
if(!$url) {
$dir = Get-Location
$Files = #(Get-ChildItem "$($dir.Path)\*" -Include *.jpg, *.jpeg, *.png)
$maxSize = $Files.Length
Write-Output $maxSize
Write-Output $Files.Fullname
$img = [System.Drawing.Image]::Fromfile((Get-Item $Files.Fullname[0]))
Load-Images -path $img
}

Continuing from my comment. What you are after is not specific to PowerShell at all. It's a UX/UI design/property/event item.
For Example, here is one showing adding and using the property/event setting to watch for defined keypresses. Just run the function, call the function, and hit 'Enter' or 'Esc', or click 'OK' to fire those events.
function Start-CreateForm
{
#Import Assemblies
Add-Type -AssemblyName System.Windows.Forms,
System.Drawing
$Form1 = New-Object System.Windows.Forms.Form
$OKButton = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$Label1 = New-Object System.Windows.Forms.Label
$textBox1 = New-Object System.Windows.Forms.TextBox
$Field1 = ""
# Check for ENTER and ESC presses
$Form1.KeyPreview = $True
$Form1.Add_KeyDown({if ($PSItem.KeyCode -eq "Enter")
{
# if enter, perform click
$OKButton.PerformClick()
}
})
$Form1.Add_KeyDown({if ($PSItem.KeyCode -eq "Escape")
{
# if escape, exit
$Form1.Close()
}
})
# The action on the button
$handler_OK_Button_Click=
{
$Field1 = $textBox1.Text
$Field1
# Returns a message of no data
if ($Field1 -eq "") {[System.Windows.Forms.MessageBox]::Show("You didn't enter anything!", "Data")}
# Returns what they types. You could add your code here
else {[System.Windows.Forms.MessageBox]::Show($Field1, "Data")}
}
$OnLoadForm_StateCorrection=
{
$Form1.WindowState = $InitialFormWindowState
}
# Form Code
$Form1.Name = "Data_Form"
$Form1.Text = "Data Form"
$Form1.MaximizeBox = $false #lock form
$Form1.FormBorderStyle = 'Fixed3D'
# None,FixedDialog,FixedSingle,FixedToolWindow,Sizable,SizableToolWindow
# Icon
$Form1.Icon = [Drawing.Icon]::ExtractAssociatedIcon((Get-Command powershell).Path)
# $NotifyIcon.Icon = [Drawing.Icon]::ExtractAssociatedIcon((Get-Command powershell).Path)
$Form1.DataBindings.DefaultDataSourceUpdateMode = 0
$Form1.StartPosition = "CenterScreen"# moves form to center of screen
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 300 # sets X
$System_Drawing_Size.Height = 150 # sets Y
$Form1.ClientSize = $System_Drawing_Size
$OKButton.Name = "OK_Button"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 45
$System_Drawing_Size.Height = 23
$OKButton.Size = $System_Drawing_Size
$OKButton.UseVisualStyleBackColor = $True
$OKButton.Text = "OK"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 113
$OKButton.Location = $System_Drawing_Point
$OKButton.DataBindings.DefaultDataSourceUpdateMode = 0
$OKButton.add_Click($handler_OK_Button_Click)
$Form1.Controls.Add($OKButton)
$InitialFormWindowState = $Form1.WindowState
$Form1.add_Load($OnLoadForm_StateCorrection)
$Label1.Location = New-Object System.Drawing.Point(10,20)
$Label1.Size = New-Object System.Drawing.Size(280,20)
$Label1.Text = "Enter data here:"
$Form1.Controls.Add($Label1)
$textBox1.TabIndex = 0 # Places cursor in field
$textBox1.Location = New-Object System.Drawing.Point(10,40)
$textBox1.Size = New-Object System.Drawing.Size(260,20)
$Form1.Controls.Add($textBox1)
$Form1.Topmost = $True # Moves form to top and stays on top
$Form1.Add_Shown({$textBox1.Select()})
# Show Form
$Form1.ShowDialog()
}
For your use case, you just have to use the needed keyboard specifics.

Related

I want to monitor the date and time of a file every 30 seconds

I want to monitor the date and time of a file. I wrote the code that do the job as I want but I can't reposition the gui window. I tried all I could find like "start-job" or create a new runspace but I don't get any results in richtextbox. Any suggestion is welcome.
$targetFile = "full path"
# Function - Add Text to RichTextBox
function Add-RichTextBox{
[CmdletBinding()]
param ($text)
#$richtextbox_output.Text += "`tCOMPUTERNAME: $ComputerName`n"
$richtext.Text += "$text"
$richtext.Text += "`n"
}
# Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Monitor script"
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$Font = New-Object System.Drawing.Font("Tahoma",11)
$Form.Font = $Font
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,40)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = (Get-Date).ToString()
$form.Controls.Add($label)
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Point(150,220)
$StartButton.Size = New-Object System.Drawing.Size(100,33)
$StartButton.Text = 'Start'
#$StartButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $StartButton
$form.Controls.Add($StartButton)
$StartButton.Add_click({
while($true){
$lastdate = Get-ChildItem $targetFile
$Date = $lastdate.LastAccessTime.ToString()
Add-RichTextBox "$date"
$richtext.SelectionStart = $richtext.TextLength
$richText.ScrollToCaret()
#$richtext.refresh()
#$form.refresh()
Start-sleep 30
}
})
## the Rich text box
$richtext = new-object System.Windows.Forms.RichTextBox
$richtext.Location = New-Object System.Drawing.Point(20,60)
$richtext.multiline = $true
$richtext.Name = "Results"
$richtext.text = "Results:`n"
$richtext.scrollbars = "Both"
$richtext.Height = 120
$richtext.width = 350
$richtext.font = new-object system.drawing.font "Lucida Console",10
$Form.controls.add($richtext)
$Form.Add_Shown({$Form.Activate()})
$form.ShowDialog()
Continuing from my comment to use a Timer on your form (if you absolutely do not want a FileSystemWatcher), here's how you can do that:
$targetFile = "D:\Test\blah.txt"
$lastAccessed = (Get-Date) # a variable to keep track of the last LastAccessTime of the file
# Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Monitor script"
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$Font = New-Object System.Drawing.Font("Tahoma",11)
$form.Font = $Font
# Label
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,40)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = (Get-Date).ToString()
$form.Controls.Add($label)
# Button
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Point(150,200)
$StartButton.Size = New-Object System.Drawing.Size(100,33)
$StartButton.Text = 'Start'
$form.Controls.Add($StartButton)
$StartButton.Add_click({
$timer.Enabled = $true
$timer.Start()
})
# RichTextBox
$richtext = New-Object System.Windows.Forms.RichTextBox
$richtext.Location = New-Object System.Drawing.Point(20,60)
$richtext.Multiline = $true
$richtext.Name = "Results"
$richtext.Text = "Results:`r`n"
$richtext.ScrollBars = "Both"
$richtext.Height = 120
$richtext.Width = 350
$richtext.Font = New-Object System.Drawing.Font "Lucida Console",10
$form.Controls.Add($richtext)
# Timer
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 30000 # 30 seconds
$timer.Enabled = $false # disabled at first
$timer.Add_Tick({
$file = Get-Item -Path $targetFile -ErrorAction SilentlyContinue
# if we can find the file and its last AccessedTime is not
# the same as we already stored in variable $lastAccessed
# use script-scoping here, so $script:lastAccessed instead of $lastAccessed
if ($file -and $file.LastAccessTime -gt $script:lastAccessed) {
$richtext.AppendText("$($file.LastAccessTime.ToString())`r`n")
$script:lastAccessed = $file.LastAccessTime # remember this new datetime
}
})
$form.ShowDialog()
# Important: Clean up
$timer.Stop()
$timer.Dispose()
$richtext.Dispose()
$form.Dispose()

get acl from folders with file open dialog

I have built a little gui for getting the acl permissions for folders. with the path button i want to specify the folder path with a folder browser dialog and with the permissions button i want to get the acl. unfortunately the permissions button don't work because it can't get the folder path from the get-folder function. what's wrong with the function?
#################################################### Functions #######################################################
$path = Function Get-Folder ($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null
$Ordnername = New-Object System.Windows.Forms.FolderBrowserDialog
$Ordnername.Description = "Ordner auswählen"
$Ordnername.rootfolder = "MyComputer"
if($Ordnername.ShowDialog() -eq "OK")
{
$Ordner += $Ordnername.SelectedPath
}
return $Ordner
}
############################################## GetPermissions function
function GetPermissions{
#$Folder = get-folder
$Result = (Get-ACL $path).access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags | Out-string
$outputBox.Text = $Result
}
function Close{
$Form.Close()
}
###################### CREATING PS GUI TOOL #############################
#### Form settings #################################################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border
$Form.Text = "Folder Permissions"
$Form.Size = New-Object System.Drawing.Size(1120,330)
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.BackgroundImageLayout = "Zoom"
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$Form.Icon = $Icon
#### Input window with "Folder Path" label ##########################################
#$InputBox = New-Object System.Windows.Forms.TextBox
#$InputBox.Location = New-Object System.Drawing.Size(10,50)
#$InputBox.Size = New-Object System.Drawing.Size(180,20)
#$Form.Controls.Add($InputBox)
#$Label2 = New-Object System.Windows.Forms.Label
#$Label2.Text = "Folder Path:"
#$Label2.AutoSize = $True
#$Label2.Location = New-Object System.Drawing.Size(15,30)
#$Form.Controls.Add($Label2)
#### Group boxes for buttons ########################################################
$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size(10,95)
$groupBox.size = New-Object System.Drawing.Size(180,180)
$groupBox.text = "Controls:"
$Form.Controls.Add($groupBox)
###################### BUTTONS ##########################################################
#### Path ###################################################################
$Path = New-Object System.Windows.Forms.Button
$Path.Location = New-Object System.Drawing.Size(10,10)
$Path.Size = New-Object System.Drawing.Size(150,60)
$Path.Text = "Path"
$Path.Add_Click({Get-folder})
$Path.Cursor = [System.Windows.Forms.Cursors]::Hand
$Form.Controls.Add($Path)
#### Permissions ###################################################################
$Permissions = New-Object System.Windows.Forms.Button
$Permissions.Location = New-Object System.Drawing.Size(15,25)
$Permissions.Size = New-Object System.Drawing.Size(150,60)
$Permissions.Text = "Permissions"
$Permissions.Add_Click({GetPermissions})
$Permissions.Cursor = [System.Windows.Forms.Cursors]::Hand
$groupBox.Controls.Add($Permissions)
#### Close ###################################################################
$Close = New-Object System.Windows.Forms.Button
$Close.Location = New-Object System.Drawing.Size(15,100)
$Close.Size = New-Object System.Drawing.Size(150,60)
$Close.Text = "Close"
$Close.Add_Click({Close})
$Close.Cursor = [System.Windows.Forms.Cursors]::Hand
$groupBox.Controls.Add($Close)
###################### END BUTTONS ######################################################
#### Output Box Field ###############################################################
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(200,20)
$outputBox.Size = New-Object System.Drawing.Size(900,265)
$outputBox.Font = New-Object System.Drawing.Font("Consolas", 8 ,[System.Drawing.FontStyle]::Regular)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
##############################################
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
The reason for that mainly has to do with scoping, plus you should not write the function as $path = Function ... making it a call to the function.
Also, $Ordner += $Ordnername.SelectedPath is wrong, because you have never defined what $Ordner is in the function.
Below a rewrite of your code where I took the liberty to change some variable names to make them more self-explanatory:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
###################### CREATING PS GUI TOOL #############################
# define your selected path variable and initialize to nothing
$SelectedPath = $null
#################################################### Functions #######################################################
function Get-Folder {
$Ordnername = New-Object System.Windows.Forms.FolderBrowserDialog
$Ordnername.Description = "Ordner auswählen"
$Ordnername.rootfolder = "MyComputer"
if($Ordnername.ShowDialog() -eq "OK") {
$script:SelectedPath = $Ordnername.SelectedPath # use script scoping here
$outputBox.Text = $script:SelectedPath
}
}
############################################## GetPermissions function
function Get-Permissions {
$outputBox.Text = '' # clear the textbox
if (-not [string]::IsNullOrWhiteSpace($script:SelectedPath)) {
$Result = (Get-ACL $script:SelectedPath).Access | # use script scoping here
Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags | Out-string
$outputBox.Text = $script:SelectedPath + "`r`n`r`n" + $Result
}
}
#### Form settings #################################################################
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border
$Form.Text = "Folder Permissions"
$Form.Size = New-Object System.Drawing.Size(1120,330)
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.BackgroundImageLayout = "Zoom"
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Icon = [System.Drawing.Icon]::ExtractAssociatedIcon((Join-Path -Path $PSHOME -ChildPath 'powershell.exe'))
$Form.Icon = $Icon
#### Group boxes for buttons ########################################################
$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size(10,95)
$groupBox.size = New-Object System.Drawing.Size(180,180)
$groupBox.text = "Controls:"
$Form.Controls.Add($groupBox)
###################### BUTTONS ##########################################################
#### Path button ###################################################################
$PathButton = New-Object System.Windows.Forms.Button
$PathButton.Location = New-Object System.Drawing.Size(10,10)
$PathButton.Size = New-Object System.Drawing.Size(150,60)
$PathButton.Text = "Path"
$PathButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$PathButton.Add_Click({Get-Folder})
$Form.Controls.Add($PathButton)
#### Permissions button ###################################################################
$Permissions = New-Object System.Windows.Forms.Button
$Permissions.Location = New-Object System.Drawing.Size(15,25)
$Permissions.Size = New-Object System.Drawing.Size(150,60)
$Permissions.Text = "Permissions"
$Permissions.Cursor = [System.Windows.Forms.Cursors]::Hand
$Permissions.Add_Click({Get-Permissions})
$groupBox.Controls.Add($Permissions)
#### Close ###################################################################
$Close = New-Object System.Windows.Forms.Button
$Close.Location = New-Object System.Drawing.Size(15,100)
$Close.Size = New-Object System.Drawing.Size(150,60)
$Close.Text = "Close"
$Close.Cursor = [System.Windows.Forms.Cursors]::Hand
$Close.Add_Click({$Form.Close()})
$groupBox.Controls.Add($Close)
###################### END BUTTONS ######################################################
#### Output Box Field ###############################################################
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(200,20)
$outputBox.Size = New-Object System.Drawing.Size(900,265)
$outputBox.Font = New-Object System.Drawing.Font("Consolas", 8 ,[System.Drawing.FontStyle]::Regular)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
##############################################
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
# destroy the form from memory
$Form.Dispose()

Powershell GUI tabbed layout script placement

I wrote six small gui scripts that I'd like to place in a single file, for the sake of converting said file into rxecutable with ps2exe.
I've found a script ,here on stack that is perfect for what I want. Unfortunatelly I cann't find any info on script placement within tabs and MS documentation leads me to ISE tabs, which is not helpfull.
Say I'd like to place this
Add-Type -AssemblyName PresentationFramework
$button_click = {
$folder = $textBox1.Text;
$pytanie = [System.Windows.MessageBox]::Show('Czy chcesz usunac folder?', '', '4');
If($pytanie -eq 'Yes')
{Remove-Item –path $folder –recurse -Force};
$test = Test-Path $folder;
if ($test -eq $false){[System.Windows.MessageBox]::Show('Folder Usuniety', '', '0')}}
$label2 = New-Object System.Windows.Forms.Label
$label2.AutoSize = $True
$label2.Text = ("Scieżka")
$label2.Location = New-Object System.Drawing.Point (10,30)
$label2.Size = New-Object System.Drawing.Size (25,70)
$label2.Font = [System.Drawing.Font]::new("Arial", 10, [System.Drawing.FontStyle]::Bold)
$textBox1 = New-Object System.Windows.Forms.TextBox
$textBox1.Location = New-Object System.Drawing.Point(10,70) ### Location of the text box
$textBox1.Size = New-Object System.Drawing.Size(200,50) ### Size of the text box
$textBox1.Multiline = $false ### Allows multiple lines of data
$textBox1.Font = New-Object System.Drawing.Font("Consolas",10,[System.Drawing.FontStyle]::Regular)
$textBox1.ReadOnly=$false
$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Point(10,120)
$button.Size = New-Object System.Drawing.Size (200,30)
$button.Text = "Usun Folder"
$button.Add_Click($button_click)
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Mapowanie' ### Text to be displayed in the title
$form.Size = New-Object System.Drawing.Size(240,200) ### Size of the window
$form.StartPosition = 'Manual'
$form.Location = '10,10'
$form.Topmost = $true ### Optional - Opens on top of other windows
$form.Controls.AddRange(#($textBox1,$button, $label2))
$form.ShowDialog()
within a tab. How to do it?
I think that it the
$Tab1.Controls.Add($button)
You are looking for.
For example
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$ApplicationForm = New-Object System.Windows.Forms.Form
$ApplicationForm.StartPosition = "CenterScreen"
$ApplicationForm.Topmost = $false
$ApplicationForm.Size = "800,600"
$FormTabControl = New-object System.Windows.Forms.TabControl
$FormTabControl.Size = "755,475"
$FormTabControl.Location = "25,75"
$ApplicationForm.Controls.Add($FormTabControl)
$Tab1 = New-object System.Windows.Forms.Tabpage
$Tab1.DataBindings.DefaultDataSourceUpdateMode = 0
$Tab1.UseVisualStyleBackColor = $True
$Tab1.Name = "Tab1"
$Tab1.Text = "Tab1”
$FormTabControl.Controls.Add($Tab1)
$textBox1 = New-Object System.Windows.Forms.TextBox
$textBox1.Location = New-Object System.Drawing.Point(10,70) ### Location of the text box
$textBox1.Size = New-Object System.Drawing.Size(200,50) ### Size of the text box
$textBox1.Multiline = $false ### Allows multiple lines of data
$textBox1.Font = New-Object System.Drawing.Font("Consolas",10,[System.Drawing.FontStyle]::Regular)
$textBox1.ReadOnly=$false
$Tab1.Controls.Add($textBox1)
$Tab2 = New-object System.Windows.Forms.Tabpage
$Tab2.DataBindings.DefaultDataSourceUpdateMode = 0
$Tab2.UseVisualStyleBackColor = $True
$Tab2.Name = "Tab2"
$Tab2.Text = "Tab2”
$FormTabControl.Controls.Add($Tab2)
$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Point(10,120)
$button.Size = New-Object System.Drawing.Size (200,30)
$button.Text = "Usun Folder"
$button.Add_Click($button_click)
$Tab2.Controls.Add($button)
# Initlize the form
$ApplicationForm.Add_Shown({$ApplicationForm.Activate()})
[void] $ApplicationForm.ShowDialog()

How do I return errorlevel by handling GUI using PowerShell?

I have a GUI, the form will close automatically in 10s. But if we click the pause button, it also will close the form. I want to return the error level each process that I do. If the form closes automatically, it will return error level 10. but if we click the button pause, it will return error level 20. anyone can help, please.
this is my code.
function Timer_GUI {
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$label1 = New-Object 'System.Windows.Forms.Label'
$label2 = New-Object 'System.Windows.Forms.Label'
$Cancel = New-Object 'System.Windows.Forms.Button'
$timer1 = New-Object 'System.Windows.Forms.Timer'
$form1_Load = {
$TotalTime = 10 #in seconds
$script:StartTime = (Get-Date).AddSeconds($TotalTime)
#Start the timer
$timer1.Start()
}
$label1.Location = New-Object System.Drawing.Size(220,60)
$label1.Size = New-Object System.Drawing.Size(500,30)
$label2.Text = "The Process Will Continue in 10s"
$label2.Location = New-Object System.Drawing.Size(140,30)
$label2.Size = New-Object System.Drawing.Size(500,30)
$form1.SuspendLayout()
$form1.Controls.Add($label1)
$form1.Controls.Add($label2)
$form1.Controls.Add($Cancel)
$form1.Width = 500
$form1.Height = 200
$form1.StartPosition = "CenterScreen"
$form1.BackColor = "#e2e2e2"
$form1.add_Load($form1_Load)
$Cancel.DialogResult = 'Cancel'
$Cancel.Location = New-Object System.Drawing.Size(350,100)
$Cancel.Size = New-Object System.Drawing.Size(100,30)
$Cancel.Text = "Pause"
$Cancel.add_Click($Cancel_Click)
$timer1.add_Tick($timer1_Tick)
$form1.ResumeLayout()
#Show the Form
return $form1.ShowDialog()
exit 100
}
#Call the form
Timer_GUI | Out-Null
Not a GUI expert, but, here it is. Add a global variable $Global:formresult default set to 10, if button clicked set to 20.
The following 3 lines added or updated,
Add-Type -AssemblyName System.Windows.Forms
$Global:formresult = 10
$Cancel.add_Click({ $Global:formresult = 20 })
$Global:formresult
Full code, copy and paste from yours.
Add-Type -AssemblyName System.Windows.Forms
function Timer_GUI {
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$label1 = New-Object 'System.Windows.Forms.Label'
$label2 = New-Object 'System.Windows.Forms.Label'
$Cancel = New-Object 'System.Windows.Forms.Button'
$timer1 = New-Object 'System.Windows.Forms.Timer'
$Global:formresult = 10
$form1_Load = {
$TotalTime = 10 #in seconds
$script:StartTime = (Get-Date).AddSeconds($TotalTime)
#Start the timer
$timer1.Start()
}
$label1.Location = New-Object System.Drawing.Size(220,60)
$label1.Size = New-Object System.Drawing.Size(500,30)
$label2.Text = "The Process Will Continue in 10s"
$label2.Location = New-Object System.Drawing.Size(140,30)
$label2.Size = New-Object System.Drawing.Size(500,30)
$form1.SuspendLayout()
$form1.Controls.Add($label1)
$form1.Controls.Add($label2)
$form1.Controls.Add($Cancel)
$form1.Width = 500
$form1.Height = 200
$form1.StartPosition = "CenterScreen"
$form1.BackColor = "#e2e2e2"
$form1.add_Load($form1_Load)
$Cancel.DialogResult = 'Cancel'
$Cancel.Location = New-Object System.Drawing.Size(350,100)
$Cancel.Size = New-Object System.Drawing.Size(100,30)
$Cancel.Text = "Pause"
$Cancel.add_Click({ $Global:formresult = 20 })
$timer1.add_Tick($timer1_Tick)
$form1.ResumeLayout()
#Show the Form
return $form1.ShowDialog()
exit 100
}
#Call the form
Timer_GUI | Out-Null
$Global:formresult

Auto select listbox items from searchbox

I cant seem to figure out how to auto select an item in my listbox from a searchbox.
I get a write-host back that an item is in the listbox when I use the searchbox, but I would like to autoselect the item that I search for.
The searchbox looks for the item that has the text in it from the searchbox. When you press the find button, the console says if the item is in the list or not.
I tried a couple of things with $objListbox.SelectedIndex, but I got as far as only selecting the first item in the listbox
# Alle Variabelen
<#----------------------------------------------------------------------------#>
$reg_bestanden_dir = "\\dataasp01\d$\system\scripts\ADVIESBOX\adviesbox_update_release\Productie\"
#$Listtxt = "\\dataasp01\d$\system\scripts\ADVIESBOX\adviesbox_update_release\script\Test.txt"
$count=1#>
$textBox1 = New-Object System.Windows.Forms.TextBox
$Find = New-Object System.Windows.Forms.Button
$regbestanden= Get-ChildItem $reg_bestanden_dir | where {$_.Attributes -ne 'Directory'} |select name
# Hoofd formulier
<#----------------------------------------------------------------------------#>
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Adviesbox Omgeving"
$objForm.Size = New-Object System.Drawing.Size(500,500)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{$x=$objListBox.SelectedItem;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$objForm.Close()}})
# Searchbox
<#----------------------------------------------------------------------------#>
$handler_Find_Click=
{
Foreach ($regbestand in $regbestanden)
{
if($regbestand -match $textbox1.Text)
{
#Select item in listbox
Write-Host "Item is in the list"
}
else
{
Write-Host "Item is not the same"
}
}
}
# Buttons
<#----------------------------------------------------------------------------#>
$StartenButton = New-Object System.Windows.Forms.Button
$StartenButton.Location = New-Object System.Drawing.Size(25,400)
$StartenButton.Size = New-Object System.Drawing.Size(75,23)
$StartenButton.Text = "Starten"
$StartenButton.Add_Click({$x=$objListBox.SelectedItem; Starten})
$objForm.Controls.Add($StartenButton)
$UpdateButton = New-Object System.Windows.Forms.Button
$UpdateButton.Location = New-Object System.Drawing.Size(150,400)
$UpdateButton.Size = New-Object System.Drawing.Size(75,23)
$UpdateButton.Text = "Update"
$UpdateButton.Add_Click({$x=$objListBox.SelectedItem; Updaten})
$objForm.Controls.Add($UpdateButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(275,400)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
# GUI boxen
<#----------------------------------------------------------------------------#>
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(190,20)
$objLabel.Text = "Selecteer een Adviesbox Omgeving:"
$objForm.Controls.Add($objLabel)
$objListBox = New-Object System.Windows.Forms.ListBox
$objListBox.Location = New-Object System.Drawing.Size(20,40)
$objListBox.Size = New-Object System.Drawing.Size(400,20)
$objListBox.Height = 350
$countListBox = New-Object System.Windows.Forms.ListBox
$countListBox.Location = New-Object System.Drawing.Size (200,18)
$countListBox.Size = New-Object System.Drawing.Size (30,25)
$objForm.Controls.Add($countListBox)
$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 15
$textBox1.Location = $System_Drawing_Point
$textBox1.Name = "textBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 120
$textBox1.Size = $System_Drawing_Size
$textBox1.TabIndex = 0
$objForm.Controls.Add($textBox1)
<# Autocomplete deels werkend
----------------------------------------------------------------------------
$textBox1.AutoCompleteSource = 'CustomSource'
$textBox1.AutoCompleteMode = 'SuggestAppend'
$textBox1.AutoCompleteCustomSource = $autocomplete
Get-Content $Listtxt | % {$textbox1.AutoCompleteCustomSource.AddRange($_)}
#>
$Find.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 375
$System_Drawing_Point.Y = 15
$Find.Location = $System_Drawing_Point
$Find.Name = "Find"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 50
$Find.Size = $System_Drawing_Size
$Find.TabIndex = 1
$Find.Text = "Find"
$Find.UseVisualStyleBackColor = $True
$Find.add_Click($handler_Find_Click)
$objForm.Controls.Add($Find)
# Functies
<#----------------------------------------------------------------------------#>
Function Starten
{
Set-Location -Path $reg_bestanden_dir
reg import $objListBox.SelectedItem
#invoke-item $adviesb0x
}
Function Updaten
{
Invoke-Item $objListBox.SelectedItem
}
# Warning box voor de juiste omgeving
<#----------------------------------------------------------------------------#>
<#$objListbox.add_SelectedIndexChanged(
{
[System.Windows.MessageBox]::Show($objlistBox.SelectedItem, "Omgeving:")
}
)#>
# Laat alle omgevingen zien in de listbox
<#----------------------------------------------------------------------------#>
<# foreach ($regbestand in $regbestanden) {
$regbestand.name
}#>
$regbestanden | ForEach-Object {
[void] $objListBox.Items.Add($_.name)
}
# Telt de aantal omgevingen (teller)
<#----------------------------------------------------------------------------#>
$countListBox.Items.Add($regbestanden.count)
$objForm.Controls.Add($objListBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
$x
<#Backup#>
#https://technet.microsoft.com/en-us/library/ff730949.aspx
#Get-Content $Listtxt | ForEach-Object {[void] $objListBox.Items.Add($_)}
#$objForm.WindowState = [System.Windows.Forms.FormWindowState]::Minimized
<#Set-Location -Path "\\dataasp01\d$\system\scripts\ADVIESBOX\adviesbox_update_release\Productie\"
Write-Host "Item is in list"
$findeditems = Get-ChildItem $objListBox.Items | where {$objListbox.Items -eq $textbox1.Text}
$objListbox.Items.Add($findeditems)#>
$handler_Find_Click=
{
Foreach ($regbestand in $regbestanden)
{
For ($i = 0; $i -lt $objListBox.Items.Count; $i++) {
if($regbestand -match $objListBox.Items[$i])
{
$objListBox.SetSelected($i, $True)
Write-Host "Item is in the list"
}
else
{
Write-Host "Item is not the same"
}
}
}
}
I am not sure whether you want multiple items selected in the ListBox (depending on the SelectionMode) but you might have to deselect them first:
For ($i = 0; $i -lt $objListBox.Items.Count; $i++) {
$objListBox.SetSelected($i, $False)
}