I'm lost and could really use some help. I'm trying to update a combo box with a list of column names from a csv file (selected by the open file button, and string input into textbox).
Function GetFileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.multiselect = $false
$OpenFileDialog.ShowDialog() | Out-Null
return $OpenFileDialog.FileName
}
Function GetColumnsFromFile
{
Param ($fileWithPath)
[string]$csvFileColumnTitles = Get-Content $fileWithPath -totalcount 1
[String[]]$csvFileColumnTitles = ($csvFileColumnTitles -replace ",", "|").Trim()
[String[]]$csvFileColumnTitles = ($csvFileColumnTitles -replace "`"", "").Trim()
[String[]]$listOfColumnTitles = $csvFileColumnTitles.Split('|',[System.StringSplitOptions]::RemoveEmptyEntries)
return $listOfColumnTitles
}
Function GUIBox
{
# Creates GUI Box In Memory
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.drawing
$Form = New-Object system.Windows.Forms.Form
$Form.Width = '1200'
$Form.Height = '800'
# TabControl
$TabControl = New-Object System.Windows.Forms.TabControl
$TabControl.Name = "TabControl"
$TabControl.TabIndex = 4
$TabControl.SelectedIndex = 0
$TabControl.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 50
$TabControl.Location = $System_Drawing_Point
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 685
$System_Drawing_Size.Width = 1184
$TabControl.Size = $System_Drawing_Size
$Form.Controls.Add($TabControl)
# Test 1 Tab
$Test1_Tab = New-Object System.Windows.Forms.TabPage
$Test1_Tab.DataBindings.DefaultDataSourceUpdateMode = 0
$Test1_Tab.Name = "Test 1"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 50
$Test1_Tab.Location = $System_Drawing_Point
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 685
$System_Drawing_Size.Width = 1184
$Test1_Tab.Size = $System_Drawing_Size
$Test1_Tab.TabIndex = 1
$Test1_Tab.Text = "Test 1"
$Test1_Tab.UseVisualStyleBackColor = $True
$TabControl.Controls.Add($Test1_Tab)
# Open File Label
$SelectSourceFile_Label = New-Object System.Windows.Forms.Label
$SelectSourceFile_Label.Location = "10, 30"
$SelectSourceFile_Label.Name = "label"
$SelectSourceFile_Label.Size = "120, 20"
$SelectSourceFile_Label.TabIndex = 3
$SelectSourceFile_Label.Text = "Select Source File"
$Test1_Tab.Controls.Add($SelectSourceFile_Label)
# Open File Textbox
$SelectSourceFile_Textbox = New-Object System.Windows.Forms.TextBox
$SelectSourceFile_Textbox.Location = '10, 50'
$SelectSourceFile_Textbox.Size = '200, 20'
$SelectSourceFile_Textbox.TabIndex = 3
$SelectSourceFile_Textbox.Text = $Test1_FileInput_Textbox_String
$Test1_Tab.Controls.Add($SelectSourceFile_Textbox)
# Open File Button
$SelectSourceFile_Button = New-Object System.Windows.Forms.Button
$SelectSourceFile_Button.DialogResult = 'None'
$SelectSourceFile_Button.Location = '210, 50'
$SelectSourceFile_Button.Name = 'Open File Button'
$SelectSourceFile_Button.Size = '75, 25'
$SelectSourceFile_Button.TabIndex = 3
$SelectSourceFile_Button.Text = 'Open File'
$SelectSourceFile_Button.UseVisualStyleBackColor = $true
$SelectSourceFile_Button_Click = {$SelectSourceFile_Textbox.Text = GetFileName}
$SelectSourceFile_Button.add_Click($SelectSourceFile_Button_Click)
$Test1_Tab.Controls.Add($SelectSourceFile_Button)
# Select Open File Columns Label
$SelectSourceFileColumn_Label = New-Object System.Windows.Forms.Label
$SelectSourceFileColumn_Label.Location = "10, 90"
$SelectSourceFileColumn_Label.Name = "label"
$SelectSourceFileColumn_Label.Size = "150, 20"
$SelectSourceFileColumn_Label.TabIndex = 3
$SelectSourceFileColumn_Label.Text = "Select Source File Column"
$Test1_Tab.Controls.Add($SelectSourceFileColumn_Label)
# Select Open File Columns Dropdown
[String[]]$ColumnList = GetColumnsFromFile 'C:\Scripts\Tests\1Project\Test.csv'
Write-Host '$ColumnList =' $ColumnList
$SelectSourceFileColumn_Dropdown = New-Object 'System.Windows.Forms.ComboBox'
$SelectSourceFileColumn_Dropdown.FormattingEnabled = $True
$SelectSourceFileColumn_Dropdown.Location = '10, 110'
$SelectSourceFileColumn_Dropdown.Name = 'File Column'
$SelectSourceFileColumn_Dropdown.Size = '200, 20'
$SelectSourceFileColumn_Dropdown.TabIndex = 3
$SelectSourceFileColumn_Dropdown.Height = 30
$Test1_Tab.Controls.Add($SelectSourceFileColumn_Dropdown)
## Display GUI Box ##
$Form.ShowDialog()
}
GUIBox
The csv file...
"ColumnOne","ColumnTwo","ColumnThree"
"ColumnOneValueOne","ColumnTwoValueOne","ColumnThreeValueOne"
"ColumnOneValueTwo","ColumnTwoValueTwo","ColumnThreeValueTwo"
"ColumnOneValueThree","ColumnTwoValueThree","ColumnThreeValueThree"
So in the powershell window, we can see it is able to print the 3 column names. I know if I try this line [String[]]$ColumnList = GetColumnsFromFile $SelectSourceFile_Textbox.Text (replacing line 110), it will error out (because it will iterate through this line, before the user has a chance to input the selected file). So how would I update the combobox (with column names from the csv file) after the user has input their csv file?
One way you could do this is to use the button click to show the FolderBrowserDialog and if you get a filename from it, get the headings and add each one to the combobox.
You can use the same technique to populate the ComboBox when the user types into the textbox by creating a TextChanged event.
I got this to work using the following code:
function GUIBox {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, 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('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$textbox1 = New-Object 'System.Windows.Forms.TextBox'
$combobox1 = New-Object 'System.Windows.Forms.ComboBox'
$buttonLoadCsv = New-Object 'System.Windows.Forms.Button'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.multiselect = $false
$OpenFileDialog.ShowDialog() | Out-Null
return $OpenFileDialog.FileName
}
$form1_Load={
#TODO: Initialize Form Controls here
}
$buttonLoadCsv_Click={
#TODO: Place custom script here
$file = Get-FileName -initialDirectory $env:USERPROFILE
if ($file)
{
$textbox1.Text = $file
try
{
$headers = Import-Csv -Path $file | Get-Member | Where-Object -FilterScript {$_.MemberType -eq 'NoteProperty'} | Select-Object -ExpandProperty Name -Unique
Write-Host ($headers | Out-String)
$combobox1.Items.Clear()
foreach($header in $headers)
{
$combobox1.Items.Add($header)
}
}
catch
{
Write-Warning -Message "The following error occured while trying to get the headings for csv file $file`: $($_.Exception.Message)"
}
}
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$buttonLoadCsv.remove_Click($buttonLoadCsv_Click)
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($textbox1)
$form1.Controls.Add($combobox1)
$form1.Controls.Add($buttonLoadCsv)
$form1.ClientSize = '390, 76'
$form1.Name = 'form1'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
#
# textbox1
#
$textbox1.Location = '12, 14'
$textbox1.Name = 'textbox1'
$textbox1.Size = '284, 20'
$textbox1.TabIndex = 2
#
# combobox1
#
$combobox1.DropDownStyle = 'DropDownList'
$combobox1.FormattingEnabled = $True
$combobox1.Location = '12, 40'
$combobox1.Name = 'combobox1'
$combobox1.Size = '284, 21'
$combobox1.TabIndex = 1
#
# buttonLoadCsv
#
$buttonLoadCsv.Location = '302, 12'
$buttonLoadCsv.Name = 'buttonLoadCsv'
$buttonLoadCsv.Size = '75, 49'
$buttonLoadCsv.TabIndex = 0
$buttonLoadCsv.Text = 'Load Csv'
$buttonLoadCsv.UseVisualStyleBackColor = $True
$buttonLoadCsv.add_Click($buttonLoadCsv_Click)
$form1.ResumeLayout()
#endregion Generated Form Code
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
#Call the form
GUIBox | Out-Null
Related
I’m trying to create a form which contains a message where I want to use some data imported from a CSV file.
The script will read the CSV rows and print a message that will contain data from it.
The issue is that the variables inside message textbox is not used instead a plain text is filled.
I think that this is related to System.Windows.Forms.TextBox but I can't figure it out
Any idea how I can resolve this?
Regards,
Adrian
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName PresentationFramework
function show_menu {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$form = New-Object System.Windows.Forms.Form
$form.Text = 'menu'
$form.Size = New-Object System.Drawing.Size(630,370)
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = 'FixedSingle'
#$form.Icon = [System.Drawing.Icon]::FromHandle((New-Object System.Drawing.Bitmap -Argument $stream).GetHIcon())
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(200,295)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Add_Click({
$form.Tag = $textBox_recipient.Text;
$form.Tag = $textBox_message.Text;
$form.Close()
})
$form.AcceptButton = $okButton
$form.Controls.Add($okButton)
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(355,295)
$cancelButton.Size = New-Object System.Drawing.Size(75,23)
$cancelButton.Text = 'Cancel'
$cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $cancelButton
$form.Controls.Add($cancelButton)
$textBox_recipient = New-Object System.Windows.Forms.TextBox
$textBox_recipient.Location = New-Object System.Drawing.Point(210,70)
$textBox_recipient.Size = New-Object System.Drawing.Size(245, 20)
$textBox_recipient.ReadOnly = $true
$form.Controls.Add($textBox_recipient)
##
$textBox_recipient_select = New-Object System.Windows.Forms.Button
$textBox_recipient_select.Location = New-Object System.Drawing.Point(460, 70)
$textBox_recipient_select.Size = New-Object System.Drawing.Size(100, 20)
$textBox_recipient_select.Text = "Select CSV file"
$textBox_recipient_select.add_Click({
$ofd = New-Object system.windows.forms.Openfiledialog
#$ofd.Filter = 'Supported file types (*.csv,*.xlsx)|*.csv,*.xlsx'
$ofd.Filter = 'Supported file types (*.csv, *.xlsx)|*.csv; *.xlsx| All (*.*)|*.*'
$script:recipient_filename = 'Not found'
if ($ofd.ShowDialog() -eq 'Ok') {
$script:recipient_filename = $textbox_recipient.Text = $ofd.FileName
}
})
#$textBox_recipient.Text = "C:\Users\Ady\Desktop\test.csv"
$form.Controls.Add($textBox_recipient_select)
$label_message = New-Object System.Windows.Forms.Label
$label_message.Location = New-Object System.Drawing.Point(10,150)
$label_message.Size = New-Object System.Drawing.Size(200,20)
$label_message.BackColor = [System.Drawing.Color]::FromName("Transparent")
$label_message.Font = [System.Drawing.Font]::new("Microsoft Sans Serif", 10, [System.Drawing.FontStyle]::Bold)
$label_message.Text = 'Message:'
$form.Controls.Add($label_message)
$textBox_message = New-Object System.Windows.Forms.TextBox
$textBox_message.Multiline = $True
$textBox_message.Scrollbars = "Vertical"
$textBox_message.Location = New-Object System.Drawing.Point(210,150)
$textBox_message.Size = New-Object System.Drawing.Size(350, 135)
$textBox_message.Text = "Insert your text here. HTML format supported"
$form.Controls.Add($textBox_message)
$form.Topmost = $true
$form.Add_Shown({ $textBox_recipient.Select(),$textBox_message.Select() })
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
$script:filename = "$(($textBox_recipient).Text)"
$recipients = Import-csv -Path "$filename"
$total_recipient_nr = get-content "$filename" | select-string "#" | measure-object -line
$recipient_nr = 0
foreach ($recipient in $recipients) {
if (++$recipient_nr % 31 -eq 0)
{
Start-Sleep -Seconds 30
echo "waiting 1 minute"
}
$script:user_email = $recipient.email
$script:user_firstname = $recipient.firstname
$script:user_lastname = $recipient.lastname
$script:user_code = $recipient.code
$script:message = $textBox_message.Text
Write-Host $message
}
}
}
show_menu
For example, the following csv:
firstname, lastname, email, code ---- header of csv file
firstname1, lastname1, email1#domain, code1
firstname2, lastname2, email2#domain, code2
What I want to do is to use variables like $user_email, $user_code inside "$textBox_message.Text" field of the form and for each line of the CSV file, the message to use the value of those variables. (recipient is a row from the csv file that contains different values at each foreach run)
$script:user_firstname = $recipient.firstname
$script:user_code = $recipient.code
$script:message = $textBox_message.Text
I run the script, the form appears and I replace the default text "Insert your text here. HTML format supported" of $textBox_message.Text with the following:
Hi $user_firstname. This is your code: $user_code
The result (value of $message var) by executing line 96, should be:
Hi firstname1. This is your code: code1 - at first run of foreach loop
and
Hi firstname2. This is your code: code2 - at second run of foreach loop
Instead, the result is:
Hi $user_firstname. This is your code: $user_code --- plain text (the value) of $message
This is from what I have observed from Powershell when trying to writing a simple string with variables:
if you use single quotes i.e.
$firstName = "John"
write-host 'First name is $firstName'
The output is going to be:
First name is $firstName
However if you use double quotes, you should get the variable value instead of variable being displayed as plain text. i.e.
$firstName = "John"
write-host "First name is $firstName" or write-host "First name is $($firstName)"
you should get the desired output:
First name is John
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.
I am using code to open and view an XML file in datagridview, but the rows and columns are not already open like they are in excel.
I have been searching the internet for answers on how to have the data already presented like it would be in excel, but have not been able to find how to do this.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
[Void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
[Void][reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[Void][System.Windows.Forms.Application]::EnableVisualStyles()
#Open File Dialog
Function Get-FileName($initialDirectory){
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "XML (*.xml)| *.xml"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
#Save File Dialog
Function Save-FileName($initialDirectory){
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "XML (*.xml)| *.xml"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
#Create Form Functions
function Create-Form {
# Draw Form
$form1 = New-Object System.Windows.Forms.Form
$form1.ClientSize = New-Object System.Drawing.Size(725,400)
$form1.Text = "XML to DataGrid Editor"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.FormBorderStyle = 5
# Draw DataGrid
$dataGrid1 = New-Object System.Windows.Forms.DataGrid
$dataGrid1.Size = New-Object System.Drawing.Size(700,338)
$dataGrid1.Location = New-Object System.Drawing.Point (13,13)
$dataGrid1.DataBindings.DefaultDataSourceUpdateMode = 0
$dataGrid1.HeaderForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
$dataGrid1.Name = "dataGrid1"
$dataGrid1.DataMember = ""
$dataGrid1.TabIndex = 0
$form1.Controls.Add($dataGrid1)
# Draw Open xml Configuration Button
$button_openxml = New-Object System.Windows.Forms.Button
$button_openxml.Size = New-Object System.Drawing.Size(150,25)
$button_openxml.Location = New-Object System.Drawing.Point(13,365)
$button_openxml.Text = "Open XML Document"
$button_openxml.Add_Click({
$xml_networkschema = Get-FileName
# Bind Data to DataGrid
$ds = New-Object System.Data.Dataset
$ds.ReadXml($xml_networkschema)
$dataGrid1.DataSource = $ds
})
$form1.Controls.Add($button_openxml)
# Save xml Configuration Button
$button_savexml = New-Object System.Windows.Forms.Button
$button_savexml.Size = New-Object System.Drawing.Size(150,25)
$button_savexml.Location = New-Object System.Drawing.Point(170,365)
$button_savexml.Text = "Save XML Document"
$button_savexml.enabled = "false"
$button_savexml.Add_Click({
$dbm_savenetworkschema = Save-FileName
$dataGrid1.DataSource.writexml($dbm_savenetworkschema)
})
$form1.Controls.Add($button_savexml)
$form1.ShowDialog()| Out-Null
}
Create-Form
what the display should like
I don't understand why my GroupBox isn't displayed.
I would like to display groupbox with several labels but it doesn't work.
I've tried to replace the radiobuttons by labels with the code here => https://sysadminemporium.wordpress.com/2012/12/07/powershell-gui-for-your-scripts-episode-3/
I'm a beginner in GUI and I have seen other examples but I can't use this code as I would like.
Here is my code :
#----------------------------------------------
# Generated Form Function
#----------------------------------------------
function Call-test_psf {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$form1.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$form1.MaximizeBox = $False
$form1.MinimizeBox = $False
# Choix du titre
$form1.Text = "Title"
$label4 = New-Object 'System.Windows.Forms.Label'
$label5 = New-Object 'System.Windows.Forms.Label'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$form1_Load={
#TODO: Initialize Form Controls here
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$buttonSuivant.remove_Click($buttonSuivant_Click)
$buttonRetour.remove_Click($buttonRetour_Click)
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($groupBox1)
$form1.ClientSize = '700, 300'
#endregion
$form1.Name = 'form1'
$form1.Text = 'Title'
$form1.add_Load($form1_Load)
#
# GroupBox1
#
$groupBox1 = New-Object System.Windows.Forms.GroupBox
$groupBox1.Location = '150,300'
$groupBox1.size = '400,150'
$groupBox1.text = "Title groupBox1"
$groupBox1.Visible = $true
#
# progressBar1
#
$progressBar1 = New-Object System.Windows.Forms.ProgressBar
$progressBar1.Name = 'progressBar1'
$progressBar1.Value = 0
$progressBar1.Style="Continuous"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = $width - 40
$System_Drawing_Size.Height = 20
$progressBar1.Size = $System_Drawing_Size
$progressBar1.Left = 5
$progressBar1.Top = 40
#
# label4
#
$label4.Font = 'Microsoft Sans Serif, 8pt'
$label4.Location = '50, 50'
$label4.Name = 'label2'
$label4.Size = '20, 20'
$label4.TabIndex = 8
$label4.TextAlign = 'TopLeft'
$label4.Visible = $false
$label4.Text = "test"
#
# label5
#
$label5.Font = 'Microsoft Sans Serif, 8pt'
$label5.Location = '50, 70'
$label5.Name = 'label2'
$label5.Size = '20, 20'
$label5.TabIndex = 10
$label5.TextAlign = 'TopLeft'
$label5.Visible = $false
$label5.Text = "test"
$groupBox1.Controls.AddRange(#($Label4,$Label5))
#
$form1.ResumeLayout()
#endregion Generated Form Code
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
#Call the form
Call-test_psf | Out-Null
Can you help me ?
Thank you in advance.
Change 2 lines:
$groupBox1.Location = '150,300'
y location is 300, which is off the bottom of your form as it's only 300px high.
$form1.Controls.Add($groupBox1)
Move this line to after you have created the groupbox. So anywhere after $groupBox1 = New-Object System.Windows.Forms.GroupBox
For example:
$groupBox1 = New-Object System.Windows.Forms.GroupBox
$groupBox1.Location = '10,10'
$groupBox1.size = '400,150'
$groupBox1.text = "Title groupBox1"
$groupBox1.Visible = $true
$form1.Controls.Add($groupBox1) # line moved here.
I folks,
I've try my best to handle a LDAP query on a button click, but I can get the dropdown2.text to search a name instead I put the complet name like "smith, peter".
What I want is, if I put any of first name or Last name in the "Manager" field, the click button will searh and return me all the corresponding value in Active Directory event if it's a name or a family name. I'm not far, but I can't find where is my mistake
function GenerateForm {
set-Location c:\
add-PSSnapin quest.activeroles.admanagement
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$searchldap = New-Object System.Windows.Forms.Button
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel2 = new-object System.Windows.Forms.Label
$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown2 = new-object System.Windows.Forms.ComboBox
#Handler
$handler_searchldap_click=
{
$manager = ""
$dropdown2.items.clear()
$manager = get-aduser -f {name -like $dropdown2.text}
foreach ($thing in $manager){
$useraccountname = $thing.name
$DropDown2.Items.Add($useraccountname) | Out-Null
}
}
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#----------------------------------------------
#region Generated Form Code
$form1.Text = "User Creation software"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 400
$System_Drawing_Size.Height = 200
$form1.ClientSize = $System_Drawing_Size
$DropDownArray = "Site1" , "Site2" , "Site3"
$DropDown2.Location = new-object System.Drawing.Size(125,80)
$DropDown2.Size = new-object System.Drawing.Size(150,27)
$dropdown2.DataBindings.DefaultDataSourceUpdateMode = 0
$dropdown2.TabIndex = 5
$dropdown2.Name = "dropdown2"
$DropDown2.add_TextUpdate({ Write-Host "TextUpdate. Updated text is: $($Dropdown2.Text)" })
$Form1.Controls.Add($DropDown2)
$DropDownLabel2 = new-object System.Windows.Forms.Label
$DropDownLabel2.Location = new-object System.Drawing.Size(50,80)
$DropDownLabel2.size = new-object System.Drawing.Size(50,27)
$DropDownLabel2.Text = "Manager:"
$Form1.Controls.Add($DropDownLabel2)
$DropDown.Location = new-object System.Drawing.Size(125,55)
$DropDown.Size = new-object System.Drawing.Size(150,27)
$dropdown.DataBindings.DefaultDataSourceUpdateMode = 0
$dropdown.TabIndex = 4
$dropdown.Name = "dropdown1"
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(50,58)
$DropDownLabel.size = new-object System.Drawing.Size(50,27)
$DropDownLabel.Text = "Location:"
$Form1.Controls.Add($DropDown)
$Form1.Controls.Add($DropDownLabel)
ForEach ($Item in $DropDownArray) {
$DropDown.Items.Add($Item) | Out-Null
}
###Button section
$searchldap.Location = New-Object System.Drawing.Size(275,80)
$searchldap.Size = New-Object System.Drawing.Size(100,20)
$searchldap.Text = "Search"
$searchldap.Add_Click($handler_searchldap_click)
$Form1.Controls.Add($searchldap)
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #end of function
GenerateForm
Try this:
$filter = [scriptblock]::Create("Name -like '*$($dropdown2.text)*'")
$manager = get-aduser -f $filter
Powershell does not expand local variables used in filter script blocks before it passes them to the DC (via the AD Gateway Service). To get around that, create the filter script block from an expandable string