Contenidos
- Introducción
- Componentes
- Ventana (Window)
- Formulario (Form)
- Etiqueta (Label)
- Etiqueta de enlace (LinkLabel)
- Botón (Button)
- Caja de texto (TextBox)
- Casilla de verificación (CheckBox)
- Cuadro combinado (ComboBox)
- Selector de fecha y hora (DateTimePicker)
- Cuadro de lista (ListBox)
- Vista de lista (ListView)
- Calendario mensual (MonthCalendar)
- Cuadro de imagen (PictureBox)
- Barra de progreso (ProgressBar)
- Botón de opción (RadioButton)
- Cuadro de texto enriquecido (RichTextBox)
- Barra de estado (StatusStrip)
- Caja de texto (TextBox)
- Contenedores
- Gestores de posiciones
- Eventos
- Ejemplos
- Crear un botón y añadir un evento que cuando se haga click en el botón aparezca un mensaje de «Estoy pulsando»
- Crear un formulario, añadir una etiqueta, un botón y una caja de texto, el usuario escribe un texto en la caja de texto y pulsa Enter, en ese caso el texto escrito en la caja de texto aparecerá en la consola de PowerShell, también puede pulsar la tecla ESC, en ese caso saldrá del formulario
- Ejercicios
- Ejemplos
- Dibujos
- Ejemplos
- Ejercicios
- Dibujar una casa en PowerShell
- Dibujar un texto dentro de un objeto Bitmap
- Añadir una marca de agua a una imagen
- Añadir una marca de agua a varias imágenes
- Crear un objeto Bitmap y guardar una captura de la pantalla dentro del mismo
- Crear un formulario con un botón que al pulsarlo realiza una captura de pantalla cinco segundos después
- Realizar una captura de pantalla mediante una interfaz gráfica creada con PowerShell
- Realizar una miniatura de una imagen
- Detectar el color de un pixel de una captura de pantalla
- Comparar dos imágenes con PowerShell indicando el momento en el que empieza la diferencia
- Comparar dos imágenes con PowerShell mostrando la diferencia
- Extraer coordenadas GPS de imágenes con PowerShell
- Más información
- Automatización
Introducción
Elementos que componen las interfaces de usuario:
- Componentes como los botones, cajas de texto, etc.
- Contenedores
- Gestores de posiciones
- Eventos
- Dibujos
Componentes
La gestión de componentes se realiza mediante varias clases .NET.
Existen varias formas de gestionar interfaces de usuario, mediante los espacios de nombres:
- System.Windows: proporciona varias clases de elementos base importantes de Windows Presentation Foundation (WPF).
- System.Windows.Forms: contiene clases para crear aplicaciones para Windows que aprovechan todas las ventajas de las características de la interfaz de usuario enriquecida disponibles en el sistema operativo Microsoft Windows.
Ventana (Window)
Si se quiere trabajar con ventanas hay que utilizar la clase System.Windows.Window que brinda la capacidad de crear, configurar, mostrar y administrar la vida útil de ventanas y cuadros de diálogo.
Ejemplo
Crear una ventana
1 2 3 4 5 6 | ( [System.Windows.Window]@{ Title = 'Mi ventana' Background = [System.Windows.Media.Brushes]::Red } ).ShowDialog() |
Ejercicio
Crear una Windows Presentation Foundation (WPF) ventana en PowerShell de forma simple y sencilla
1 2 3 4 5 6 7 | ($window = [System.Windows.Window] @{ Title = "Mi formulario" Height = 200 Width = 400 WindowStartupLocation = [System.Windows.WindowStartupLocation]::CenterScreen Background = [System.Windows.Media.Brushes]::Red }).ShowDialog() |

