Capítulo 28: Formulario completo en EPLAN con C#

5 min de lectura

Parte VIII: Windows Forms - Sección 16: Interfaces gráficas - Nivel: Intermedio


Objetivos de aprendizaje

Al finalizar este capítulo serás capaz de:

  • Agregar controles básicos (Button, Label, TextBox, CheckBox)
  • Manejar eventos (Click, CheckedChanged)
  • Diseñar un formulario funcional para solicitar datos al usuario
  • Validar la entrada del usuario antes de cerrar

Requisitos previos

  • Capítulo 27 (Template Forms)

Introducción: Llenando el vacío

Una ventana vacía no sirve de mucho. Necesitamos "controles" (widgets) para interactuar.

Los controles más comunes son:

  1. Label: Texto estático (etiquetas).
  2. TextBox: Campo de entrada de texto.
  3. CheckBox: Opción Sí/No.
  4. Button: Acción al hacer clic.

En Windows Forms, cada control es una clase que debes instanciar, configurar y agregar a la colección de controles del formulario.


1. Agregando controles

1.1 El proceso de 3 pasos

Dentro de InitializeComponent():

  1. Instanciar: Crear el objeto.
  2. Configurar: Propiedades (Texto, Tamaño, Posición).
  3. Agregar: Añadirlo al formulario con this.Controls.Add().

1.2 Ejemplo: Agregar un Botón

// 1. Instanciar (variable miembro de la clase)
private Button btnAction;

private void InitializeComponent()
{
    this.btnAction = new Button();

    // 2. Configurar
    this.btnAction.Text = "Ejecutar";
    this.btnAction.Location = new System.Drawing.Point(50, 50); // X, Y
    this.btnAction.Size = new System.Drawing.Size(100, 30); // Ancho, Alto

    // 3. Agregar
    this.Controls.Add(this.btnAction);
}

2. Manejando Eventos (Hacer que funcione)

Un botón no hace nada si no "escuchas" su evento Click.

// Suscribirse al evento
this.btnAction.Click += new System.EventHandler(this.BtnAction_Click);

// El método que se ejecuta
private void BtnAction_Click(object sender, System.EventArgs e)
{
    MessageBox.Show("¡Hiciste clic!");
}

3. Ejemplo Completo: Configurador de Exportación

Vamos a crear un formulario que pregunte:

  • Nombre del archivo (TextBox)
  • Si comprimir (CheckBox)
  • Botón Aceptar (Ejecuta y Cierra)

Basado en EPLAN-Scripting-4.0/09_Forms/02_FormsExample.cs:

using System;
using System.Drawing;
using System.Windows.Forms;
using Eplan.EplApi.Scripting;

public class FormularioCompleto
{
    [Start]
    public void Function()
    {
        ExportForm frm = new ExportForm();
        frm.ShowDialog();
    }
}

public class ExportForm : Form
{
    private Label lblName;
    private TextBox txtName;
    private CheckBox chkCompress;
    private Button btnOk;
    private Button btnCancel;

    public ExportForm()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        this.Text = "Configurar Exportación";
        this.Size = new Size(300, 200);
        this.StartPosition = FormStartPosition.CenterScreen;

        // 1. Label
        lblName = new Label();
        lblName.Text = "Nombre archivo:";
        lblName.Location = new Point(20, 20);
        lblName.AutoSize = true;

        // 2. TextBox
        txtName = new TextBox();
        txtName.Location = new Point(20, 45);
        txtName.Size = new Size(240, 20);
        txtName.Text = "Export_01"; // Valor por defecto

        // 3. CheckBox
        chkCompress = new CheckBox();
        chkCompress.Text = "Comprimir ZIP";
        chkCompress.Location = new Point(20, 80);
        chkCompress.Checked = true; // Por defecto marcado

        // 4. Botón OK
        btnOk = new Button();
        btnOk.Text = "Exportar";
        btnOk.Location = new Point(100, 120);
        btnOk.Click += new EventHandler(BtnOk_Click);

        // 5. Botón Cancel
        btnCancel = new Button();
        btnCancel.Text = "Cancelar";
        btnCancel.Location = new Point(190, 120);
        btnCancel.Click += new EventHandler(BtnCancel_Click);

        // AGREGAR CONTROLES
        this.Controls.Add(lblName);
        this.Controls.Add(txtName);
        this.Controls.Add(chkCompress);
        this.Controls.Add(btnOk);
        this.Controls.Add(btnCancel);

        // Configuración extra
        this.AcceptButton = btnOk; // Enter dispara OK
        this.CancelButton = btnCancel; // Esc dispara Cancel
    }

    private void BtnOk_Click(object sender, EventArgs e)
    {
        // Validación
        if (string.IsNullOrEmpty(txtName.Text))
        {
            MessageBox.Show("El nombre no puede estar vacío.");
            return; // No cerramos
        }

        // Simular lógica
        string mensaje = "Exportando: " + txtName.Text;
        if (chkCompress.Checked) mensaje += " (ZIP)";
        
        MessageBox.Show(mensaje);

        // Cerrar formulario
        this.Close();
    }

    private void BtnCancel_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}

4. Buenas prácticas

  1. Nombres Claros: btnOk es mejor que button1.
  2. Validación: Valida los datos en el evento del botón Aceptar antes de cerrar.
  3. AcceptButton / CancelButton: Configúralos para mejorar la usabilidad (Enter/Esc).
  4. TabIndex: Usa tabIndex si tienes muchos controles para ordenar la navegación con la tecla TAB.

Resumen

  • Una GUI se construye componiendo controles simples.
  • Cada control debe ser instanciado, configurado y agregado a this.Controls.
  • La lógica del negocio va dentro de los manejadores de eventos (ej. BtnOk_Click).

Conexiones

Capítulo anterior

Capítulo 27: Template de Windows Forms

Próximo capítulo

Capítulo 29: Cambiar cursor durante operaciones

En el próximo capítulo veremos cómo dar feedback visual cambiando el cursor a "Espera" cuando el script está ocupado.