Más información
- https://www.jesusninoc.com/07/08/crear-aplicaciones-wpf-parte-1/
- https://www.jesusninoc.com/07/09/crear-aplicaciones-wpf-parte-2/
- https://www.jesusninoc.com/07/10/crear-aplicaciones-wpf-parte-3/
- https://www.jesusninoc.com/09/11/crear-aplicaciones-wpf-parte-4/
- https://www.jesusninoc.com/02/12/enviar-una-ventana-mediante-el-protocolo-udp-de-un-ordenador-a-otro-desde-powershell-hacerlo-de-forma-simple-y-sencilla/
- https://www.jesusninoc.com/02/27/cargar-un-formulario-contenido-en-un-fichero-json-desde-powershell/
Formulario (Form)
Un formulario representa una ventana o un cuadro de diálogo que constituye la interfaz de usuario de una aplicación.
Ejemplo
Crear un formulario (dos posibles formas de crearlo que hacen lo mismo)
1.
1 2 | $Form = New-Object System.Windows.Forms.Form $Form.ShowDialog() |
2.
1 2 3 4 5 | ( [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } ).ShowDialog() |
Más información
- https://www.jesusninoc.com/11/09/crear-formularios-parte-1/
- https://www.jesusninoc.com/02/25/crear-formularios-parte-2/
- https://www.jesusninoc.com/03/03/crear-formularios-parte-3/
- https://www.jesusninoc.com/02/03/crear-una-aplicacion-grafica-en-powershell-que-represente-un-piano-con-las-notas-del-do-a-si-y-que-suene-cada-nota/
- https://www.jesusninoc.com/02/03/crear-formulario-dentro-de-otro-formulario-mediante-una-funcion-con-powershell/
- https://www.jesusninoc.com/02/01/convertir-un-script-de-powershell-en-un-ejecutable-de-windows-convertir-un-formulario-en-powershell/
Etiqueta (Label)
Representa una etiqueta estándar de Windows.
Ejemplo
Crear un componente de tipo etiqueta y añadirlo a un formulario
1 2 3 4 5 6 7 8 9 10 11 | $Label = [System.Windows.Forms.Label]@{ text = "Etiqueta de ejemplo" AutoSize = $True } $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $Form.Controls.Add($Label) $Form.ShowDialog() |
Etiqueta de enlace (LinkLabel)
Representa un control de etiqueta de Windows que puede mostrar hipervínculos.
Ejemplo
Crear un componente de tipo etiqueta de enlace y añadirlo a un formulario
1 2 3 4 5 6 7 8 9 10 11 12 13 | $LinkLabel = [System.Windows.Forms.LinkLabel]@{ text = "Etiqueta de ejemplo" AutoSize = $True } $LinkLabel.add_Click({[system.Diagnostics.Process]::start("http://www.jesusninoc.com")}) $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $Form.Controls.Add($LinkLabel) $Form.ShowDialog() |
Botón (Button)
Representa un control de botón de Windows.
Ejemplo
Crear un componente de tipo botón y añadirlo a un formulario
1 2 3 4 5 6 7 8 9 | $form = [System.Windows.Forms.Form] @{ Text = 'Mi formulario' } $button = [System.Windows.Forms.Button] @{ Text = 'Pulsar' Dock = 'Fill' } $form.Controls.Add($button) $form.ShowDialog() |
Ejercicios
Crear un formulario con un botón en PowerShell de forma simple y sencilla
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using assembly System.Windows.Forms using namespace System.Windows.Forms $form = [Form] @{ Text = 'Mi formulario' } $button = [Button] @{ Text = 'Pulsar' Dock = 'Fill' } $button.add_Click{ $form.Close() } $form.Controls.Add($button) $form.ShowDialog() |
Añadir botones a un formulario en PowerShell de forma automática
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | $buttons_functionslist=@( "Botón1", "Botón2", "Botón3" "Botón4" "Botón5" ) $buttons_functionbuttoncount = $buttons_functionslist.count $loop = 0 #Formulario $Form = New-Object System.Windows.Forms.Form $Form.Text="Formulario" $Form.Size=New-Object System.Drawing.Size(500,500) $Form.StartPosition="CenterScreen" while($loop -lt $buttons_functionbuttoncount) { $thisbutton = New-Object System.Windows.Forms.Button [string]$thisbuttonname = $buttons_functionslist[$loop] $thisbutton.Text = $thisbuttonname $thisbutton.size = New-Object System.Drawing.Size(100,20) $thisbutton.Location = New-Object System.Drawing.Size(200,(20*$loop+1)) $thisbutton.Add_Click({ Write-Host $this.Text }) $Form.Controls.Add($thisbutton) $loop += 1 } $Form.ShowDialog() |
Crear un formulario con dos botones (uno de los botones deshabilitado)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | using assembly System.Windows.Forms using namespace System.Windows.Forms $form = [Form] @{ Text = 'Mi formulario' } $button = [Button] @{ Text = 'Pulsar' Location = [System.Drawing.Size]::new(100,100) BackColor = '#CCCC99' } $button2 = [Button] @{ Text = 'No Pulsar' Location = [System.Drawing.Size]::new(100,200) Enabled = $false BackColor = '#99CC99' } $button.add_Click{ start cmd } $button2.add_Click{ start notepad } $form.Controls.Add($button) $form.Controls.Add($button2) $form.ShowDialog() |

Más información
- https://www.jesusninoc.com/06/17/ver-mediante-una-lista-de-botones-en-un-formulario-de-powershell-las-categorias-de-una-pagina-en-wordpress/
- https://www.jesusninoc.com/06/19/abrir-las-categorias-de-una-pagina-web-en-wordpress-que-se-listan-mediante-botones-en-un-formulario-de-powershell/
- https://www.jesusninoc.com/03/23/crear-un-formulario-con-botones-que-sean-los-numeros-del-1-al-9-y-cada-vez-que-se-pulsa-un-numero-se-anada-a-una-caja-de-texto-en-powershell/
Caja de texto (TextBox)
Representa un control de cuadro de texto de Windows.
Ejemplo
Crear un componente de tipo caja de texto y añadirlo a un formulario
1 2 3 4 5 6 7 8 | $form = [System.Windows.Forms.Form] @{ Text = 'Mi formulario' } $TextBox = [System.Windows.Forms.TextBox] @{ Text = "Texto de prueba" } $form.Controls.Add($TextBox) $form.ShowDialog() |
Casilla de verificación (CheckBox)
Representa un control CheckBox de Windows.
Ejemplo
Añadir una casilla de verificación a un formulario
1 2 3 4 5 6 7 8 9 10 | $CheckBox = [System.Windows.Forms.CheckBox]@{ text = "Opción 1" } $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $Form.Controls.Add($CheckBox) $Form.ShowDialog() |
Ejercicio
Añadir varias casillas de verificación a un formulario
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | $CheckBox_functionslist=@( "CheckBox1", "CheckBox2", "CheckBox3" "CheckBox4" "CheckBox5" ) $CheckBox_functionbuttoncount = $CheckBox_functionslist.count $loop = 0 #Formulario $Form = New-Object System.Windows.Forms.Form $Form.Text="Formulario" $Form.Size=New-Object System.Drawing.Size(500,500) $Form.StartPosition="CenterScreen" while($loop -lt $CheckBox_functionbuttoncount) { $thisCheckBox = New-Object System.Windows.Forms.CheckBox [string]$thisCheckBoxname = $CheckBox_functionslist[$loop] $thisCheckBox.Text = $thisCheckBoxname $thisCheckBox.size = New-Object System.Drawing.Size(100,20) $thisCheckBox.Location = New-Object System.Drawing.Size(200,(20*$loop+1)) $thisCheckBox.Add_Click({ Write-Host $this.Text }) $Form.Controls.Add($thisCheckBox) $loop += 1 } $Form.ShowDialog() |

Cuadro combinado (ComboBox)
Representa un control de cuadro combinado de Windows.
Ejercicio
Añadir un cuadro combinado con varias opciones a un formulario
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $textComboBox = @( "CheckBox1", "CheckBox2", "CheckBox3" "CheckBox4" "CheckBox5" ) $ComboBox = [System.Windows.Forms.ComboBox]@{ text = "Seleccionar" } foreach($elemento in $textComboBox) { $ComboBox.Items.Add($elemento) } $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $Form.Controls.Add($ComboBox) $Form.ShowDialog() |
Selector de fecha y hora (DateTimePicker)
Representa un control de Windows que permite al usuario seleccionar una fecha y una hora, y mostrarlas con un formato especificado.
Ejemplo
Crear un selecto de fecha y hora dentro de un formulario
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $form = [System.Windows.Forms.Form] @{ Text = 'Mi formulario' } $DatePicker = [System.Windows.Forms.DateTimePicker] @{ Width = "200" Location = "50, 10" } $TimePicker = [System.Windows.Forms.DateTimePicker] @{ Width = "200" Location = "50, 50" Format = [System.Windows.Forms.DateTimePickerFormat]::Custom CustomFormat = "HH:mm:ss" } $form.Controls.Add($DatePicker) $form.Controls.Add($TimePicker) $form.ShowDialog() |
Cuadro de lista (ListBox)
Representa un control de Windows para mostrar una lista de elementos.
Ejercicio
Crear un formulario con una ListBox (o cuadro de lista)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using assembly System.Windows.Forms using namespace System.Windows.Forms $form = [Form] @{ Text = 'Mi formulario' } $listBox = [ListBox] @{ Location = New-Object System.Drawing.Point(10,40) Size = New-Object System.Drawing.Size(260,40) Height = 150 } [void] $listBox.Items.Add('1') [void] $listBox.Items.Add('2') $button = [Button] @{ Text = 'Pulsar y mostrar elemento seleccionado' Size = New-Object System.Drawing.Size(260,40) } $button.add_Click{ Write-Host $listBox.SelectedItem $form.Close() } $form.Controls.Add($listBox) $form.Controls.Add($button) $form.ShowDialog() |

Vista de lista (ListView)
Representa un control de vista de lista de Windows, el cual muestra una colección de elementos que se pueden ver mediante una de vistas distintas.
Ejemplo
Crear un formulario con una vista de la lista distinta
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | $form = [System.Windows.Forms.Form] @{ Text = 'Mi formulario' Width = 400 Height = 400 } $datos = [System.Windows.Forms.ListViewItem] @{ Text = "1" } $datos.SubItems.Add('Pepito') $datos.SubItems.Add('Grillo') $ListView = [System.Windows.Forms.ListView] @{ View = 'Details' Width = 400 Height = 400 } $ListView.Columns.Add('Identificador') $ListView.Columns.Add('Nombre') $listView.Columns.Add('Apellido') $ListView.Items.AddRange(($datos)) $form.Controls.Add($ListView) [void] $form.ShowDialog() |
Calendario mensual (MonthCalendar)
Representa un control de Windows que permite al usuario seleccionar una fecha mediante una presentación del calendario mensual visual.
Ejemplo
Crear un formulario con un calendario mensual
1 2 3 4 5 6 7 8 9 10 11 | $form = [System.Windows.Forms.Form] @{ Text = 'Mi formulario' } $calendar = [Windows.Forms.MonthCalendar] @{ ShowTodayCircle = $false MaxSelectionCount = 1 } $form.Controls.Add($calendar) $form.ShowDialog() |
Cuadro de imagen (PictureBox)
Representa un control de cuadro de imagen de Windows para mostrar una imagen.
Ejemplo
Mostrar una imagen mediante un cuadro de imagen dentro de un formulario
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $form = [System.Windows.Forms.Form] @{ Text = 'Mi formulario' } $img = [System.Drawing.Image]::Fromfile((Get-Item '.\thumbnailimagen.bmp')) $PictureBox = [System.Windows.Forms.PictureBox] @{ SizeMode = "Autosize" Anchor = "Bottom, right" Image = $img } $form.controls.add($PictureBox) $form.ShowDialog() |

Barra de progreso (ProgressBar)
Representa un control de barra de progreso de Windows.
Ejemplo
Mostrar una barra de progreso dentro de un formulario
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $ProgressBar = [System.Windows.Forms.ProgressBar]@{ Step = 1 } $Timer = [System.Windows.Forms.Timer]@{ Interval = 100 } $Form.Controls.Add($ProgressBar) $timer1.add_tick($ProgressBar.PerformStep()) $timer1.Start() $Form.ShowDialog()| Out-Null |
Botón de opción (RadioButton)
Permite al usuario seleccionar una sola opción de un grupo de opciones cuando se combina con otros controles de botón de opción.
Ejemplo
Añadir un botón de opción a un formulario
1 2 3 4 5 6 7 8 9 10 | $RadioButton = [System.Windows.Forms.RadioButton]@{ text = "Opción 1" } $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $Form.Controls.Add($RadioButton) $Form.ShowDialog() |
Cuadro de texto enriquecido (RichTextBox)
Representa un control RichTextBox de Windows.
Ejemplo
Añadir un cuadro de texto enriquecido a un formulario
1 2 3 4 5 6 7 8 9 10 | $RichTextBox = [System.Windows.Forms.RichTextBox]@{ text = "Texto ejemplo" } $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $Form.Controls.Add($RichTextBox) $Form.ShowDialog() |
Barra de estado (StatusStrip)
Representa un control de barra de estado de Windows.
Ejemplo
Añadir una barra de estado a un formulario
1 2 3 4 5 6 7 8 9 | $StatusStrip = [System.Windows.Forms.StatusStrip]@{ } $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $Form.Controls.Add($StatusStrip) $Form.ShowDialog() |
Caja de texto (TextBox)
Representa un control de cuadro de texto de Windows.
Ejemplo
Añadir una caja de texto a un formulario
1 2 3 4 5 6 7 8 9 10 | $TextBox = [System.Windows.Forms.TextBox]@{ text = "Text" } $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $Form.Controls.Add($TextBox) $Form.ShowDialog() |
Contenedores
Un contendor se compone componentes, de esa forma se simplifica la tarea de colocar elementos en los interfaces.
Cuadro de grupo (GroupBox)
Representa un control Windows que muestra un marco alrededor de un grupo de controles con un título opcional.
Ejemplo
Añadir varios botones de opciones a un formulario
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' } $RadioButton1 = [System.Windows.Forms.RadioButton]@{ text = "Opción 1" Location = "20,20" } $RadioButton2 = [System.Windows.Forms.RadioButton]@{ text = "Opción 2" Location = "20,40" } $RadioButton3 = [System.Windows.Forms.RadioButton]@{ text = "Opción 2" Location = "20,60" } $GroupBox = [System.Windows.Forms.GroupBox]@{ Text = 'Opciones' Visible = $true } $GroupBox.Controls.Add($RadioButton1) $GroupBox.Controls.Add($RadioButton2) $GroupBox.Controls.Add($RadioButton3) $Form.Controls.Add($GroupBox) $Form.ShowDialog() |
Divisor (SplitContainer)
Representa un control que consta de una barra móvil que divide el área de presentación de un contenedor en dos paneles de tamaño variable.
Gestores de posiciones
Los elementos que forman parte de los formularios se tienen que ubicar dentro del formulario mediante una correcta gestión de las posiciones.
La posición de los componentes visuales es relativa al contendedor en el que se encuentra.
La coordenada 0,0 es la esquina superior izquierda del contenedor.
Ejemplo
Mostrar un formulario con componentes representados en distintas posiciones
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | $Form = [System.Windows.Forms.Form]@{ Text = 'Mi formulario' Size = "300,300" } $RadioButton1 = [System.Windows.Forms.RadioButton]@{ text = "Opción 1" Location = "20,20" } $RadioButton2 = [System.Windows.Forms.RadioButton]@{ text = "Opción 2" Location = "20,40" } $RadioButton3 = [System.Windows.Forms.RadioButton]@{ text = "Opción 3" Location = "20,60" } $RadioButton4 = [System.Windows.Forms.RadioButton]@{ text = "Opción 4" Location = "20,80" } $GroupBox1 = [System.Windows.Forms.GroupBox]@{ Text = 'Opciones' Visible = $true Location = "10,10" Size = "260,110" } $GroupBox1.Controls.Add($RadioButton1) $GroupBox1.Controls.Add($RadioButton2) $GroupBox1.Controls.Add($RadioButton3) $GroupBox1.Controls.Add($RadioButton4) $Form.Controls.Add($GroupBox1) $GroupBox2 = [System.Windows.Forms.GroupBox]@{ Text = 'Valoración' Visible = $true Location = "10,130" Size = "260,110" } $TextBox = [System.Windows.Forms.TextBox]@{ text = "Text" Location = "20,30" } $GroupBox2.Controls.Add($TextBox) $Form.Controls.Add($GroupBox2) $Form.ShowDialog() |

Eventos
Cuando se espera la realización de una acción por parte de un control, puede ser la acción de un usuario interactuando con la interfaz, un ejemplo sería pulsar un botón que cierra una ventana. Hay que especificar las acciones que se llevan a cabo por parte de los controles.
Algunos eventos que pueden tener los controles:
Ejemplos
Crear un botón y añadir un evento que cuando se haga click en el botón aparezca un mensaje de «Estoy pulsando»
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $form = [System.Windows.Forms.Form] @{ Text = 'Mi formulario' } $button = [System.Windows.Forms.Button] @{ Text = 'Pulsar' Dock = 'Fill' } function Hago-Click{ Write-Host "Estoy pulsando" } $button.add_click({Hago-Click}) $form.Controls.Add($button) $form.ShowDialog() |

Crear un formulario, añadir una etiqueta, un botón y una caja de texto, el usuario escribe un texto en la caja de texto y pulsa Enter, en ese caso el texto escrito en la caja de texto aparecerá en la consola de PowerShell, también puede pulsar la tecla ESC, en ese caso saldrá del formulario
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #Crear un formulario, añadir una etiqueta, un botón y una caja de texto #Funcionalidad para el formulario: #Pulsar la tecla Enter almacena en una variable el contenido de la caja de texto y se muestra #Pulsar la tecla Escape sale del formulario #Formulario $Form = New-Object System.Windows.Forms.Form $Form.Text="Formulario" $Form.Size=New-Object System.Drawing.Size(500,500) $Form.StartPosition="CenterScreen" #Etiqueta $Label=New-Object System.Windows.Forms.Label $Label.Text="Etiqueta de ejemplo" $Label.AutoSize=$True $Label.Location=New-Object System.Drawing.Size(160,160) #Botón $Button=New-Object System.Windows.Forms.Button $Button.Size=New-Object System.Drawing.Size(75,23) $Button.Text="Botón de ejmplo" $Button.Location=New-Object System.Drawing.Size(180,180) #Caja de texto $TextBox = New-Object System.Windows.Forms.TextBox $TextBox.Location = New-Object System.Drawing.Size(100,220) $TextBox.Size = New-Object System.Drawing.Size(260,20) #Funcionalidad para el formulario: #Pulsar la tecla Enter almacena en una variable el contenido de la caja de texto y se muestra #Pulsar la tecla Escape sale del formulario $Form.KeyPreview = $True $Form.Add_KeyDown({if ($_.KeyCode -eq "Enter"){$Var=$TextBox.Text;Write-Host $Var;$Form.Close()}}) $Form.Add_KeyDown({if ($_.KeyCode -eq "Escape"){$Form.Close()}}) #Añadir etiqueta $Form.Controls.Add($Label) #Añadir botón $Form.Controls.Add($Button) #Añadir caja de texto $Form.Controls.Add($TextBox) $Form.ShowDialog() |
Ejercicios
Crear una aplicación mediante en PowerShell que incremente y disminuya la frecuencia de sonido
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | # Formulario con sus botones (arriba, abajo, caja de texto) #Beep function #Generates simple tones on the speaker #Beep(Freq,Duration) #Beep(Frecuencia,Duración) #Freq: The frequency of the sound, in hertz #Duration: The duration of the sound, in milliseconds # Definición de componentes $form1 = New-Object System.Windows.Forms.Form $DownButton = New-Object System.Windows.Forms.Button $Upbutton = New-Object System.Windows.Forms.Button # Definición de formulario $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 262 $System_Drawing_Size.Width = 284 $form1.ClientSize = $System_Drawing_Size $form1.DataBindings.DefaultDataSourceUpdateMode = 0 $form1.Name = "formulario" $form1.Text = "Beep" # Definición de botón - $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 224 $System_Drawing_Point.Y = 104 $DownButton.Location = $System_Drawing_Point $DownButton.Name = "-" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 34 $System_Drawing_Size.Width = 48 $DownButton.Size = $System_Drawing_Size $DownButton.TabIndex = 2 $DownButton.Text = "-" $DownButton.UseVisualStyleBackColor = $True $DownButton.add_Click($handler_DownButton_Click) # Añadir botón al formulario $form1.Controls.Add($DownButton) # Definición de botón + $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 224 $System_Drawing_Point.Y = 48 $Upbutton.Location = $System_Drawing_Point $Upbutton.Name = "+" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 34 $System_Drawing_Size.Width = 48 $Upbutton.Size = $System_Drawing_Size $Upbutton.TabIndex = 1 $Upbutton.Text = "+" $Upbutton.UseVisualStyleBackColor = $True $Upbutton.add_Click($handler_UpButton_Click) # Añadir botón al formulario $form1.Controls.Add($Upbutton) # Definición de caja de texto con valor por defecto $TextBox = New-Object System.Windows.Forms.TextBox $TextBox.Location = New-Object System.Drawing.Size(100,220) $TextBox.Size = New-Object System.Drawing.Size(50,20) $TextBox.Text = 37 # Añadir cada de texto $form1.Controls.Add($TextBox) # Mostrar el formulario $form1.ShowDialog() # Programar qué hacer cuando se pulsa el + o el - $handler_DownButton_Click= { if([Int]$TextBox.Text -in 37..32766) { [System.Console]::Beep([Int]$TextBox.Text,200) $TextBox.Text = ([Int]$TextBox.Text -1) } else { $TextBox.Text = 37 } } $handler_UpButton_Click= { if([Int]$TextBox.Text -in 37..32766) { [System.Console]::Beep([Int]$TextBox.Text,200) $TextBox.Text = ([Int]$TextBox.Text +1) } else { $TextBox.Text = 37 } } |

Dibujos
En los interfaces se pueden realizar dibujos en el caso de PowerShell se utiliza el espacio de nombres System.Drawing que proporciona acceso a la funcionalidad gráfica básica de GDI+. Los espacios de nombres System.Drawing.Drawing2D, System.Drawing.Imaging y System.Drawing.Text proporcionan una funcionalidad más avanzada.
Ejemplos
Mostrar los colores de cada uno de los pixeles que tiene una imagen BMP
1 2 3 4 5 6 7 8 | $Cave = [System.Drawing.Bitmap]::FromFile('.\fichero.bmp') for ($x = 0;$x -lt $Cave.Height;$x+=1) { for ($y = 0;$y -lt $Cave.Width;$y+=1) { Write-Host "X="$x "Y="$y ($Cave.GetPixel($y,$x).name).substring(2,6) } } |
Dibujar una recta en una imagen dentro de un formulario de PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # Crear en Pen $mypen = new-object Drawing.Pen red $mypen.width = 5 # Crear el formulario $form = New-Object Windows.Forms.Form $form.Width = 580 $form.Height = 235 $formGraphics = $form.createGraphics() # Añadir una imagen al formulario $Image = [system.drawing.image]::FromFile("C:\Users\Desktop\bank.jpg") $Form.BackgroundImage = $Image # Dibujar una línea en la imagen del formulario $form.add_paint({$formGraphics.DrawLine($mypen, 550, 170, 420, 185)}) $form.ShowDialog() |
Dibujar líneas paralelas en PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $mypen = new-object Drawing.Pen red $mypen.width = 10 $form = New-Object Windows.Forms.Form $formGraphics = $form.createGraphics() $form.add_paint({$formGraphics.DrawLine($mypen, 10, 10, 200, 10)}) $form.add_paint({$formGraphics.DrawLine($mypen, 10, 60, 200, 60)}) $form.add_paint({$formGraphics.DrawLine($mypen, 10, 110, 200, 110)}) $form.add_paint({$formGraphics.DrawLine($mypen, 10, 160, 200, 160)}) $form.ShowDialog() |
Ejercicios
Dibujar una casa en PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #Create pen $mypen = new-object Drawing.Pen red $mypen.width = 10 $form = New-Object Windows.Forms.Form $formGraphics = $form.createGraphics() #Drawing tiled $form.add_paint({$formGraphics.DrawLine($mypen, 100, 10, 10, 100)}) $form.add_paint({$formGraphics.DrawLine($mypen, 100, 10, 200, 100)}) #Drawing square #$form.add_paint({$formGraphics.DrawLine($mypen, 10, 10, 200, 10)}) $form.add_paint({$formGraphics.DrawLine($mypen, 10, 100, 200, 100)}) $form.add_paint({$formGraphics.DrawLine($mypen, 10, 200, 200, 200)}) $form.add_paint({$formGraphics.DrawLine($mypen, 10, 100, 10, 200)}) $form.add_paint({$formGraphics.DrawLine($mypen, 200, 100, 200, 200)}) $form.ShowDialog() |
Dibujar un texto dentro de un objeto Bitmap
1 2 3 4 5 6 7 8 9 10 11 12 13 | Add-Type -AssemblyName System.Drawing $file = "example2.png" $png = new-object System.Drawing.Bitmap 200,50 $font = new-object System.Drawing.Font Arial,30 $colorl = [System.Drawing.Brushes]::White $graphics = [System.Drawing.Graphics]::FromImage($png) $graphics.DrawString("Hello",$font,$colorl,5,5) $graphics.Dispose() $png.Save($file) |
Añadir una marca de agua a una imagen
1 2 3 4 5 6 7 8 9 10 11 12 13 | #Cargar imagen $imagen = [System.Drawing.Image]::FromFile("D:\power\foto5.bmp") #Crear Bitmap $bmp = New-Object System.Drawing.Bitmap([int]($imagen.width)),([int]($imagen.height)) #Cargar Graphic $dibujo = [System.Drawing.Graphics]::FromImage($bmp) #Dibujar la marca de agua utilizando una figura de tipo rectángulo y un texto con una fuente $dibujo.DrawImage($imagen,(New-Object Drawing.Rectangle 0,0,$imagen.Width,$imagen.Height),0,0,$imagen.Width,$imagen.Height,([Drawing.GraphicsUnit]::Pixel)) $dibujo.DrawString('Marca de agua',(New-Object System.Drawing.Font("Arial",29,[Drawing.FontStyle]'Bold' )),(New-Object Drawing.SolidBrush ([System.Drawing.Color]::Red)),0,10) #Guardar el Bitmap $bmp.Save('D:\power\foto5marcagua.bmp',[System.Drawing.Imaging.ImageFormat]::Bmp) $bmp.Dispose() $imagen.Dispose() |
Añadir una marca de agua a varias imágenes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #Cargar System.Drawing [Reflection.Assembly]::LoadWithPartialName("System.Drawing") #Listar imágenes Get-ChildItem D:\power\video\capturas2 | %{ #Listar cada imagen $_ #Cargar imagen $imagen = [System.Drawing.Image]::FromFile($_.FullName) #Crear Bitmap $bmp = New-Object System.Drawing.Bitmap([int]($imagen.width)),([int]($imagen.height)) #Cargar Graphic $dibujo = [System.Drawing.Graphics]::FromImage($bmp) #Dibujar la marca de agua utilizando una figura de tipo rectángulo y un texto con una fuente $dibujo.DrawImage($imagen,(New-Object Drawing.Rectangle 0,0,$imagen.Width,$imagen.Height),0,0,$imagen.Width,$imagen.Height,([Drawing.GraphicsUnit]::Pixel)) $dibujo.DrawString('Marca de agua',(New-Object System.Drawing.Font("Arial",29,[Drawing.FontStyle]'Bold' )),(New-Object Drawing.SolidBrush ([System.Drawing.Color]::Red)),0,10) #Guardar el Bitmap $bmp.Save('D:\power\video\capturas3\'+$_.Name,[System.Drawing.Imaging.ImageFormat]::Bmp) $bmp.Dispose() $imagen.Dispose() } |
Crear un objeto Bitmap y guardar una captura de la pantalla dentro del mismo
1 2 3 4 5 | $b = New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height) $g = [System.Drawing.Graphics]::FromImage($b) $g.CopyFromScreen((New-Object System.Drawing.Point(0,0)), (New-Object System.Drawing.Point(0,0)), $b.Size) $g.Dispose() $b.Save("fichero.bmp",'Bmp') |
Crear un formulario con un botón que al pulsarlo realiza una captura de pantalla cinco segundos después
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | using assembly System.Windows.Forms using namespace System.Windows.Forms function screenshot($path) { Start-Sleep -Seconds 6 $b=New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height) $g=[System.Drawing.Graphics]::FromImage($b) $g.CopyFromScreen((New-Object System.Drawing.Point(0,0)), (New-Object System.Drawing.Point(0,0)), $b.Size) $g.Dispose() $b.Save($path,'Bmp') } $form = [Form] @{ Text = 'Mi formulario' BackgroundImageLayout = "None" } #Creación de los botones $button = [Button] @{ Text = 'Realizar captura de pantalla (en 5 segundos realiza)' Dock = 'Top' } #Acciones de los botones $button.add_Click{ screenshot(".\test.bmp") #Creación del formulario $Image=[system.drawing.image]::FromFile(".\test.bmp") $form2 = [Form] @{ Text = 'Mi formulario' BackgroundImage = $Image Width = $Image.Width Height = $Image.Height BackgroundImageLayout = "None" } $form2.ShowDialog() } #Añadir botones al formulario $form.Controls.Add($button) $form.ShowDialog() |
Realizar una captura de pantalla mediante una interfaz gráfica creada con PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | [Reflection.Assembly]::LoadWithPartialName("System.Drawing") Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing function screenshot($path) { $b=New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height) $g=[System.Drawing.Graphics]::FromImage($b) $g.CopyFromScreen((New-Object System.Drawing.Point(0,0)), (New-Object System.Drawing.Point(0,0)), $b.Size) $g.Dispose() $b.Save($path,'Bmp') } $form = New-Object System.Windows.Forms.Form $form.Text = "Guardar fondo" $form.Size = New-Object System.Drawing.Size(300,200) $form.StartPosition = "CenterScreen" $OKButton = New-Object System.Windows.Forms.Button $OKButton.Location = New-Object System.Drawing.Point(75,120) $OKButton.Size = New-Object System.Drawing.Size(75,23) $OKButton.Text = "Guardar" $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK $form.AcceptButton = $OKButton $form.Controls.Add($OKButton) $CancelButton = New-Object System.Windows.Forms.Button $CancelButton.Location = New-Object System.Drawing.Point(150,120) $CancelButton.Size = New-Object System.Drawing.Size(75,23) $CancelButton.Text = "Cancelar" $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel $form.CancelButton = $CancelButton $form.Controls.Add($CancelButton) $label = New-Object System.Windows.Forms.Label $label.Location = New-Object System.Drawing.Point(10,20) $label.Size = New-Object System.Drawing.Size(280,20) $label.Text = "Nombre para guardar la foto:" $form.Controls.Add($label) $textBox = New-Object System.Windows.Forms.TextBox $textBox.Location = New-Object System.Drawing.Point(10,40) $textBox.Size = New-Object System.Drawing.Size(260,20) $form.Controls.Add($textBox) $form.Topmost = $True $form.Add_Shown({$textBox.Select()}) $result = $form.ShowDialog() if ($result -eq [System.Windows.Forms.DialogResult]::OK) { Start-Sleep -Seconds 1 $x = $textBox.Text $path= "$HOME\Desktop\$x.bmp" screenshot($path) } |
Realizar una miniatura de una imagen
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $Path = "imagen.bmp" $Bitmap=New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height) $Graphics=[System.Drawing.Graphics]::FromImage($Bitmap) $Graphics.CopyFromScreen((New-Object System.Drawing.Point(0,0)), (New-Object System.Drawing.Point(0,0)), $Bitmap.Size) $Graphics.Dispose() $Bitmap.Save($Path,'Bmp') $Bitmap.Dispose() $BitmapT = [System.Drawing.Image]::FromFile($Path) $Thumbnail = $BitmapT.GetThumbnailImage(200, 200, $null, [intptr]::Zero) $Thumbnail.Save("thumbnail" + $Path) $BitmapT.Dispose() $Thumbnail.Dispose() |
Detectar el color de un pixel de una captura de pantalla
1 2 3 4 5 6 7 8 9 | $path="prueba.bmp" $b=New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height) $g=[System.Drawing.Graphics]::FromImage($b) $g.CopyFromScreen((New-Object System.Drawing.Point(0,0)), (New-Object System.Drawing.Point(0,0)), $b.Size) $g.Dispose() $b.Save($path,'Bmp') $Cave = [System.Drawing.Bitmap]::FromFile('.\prueba.bmp') $Cave.GetPixel(974,1005) |
Comparar dos imágenes con PowerShell indicando el momento en el que empieza la diferencia
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #Es necesario que las dos imágenes estén en la misma posición inicial $foto1 = [System.Drawing.Bitmap]::FromFile('C:\Users\juan\Desktop\recono\coche.png') $foto2 = [System.Drawing.Bitmap]::FromFile('C:\Users\juan\Desktop\recono\coche - copia.png') $pixelestotales=0 $pixelesdistintos=0 $primeraposicion=0 for($y=0;$y -lt $foto1.Height;$y+=1) { for($x=0;$x -lt $foto1.Width;$x+=1) { $pixelestotales+=1 if($foto1.GetPixel($x,$y).name -eq $foto2.GetPixel($x,$y).name) { } else { $pixelesdistintos+=1 if($primeraposicion -eq 0) { Write-Host "Empieza la diferencia de la foto: $x,$y" $primeraposicion=1 } } } } $porcentajepixelesdistintos=($pixelesdistintos/$pixelestotales)*100 Write-Host "Píxeles totales: $pixelestotales" Write-Host "Píxeles distintos: $pixelesdistintos, porcentaje de píxeles distintos: $porcentajepixelesdistintos" |
Comparar dos imágenes con PowerShell mostrando la diferencia
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #Es necesario que las dos imágenes estén en la misma posición inicial $foto1 = [System.Drawing.Bitmap]::FromFile('C:\Users\juan\Desktop\recono\coche.png') $foto2 = [System.Drawing.Bitmap]::FromFile('C:\Users\juan\Desktop\recono\coche - copia.png') $pixelestotales=0 $pixelesdistintos=0 for($y=0;$y -lt $foto1.Height;$y+=1) { for($x=0;$x -lt $foto1.Width;$x+=1) { $pixelestotales+=1 if($foto1.GetPixel($x,$y).name -eq $foto2.GetPixel($x,$y).name) { switch ($foto1.GetPixel($x,$y).name){ default{Write-Host ' ' -BackgroundColor White -ForegroundColor Black -NoNewLine} } } else { $pixelesdistintos+=1 switch ($foto2.GetPixel($x,$y).name){ default{Write-Host ' ' -BackgroundColor Black -ForegroundColor White -NoNewLine} } } } Write-Host " " } $porcentajepixelesdistintos=($pixelesdistintos/$pixelestotales)*100 Write-Host "Píxeles totales: $pixelestotales" Write-Host "Píxeles distintos: $pixelesdistintos, porcentaje de píxeles distintos: $porcentajepixelesdistintos" |
Extraer coordenadas GPS de imágenes con PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 | $imagePath = 'C:\Users\juan\Desktop\recono\IMG_20171226_232738.jpg' $imageProperties = New-Object -TypeName System.Drawing.Bitmap -ArgumentList $imagePath [double]$LatDegrees = (([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(2).Value, 0)) / ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(2).Value, 4))); [double]$LatMinutes = ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(2).Value, 8)) / ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(2).Value, 12)); [double]$LatSeconds = ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(2).Value, 16)) / ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(2).Value, 20)); [double]$LonDegrees = (([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(4).Value, 0)) / ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(4).Value, 4))); [double]$LonMinutes = ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(4).Value, 8)) / ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(4).Value, 12)); [double]$LonSeconds = ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(4).Value, 16)) / ([System.BitConverter]::ToInt32( $imageProperties.GetPropertyItem(4).Value, 20)); "Latitude: $LatDegrees;$LatMinutes;$LatSeconds" "Longitude: $LonDegrees;$LonMinutes;$LonSeconds" |
Más información
- https://www.jesusninoc.com/02/01/how-to-draw-the-letter-a/
- https://www.jesusninoc.com/04/03/drawing-number-one/
- https://www.jesusninoc.com/11/28/dibujar-una-recta-en-una-imagen-dentro-de-un-formulario-de-powershell/
- https://www.jesusninoc.com/03/09/dividir-en-dos-partes-una-captura-de-pantalla/
- https://www.jesusninoc.com/01/22/convert-bitmap-to-html/
- https://www.jesusninoc.com/01/22/convert-bitmap-to-write-host/
- https://www.jesusninoc.com/01/08/convert-una-imagen-jpg-a-caracteres-en-la-consola-de-powershell/
- https://www.jesusninoc.com/03/12/tratamiento-de-imagenes-con-powershell-simular-en-un-dibujo-varias-alturas/
Automatización
En los interfaces gráficos se pueden realizar automatizaciones, en algunos casos se hace de forma gráfica y en otros mediante la gestión de eventos.
Saber más
- https://www.jesusninoc.com/02/03/crear-una-aplicacion-grafica-en-powershell-que-represente-un-piano-con-las-notas-del-do-a-si-y-que-suene-cada-nota/
- https://www.jesusninoc.com/02/03/automatizar-el-funcionamiento-de-una-aplicacion-que-simula-un-piano-pulsar-automaticamente-las-notas-del-piano/
- https://www.jesusninoc.com/01/30/buscar-el-nombre-de-una-clase-de-un-formulario-en-powershell-con-microsoft-spy/
- https://www.jesusninoc.com/01/30/buscar-el-nombre-de-una-clase-de-un-formulario-en-powershell-con-microsoft-spy-y-escribir-un-mensaje-en-una-caja-de-texto-desde-powershell/
- https://www.jesusninoc.com/01/31/buscar-el-nombre-de-una-clase-de-un-formulario-en-powershell-con-microsoft-spy-y-escribir-un-mensaje-en-una-caja-de-texto-sin-conocer-el-identificador-de-ventana-en-concreto-del-proceso-desde-powers/
- https://www.jesusninoc.com/01/30/escribir-y-un-mensaje-en-una-caja-de-texto-y-hacer-click-en-un-boton-de-un-formulario-de-powershell-de-forma-automatica-utilizando-sendmessage-y-findwindowex-de-user32-dll/