jueves, 23 de marzo de 2017

Cuestionario


¿Que es un evento?
Son acciones que se tienen que ejecutar en una interfaz gráfica. 
Menciona los 2 grupos generales de los eventos
Eventos de Bajo Nivel
Eventos Semánticos¿Que tipo de eventos encapsula la semántica del modelo de componentes de interfaz usuario?
Action Event, ChangedEvent, ItemEvent
¿Cual es el evento que controla las acciones realizadas por el teclado?
Key Event
¿Que realiza el evento MouseEvent?
Controla todas las acciones que podemos realizar con el mouse.
Menciona 3 componentes en los cuales se puede generar eventos
Button, Scrollbar, TextComponents
¿Cual es el paquete que contiene la mayor parte de las clases e interfaces de eventos?
Java.awt.Event
¿Que evento es el controla las acciones de las ventana?
WindowEvent

Tipos de Eventos

Los eventos son todas las acciones que el usuario inicia, al dar clic sobre un button, presionar las teclas del teclado, etc.
Un evento es la notificación que hace un elemento gráfico cuando el usuario interactua con el.
Existen 2 tipos de eventos las cuales son:
a) Eventos de Bajo Nivel.
b) Eventos Semánticos (Alto Nivel).

Eventos de Bajo Nivel
 Representan entradas o interacciones de bajo nivel con elementos de interfaz gráfico ( cambio de foco,cambio de tamaño u operación con el mouse o con el teclado).
Component Event: Cambia de tamaño, posición, visibilidad
Focus Event: Cambio de foco, capacidad de un componente.
KeyEvent: Operación con el teclado.
Mouse Event: Operación con el Mouse.
Window Event: Operación de la ventana
Eventos Semánticos (Alto Nivel)
 Encapsulan la semántica del modelo de componentes del interfaz de usuario(hacer una acción, un cambio).
Action Event: Realización de acción especifica, asociado al componente.
Change Event: Cambio de estado en el componente (texto,color,forma).
Item Event: Elemento Seleccionado o De-seleccionado.
ListSelectionEvent: Cambio en la selección actual de una lista.

Algunos eventos en donde  se pueden generar:
Eventos de ventana
Son los que se generan en respuesta a los cambios de una ventana, un Frame o un Dialogo.

  1. Window_Destroy
  2. Window_Expose
  3. Window_Iconifi
  4. Window_Moved
  5. Window_Deiconifi

Eventos del teclado

Son generados en respuesta a cuando el usuario pulsa y suelta una tecla mientras un componente tiene el foco de entrada.

  1. Key_Press
  2. Key_Down
  3. Key_Up

Eventos del Ratón(Mouse)

Son los eventos generados por las acciones sobre el ratón dentro de los limites de un componente.

  1. Mouse_Down
  2. Mouse_Up
  3. Mouse_Move
  4. Mouse_Enter




Clases de Eventos

Action Event: Se genera cuando se presiona un button, se hace doble click en un elemento de una lista, o se selecciona un elemento de tipo menú.
Ajustment Event: Se genera cuando se manipula el scrollbar.
Component Event : Se genera cuando un componente se oculta se mueve, se cambia de tamaño o se ha visible.
Container Event: Se genera cuand se añade o se elimina un componente de un contenedor.
Focus Event: Se genera cuando un componente gana o pierde el foco.
Input Event: Superclase abstracta de cualquier clase de evento de entrada de componente.
ItemEvent: Se genera cuando se hace click en un CheckBox o en un elemento de la lista.
KeyEvent: Se genera cuando se recibe una entrada desde el teclado. 
Mouse Event: Se genera cuando se arrastra, se mueve, se hace click, se presiona o se libera el mouse. 
TextEvent: Se genera cuando se cambia el valor de un area de texto o un componente de texto.
WindowEvent: Se genera cuando se cambia una ventana se activa, se cierra, se desactiva, se minimiza, se maximiza, se abre o se sale de ella.

martes, 21 de marzo de 2017

Practica Karel 2

Has que Karel recoja Zumbadores del reglon y los coloque en la pared que esta frente a el

iniciar-programa
    inicia-ejecucion
    Repetir 3 veces gira-izquierda;
    mientras frente-libre hacer inicio
    avanza;
    mientras junto-a-zumbador hacer inicio
    coge-zumbador;
    fin;
    fin;
    mientras algun-zumbador-en-la-mochila hacer inicio
    deja-zumbador;
    fin;
        apagate;
    termina-ejecucion
finalizar-programa

Practica Karel 2

Karel quiere asomarse arriba de la barda para ver que hay del otro lado.

iniciar-programa
    inicia-ejecucion
    Repetir 3 veces gira-izquierda;
    avanza;
    gira-izquierda;
    Mientras Izquierda-Libre HACER inicio
    Avanza;
    fin;
        apagate;
    termina-ejecucion
finalizar-programa

Practica Karel 1

Karel quiere visitar a su abuelita, la casa de su abuela se encuentra frente a Karel en la posicion que tiene la izquierda y esta junto a un Zumbador

iniciar-programa
    inicia-ejecucion
     Repetir 3 veces gira-izquierda;
     avanza;
     Repetir 4 veces coge-zumbador;
     avanza;
     Repetir 6 veces coge-zumbador;
     avanza;
     Repetir 4 veces coge-zumbador;
     avanza;
     Repetir 9 veces coge-zumbador;
     avanza;
     coge-zumbador;
     avanza;
     Repetir 6 veces coge-zumbador;
     avanza;
     Repetir 5 veces coge-zumbador;
     Repetir 2 veces avanza;
     gira-izquierda;
     Repetir 6 veces avanza;
     Repetir 3 veces gira-izquierda;
     avanza;
     Repetir 3 veces gira-izquierda;
     Repetir 6 veces avanza;
     gira-izquierda;
     avanza;
     Repetir 4 veces deja-zumbador;
     avanza;
     Repetir 6 veces deja-zumbador;
     avanza;
     Repetir 4 veces deja-zumbador;
     avanza;
     Repetir 9 veces deja-zumbador;
     avanza;
     deja-zumbador;
     avanza;
     Repetir 6 veces deja-zumbador;
     avanza;
     Repetir 5 veces deja-zumbador;
        apagate;
    termina-ejecucion
finalizar-programa

Eventos en Java


package eventos;
import java.awt.*;
public class Principal extends javax.swing.JFrame {
    public Principal() {
        initComponents();
    }
  private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                               
        // TODO add your handling code here:
        CheckBox Check= new CheckBox();
        Check.setVisible(true);
    }                                        

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        ListBox List =new ListBox();
        List.setVisible(true);
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO ad your handling code here:

        String eleccion = this.cmbMetodos.getSelectedItem().toString();
         if(eleccion.equals("Naranja")){
           this.getContentPane().setBackground(Color.ORANGE);
        }
        if(eleccion.equals("Amarrillo")){
           this.getContentPane().setBackground(Color.YELLOW);
        }
        if(eleccion.equals("Azul")){
           this.getContentPane().setBackground(Color.BLUE);
        }
        if(eleccion.equals("Verde")){
           this.getContentPane().setBackground(Color.GREEN);
        }
        if(eleccion.equals("Negro")){
           this.getContentPane().setBackground(Color.BLACK);
        }
        if(eleccion.equals("Rojo")){
           this.getContentPane().setBackground(Color.RED);
        }
        if(eleccion.equals("Morado")){
           this.getContentPane().setBackground(Color.MAGENTA);
        }
        if(eleccion.equals("Rosa")){
           this.getContentPane().setBackground(Color.PINK);
        }
        if(eleccion.equals("Gris")){
           this.getContentPane().setBackground(Color.gray);
        }
        if(eleccion.equals("Azul Claro")){
           this.getContentPane().setBackground(Color.CYAN);
        }
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

         Principal.this.setSize(1000, 800);
    }                                        

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        System.exit(0);
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        if (jLabel.isVisible()){
            jLabel.setVisible(false);
        }
        else{
            jLabel.setVisible(true);
        }       
    }                                        
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Principal.this.setSize(500, 400);
    }


public class ListBox extends javax.swing.JFrame {
    
    public ListBox() {
        initComponents();
        //Método de arranque.
        inicio();

    }
private DefaultListModel modelList; 
   private void inicio(){
        String [] nom  = { ""};
//DefaultListModel para manejar las lista.
          modelList = new DefaultListModel();
//Agregamos datos a la lista utilizando for
        for (String string : nom) {
       modelList.addElement(string);
       jList1.setModel(modelList);
       jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
       jList1.setSelectedIndex(0);
       jList1.setVisibleRowCount(7);
    }
   }
    private void eliminar(){
  //Método para eliminar elementos de la lista Se optiene el índice del elemento seleccionado
     int selectedIndex = jList1.getSelectedIndex();
 //Si selectedIndex es igual a ‐1, no hay elemento seleccionado
      if(selectedIndex!=-1){
      modelList.remove(selectedIndex);
      }
    else{
   JOptionPane.showMessageDialog(null, "Seleccione un elemento de la lista.");
   }
}
    //Método para comprobar datos repetidos
     protected boolean enLista(String name) {
       return modelList.contains(name);
}
     private void agregar(){
//Método para agregar elementos a la lista
//Comprobamos que el campo de datos no este vacio
         if(txtTexto.getText().isEmpty()){
           JOptionPane.showMessageDialog(null, "Campo vacio.");
         }
           else{
//Utilizando el método enLista, comprobamos que no se repitan los datos.
         if(enLista(txtTexto.getText())){
          JOptionPane.showMessageDialog(null, "Nombre repetido..");
          }
//Agregamos elemento y limpiamos campo.
         else{
          modelList.addElement(txtTexto.getText());
         txtTexto.setText(null);
         }
       }

     }

private void BtnRegresarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        Principal prin = new Principal();
        prin.setVisible(true);
        prin.setMaximumSize(null);
        this.dispose();
    }                                           

    private void BtnAñadirActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
       agregar();   
    }                                         

    private void BtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        eliminar();

    } 



public class CheckBox extends javax.swing.JFrame {

    public CheckBox() {
        initComponents();
    }
    
  public String ValidarDatos() {//Metodo para comprobar que los datos esten completos
        String msj = "";
        if (txtTexto.getText().equals("")) {//Si txtID esta vacio
            msj += "Por favor digite el Nombre \n";
            txtTexto.requestFocusInWindow();
        }      
        return msj;//devuelve msj   
        //validar que el usuario no existe
    }
  private void BtnMostrarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        JTextField Resultado = txtTexto;
        if (ValidarDatos().equals("")) {
        try{
            JOptionPane.showMessageDialog(null, Resultado);
            if(jCheckBox1.isSelected() == true){
                JOptionPane.showMessageDialog(null, "Usted  es Mayor de edad");
            }else{
                JOptionPane.showMessageDialog(null, "Usted no es mayor de edad");
            }
             if (jCheckBox2.isSelected() ==true){
                JOptionPane.showMessageDialog(null, "Usted tiene Hijos");
             }
             else{
                   JOptionPane.showMessageDialog(null, "Usted no tiene Hijos");
             }
             if (jCheckBox3.isSelected() ==true){
                 JOptionPane.showMessageDialog(null,"Usted estudió una Carrera");
             }
             else{
                 JOptionPane.showMessageDialog(null,"Usted no estudió una Carrera");
             }
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
            CheckBox Check = new CheckBox();
        }
      }
        else{
         JOptionPane.showMessageDialog(rootPane, "ERROR!! \n" + ValidarDatos(), "Verificando Dato",
                JOptionPane.ERROR_MESSAGE);   
        }
    }                                          

    private void BtnRegresarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        Principal prin = new Principal();
        prin.setVisible(true);
        prin.setMaximumSize(null);
        this.dispose();
    }              

Juego del Gato

Para poder Realizar el juego del gato utilizamos Buttons, Group Box, FlowLayoutPanel1, label y RadioButtns. Estos los controles que utilizaremos para desarrollar nuestro Juego.
Public Class Form1
'En primer lugar declaramos nuestras variables que utilizaremos
    Dim id As String = "X" ' Aqui estamos defiendo quien va primero
    Dim counter_jugadas As Integer = 0 'Contador de las jugadas
    Dim JX As Integer = 0 ' Contador para saber cuantas veces ha ganado X
    Dim JO As Integer = 0 ' Contador para saber cuantas veces ha ganado 0
    Dim Igual As Integer = 0  ' Contador para saber los empates
    Dim final_juego As Boolean = False

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        reiniciar_botones()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click
        Try
            'activamos el timer
            Timer1.Enabled = True
            'iniciamos el timer
            Timer1.Start()
            If RadioButton1.Checked = True Then
                seleccion_de_Juego(sender)
                verificar_ganador(id)
                switch()
            ElseIf RadioButton2.Checked = True Then
                If id = "X" Then
                    seleccion_de_Juego(sender)
                    verificar_ganador(id)
                    switch()
                End If
                If final_juego = False Then
                    seleccion_maquina()
                    verificar_ganador(id)
                    switch()
                End If
            Else
                MsgBox("ERROR : Selecciones Modo De Juego.", MsgBoxStyle.Critical, "Error")
            End If
        Catch ex As Exception
            MsgBox("error inesperado")
        End Try
    End Sub

    Private Sub switch()
        If id = "X" Then
            id = "O"
        Else
            id = "X"
        End If
        Label1.Text = id
    End Sub
    'METODO PARA SELECCIONAR EL TIPO DE JUEGO
    Private Sub seleccion_de_Juego(ByVal sender As Object)
        For Each opcion In FlowLayoutPanel1.Controls
            If TypeOf opcion Is Button Then
                If CType(opcion, Button).Name = CType(sender, Button).Name Then
                    CType(opcion, Button).Text = id
                    CType(opcion, Button).Enabled = False
                End If
            End If
        Next
    End Sub
'Metodo para ubicar aleatoriamente la 0 si nuestro id es x
    Private Sub seleccion()
        'Se tomara decisiones completamente al azar
        Dim numero As New Random
        While True And counter_jugadas < 9
            Dim seleccion_maquina As Integer = numero.Next(1, 10)
            Dim btns = Me.Controls.Find("button" & seleccion_maquina, True)
            If btns.Length > 0 Then
                If btns(0).Text = String.Empty Then
                    btns(0).Text = id
                    btns(0).Enabled = False
                    Exit While
                End If
            End If
        End While
    End Sub
'Fin de nuestra funcion Seleccion
'Metodo para analizar los bloqueos de nuestro juego
    Private Sub seleccion_maquina()
        If Bloqueo("O") = True Then
        Else
            If Bloqueo("X") = True Then
            Else
                seleccion()
            End If
        End If
    End Sub

    Private Function Bloqueo(ByVal opcion As String)
        'bloqueo horizontal
        Dim counter As Integer 'Conteo de X o 0 Encontrados.
        Dim empty As Integer   'Guarda Ultimo Espacio Vacio Encontrado
        For i As Integer = 1 To 7 Step 3 'LOOP Monitorea las Filas ... 1 , 4 , 7
            counter = 0
            For e As Integer = i To i + 2 'LOOP Monitorea los elementos en las filas. 123, 456 , 789
                Dim btns = Me.Controls.Find("button" & e, True)
                If btns.Length > 0 Then
                    If btns(0).Text = opcion Then
                        counter += 1
                    Else
                        empty = e
                    End If
                End If
            Next
            If counter = 2 Then
                Dim btns = Me.Controls.Find("button" & empty, True)
                If btns.Length > 0 Then
                    If btns(0).Text = String.Empty Then
                        btns(0).Text = id
                        btns(0).Enabled = False
                        Return True
                    End If
                End If
            End If

        Next

        'Bloqueo Vertical

        For i As Integer = 1 To 3 'LOOP Monitorea las Columnas
            counter = 0
            For e As Integer = i To 9 Step 3 'loop Monitorea los elementos de las columnas.
                Dim btns = Me.Controls.Find("button" & e, True)
                If btns.Length > 0 Then
                    If btns(0).Text = opcion Then
                        counter += 1
                    Else
                        empty = e
                    End If
                End If
            Next
            If counter = 2 Then
                Dim btns = Me.Controls.Find("button" & empty, True)
                If btns.Length > 0 Then
                    If btns(0).Text = String.Empty Then
                        btns(0).Text = id
                        btns(0).Enabled = False
                        Return True
                    End If
                End If
            End If
        Next
        'Bloqueo Diagonales
        counter = 0
        For e As Integer = 1 To 9 Step 4
            Dim btns = Me.Controls.Find("button" & e, True)
            If btns.Length > 0 Then
                If btns(0).Text = opcion Then
                    counter += 1
                Else
                    empty = e
                End If
            End If
        Next
        If counter = 2 Then
            Dim btns = Me.Controls.Find("button" & empty, True)
            If btns.Length > 0 Then
                If btns(0).Text = String.Empty Then
                    btns(0).Text = id
                    btns(0).Enabled = False
                    Return True
                End If
            End If
        End If
        counter = 0
        For e As Integer = 7 To 3 Step -2
            Dim btns = Me.Controls.Find("button" & e, True)
            If btns.Length > 0 Then
                If btns(0).Text = opcion Then
                    counter += 1
                Else
                    empty = e
                End If
            End If
        Next
        If counter = 2 Then
            Dim btns = Me.Controls.Find("button" & empty, True)
            If btns.Length > 0 Then
                If btns(0).Text = String.Empty Then
                    btns(0).Text = id
                    btns(0).Enabled = False
                    Return True
                End If
            End If
        End If
        Return False
    End Function

    Private Sub verificar_ganador(ByVal x As String)
        counter_jugadas += 1
        Dim counter As Integer = 0
        'Verificar Horizontal
        For i As Integer = 1 To 7 Step 3
            counter = 0
            For e As Integer = i To i + 2
                Dim btns = Me.Controls.Find("button" & e, True)
                If btns.Length > 0 Then
                    If btns(0).Text = x Then
                        btns(0).BackColor = Color.PowderBlue
                        counter += 1
                    End If
                End If
            Next
            If counter = 3 Then
                mostrar_ganador(x)
                Exit Sub
            Else
                reiniciar_colores()
            End If
        Next
        'Verificar Vertical
        For i As Integer = 1 To 3
            counter = 0
            For e As Integer = i To 9 Step 3
                Dim btns = Me.Controls.Find("button" & e, True)
                If btns.Length > 0 Then
                    If btns(0).Text = x Then
                        btns(0).BackColor = Color.PowderBlue
                        counter += 1
                    End If
                End If
            Next
            If counter = 3 Then
                mostrar_ganador(x)
                Exit Sub
            Else
                reiniciar_colores()
            End If
        Next
        'Verificar Diagonales
        counter = 0
        For e As Integer = 1 To 9 Step 4
            Dim btns = Me.Controls.Find("button" & e, True)
            If btns.Length > 0 Then
                If btns(0).Text = x Then
                    btns(0).BackColor = Color.PowderBlue
                    counter += 1
                End If
            End If
        Next
        If counter = 3 Then
            mostrar_ganador(x)
            Exit Sub
        Else
            reiniciar_colores()
        End If

        counter = 0
        For e As Integer = 7 To 3 Step -2
            Dim btns = Me.Controls.Find("button" & e, True)
            If btns.Length > 0 Then
                If btns(0).Text = x Then
                    btns(0).BackColor = Color.PowderBlue
                    counter += 1
                End If
            End If
        Next
        If counter = 3 Then
            mostrar_ganador(x)
            Exit Sub
        Else
            reiniciar_colores()
        End If

        If counter_jugadas = 9 Then
            Igual += 1
            Empate1.Text = Igual
            MsgBox("Empate", MsgBoxStyle.Information, "INFORMACION")
        End If


    End Sub

    Private Sub mostrar_ganador(ByVal ganador As String)
        'detenemos el timer
        Timer1.Stop()
        enable(False)
        final_juego = True
        MsgBox("GANO : " & ganador)
        If ganador = "X" Then
            JX += 1
        Else
            JO += 1
        End If
        Labelx.Text = JX
        LabelO.Text = JO
    End Sub

    Private Sub enable(ByVal x As Boolean)
        For Each opcion In FlowLayoutPanel1.Controls
            If TypeOf opcion Is Button Then
                If x = False Then
                    CType(opcion, Button).Enabled = False
                Else
                    CType(opcion, Button).Enabled = True
                End If

            End If
        Next
    End Sub

    Private Sub reiniciar_botones()
        For Each opcion In FlowLayoutPanel1.Controls
            If TypeOf opcion Is Button Then
                CType(opcion, Button).Text = String.Empty
            End If
        Next
        reiniciar_colores()

        counter_jugadas = 0
        Label1.Text = id

    End Sub

    Private Sub reiniciar_colores()
        For Each opcion In FlowLayoutPanel1.Controls
            If TypeOf opcion Is Button Then
                CType(opcion, Button).BackColor = Color.White
            End If
        Next
    End Sub


    Private Sub JuegoNuevo_Click(sender As Object, e As EventArgs) Handles JuegoNuevo.Click
        reiniciar_botones()
        enable(True)
        final_juego = False
        If RadioButton2.Checked = True And id <> "X" Then
            Button1_Click(Button1, New EventArgs())
        End If
        Tiempo.Text = "00"
        Label5.Text = "00"
    End Sub

    Private Sub Salir_Click(sender As Object, e As EventArgs) Handles Salir.Click
        Me.Close()
    End Sub

    Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
        If RadioButton1.Checked = True Then
            enable(True)
            reiniciar_botones()
        End If

    End Sub

    Private Sub RadioButton2_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton2.CheckedChanged
        If RadioButton2.Checked = True And id <> "X" Then
            Button1_Click(Button1, New EventArgs())
        End If
    End Sub

    Private Sub Limpiar_Click(sender As Object, e As EventArgs) Handles Limpiar.Click
        JX = 0
        JO = 0
        Igual = 0
        LabelO.Text = JO
        Labelx.Text = JX
        Empate1.Text = Igual
        Tiempo.Text = "00"
        Label5.Text = "00"
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Tiempo.Text += 1
        If Tiempo.Text = "60" Then
            Tiempo.Text += 1
        End If

    End Sub
End Class


Suma de 2 numeros

Realizar un algoritmo y su diagrama de flujo de la Suma de 2 Números

Inicio
Pedir el primer valor
Guardar el primer valor
Pedir el segundo valor
Guardar el segundo valor
Sumar el primer valor mas el segundo valor
Mostrar resultado
Fin




viernes, 17 de marzo de 2017

Eventos en C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eventos
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Color_Click(object sender, EventArgs e)
        {  
           BackColor = System.Drawing.Color.Aqua;
        }

        private void Maximizar_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Maximized;
        }

        private void Minimizar_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
        }

        private void Mostrar_MouseMove(object sender, EventArgs e)
        {

            label1.Visible = true;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            CheckBox VentanaEventos = new CheckBox();
            VentanaEventos.Show();
        }

        private void button5_Click(object sender, EventArgs e)
        {
           ListBox VentanaEventos = new ListBox();
            VentanaEventos.Show();
        }
       
        private void Elegir_Color_Click(object sender, EventArgs e)
        {
            ColorDialog MyDialog = new ColorDialog();
            MyDialog.AllowFullOpen = false;
            MyDialog.ShowHelp = true;
            MyDialog.Color =label1.ForeColor;
            if (MyDialog.ShowDialog() == DialogResult.OK)
                label1.ForeColor = MyDialog.Color;

        }

        private void Elegir_Fuente_Click(object sender, EventArgs e)
        {
            FontDialog MyDialog = new FontDialog();
            MyDialog.AllowSimulations = false;
            MyDialog.ShowHelp = true;
            MyDialog.Font = label1.Font;
            if (MyDialog.ShowDialog() == DialogResult.OK)
                label1.Font = MyDialog.Font;
        }
    }
}


public partial class ListBox : Form
    {
        public ListBox()
        {
            InitializeComponent();
        }

        private void Agregar_Click(object sender, EventArgs e)
        {
            if ( textBox1.Text =="")
            {
                MessageBox.Show("Debe ingresar un nombre para poder agregar ");
            }
            else
            {
                listBox1.Items.Add(textBox1.Text);
                textBox1.Text = "";
            }
        }

        private void Eliminar_Click(object sender, EventArgs e)
        {
            //Si la lista no está vacía entonces podemos eliminar
            if (listBox1.TabIndex < 1)
            {
                //Eliminamos el elemento que se encuentra seleccionado
                listBox1.Items.Remove(listBox1.SelectedItem);
            }
        }
    }
}




    public partial class CheckBox : Form
    {
        public CheckBox()
        {
            InitializeComponent();
        }
        public void Validar()
        {
             String msj = "";
        if (TxtBox.Equals("")) {//Si txtID esta vacio
            msj += "Por favor digite el Nombre \n";
          //  TxtBox.requestFocusInWindow();
        }      
       // return msj;//devuelve msj   
        //validar que el usuario no existe
    }
        
        private void button1_Click_1(object sender, EventArgs e)
        {
            string list = " ";
            if (TxtBox.Text == "")
            {
                MessageBox.Show("Ingrese su nombre");
            }

            else 
                list ="Su nombre es:\t" + TxtBox.Text;
                if (checkBox1.Checked == true)
                {
                    list = list + "\nUsted es Mayor de edad";
                }
                if (checkBox2.Checked == true)
                {
                    list = list + "\nTiene hijos";
                }
                if (checkBox3.Checked == true)
                {
                    list = list + "\nEstudia una Carrera";
                }
                if (list.Length > 0)
                {
                    MessageBox.Show(list);
                }
                else
                {
                    MessageBox.Show("No ha seleccionado nada");
                }

                checkBox1.ThreeState = true;
        }
    }
}

Eventos en Visual Basic


Public Class Form1

    Private Sub Color_Click(sender As Object, e As EventArgs) Handles Color.Click
        Me.BackColor = Drawing.Color.LightBlue
    End Sub

    Private Sub Maximizar_Click(sender As Object, e As EventArgs) Handles Maximizar.Click
        Me.WindowState = FormWindowState.Maximized
    End Sub

    Private Sub Mostrar_MouseMove(sender As Object, e As MouseEventArgs) Handles Mostrar.MouseMove
        Label1.Visible = True
    End Sub

    Private Sub Minimizar_Click(sender As Object, e As EventArgs) Handles Minimizar.Click
        Me.WindowState = FormWindowState.Normal
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Eventos.ListBox.Show()
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Eventos.CheckBox.Show()
    End Sub

    Private Sub Salir_Click(sender As Object, e As EventArgs) Handles Salir.Click
        Me.Close()
    End Sub
End Class



Public Class CheckBox

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Resultado As String
        If TextBox1.Text = "" Then
            MsgBox("Debe ingresar un nombre", vbExclamation, "Encuesta")
            Exit Sub
        End If
        Resultado = "Su nombre es " & TextBox1.Text & vbNewLine
        If CheckBox1.Checked = 0 Then
            Resultado = Resultado & "Usted no es mayor de edad"
        Else
            Resultado = Resultado & "Usted es mayor de edad"
        End If
        Resultado = Resultado & vbNewLine
        If CheckBox2.Checked = 0 Then
            Resultado = Resultado & "Usted no tiene Hijos"
        Else
            Resultado = Resultado & "Usted tiene hijos"
        End If
        Resultado = Resultado & vbNewLine
        If CheckBox3.Checked = 0 Then
            Resultado = Resultado & "Usted no estudió una Carrera"
        Else
            Resultado = Resultado & "Usted estudió una Carrera"
        End If
        MsgBox(Resultado, vbInformation, "Encuesta")
    End Sub
End Class


Public Class ListBox

    Private Sub Agregar_Click(sender As Object, e As EventArgs) Handles Agregar.Click
        If TextBox1.Text = "" Then
            MsgBox("Debe ingresar un nombre para poder agregar un elemento", vbQuestion +
             vbOKOnly, "Datos incompletos")
            'Salimos de la rutina ya que no se ha ingresado nada en el control text1
            Exit Sub
        End If
        ListBox1.Items.Add(TextBox1.Text)
        TextBox1.Text = ""
    End Sub

    Private Sub Eliminar_Click(sender As Object, e As EventArgs) Handles Eliminar.Click
        'Si la lista no está vacía entonces podemos eliminar
        If ListBox1.TabIndex <> 1 Then
            'Eliminamos el elemento que se encuentra seleccionado
            ListBox1.Items.Remove(ListBox1.SelectedItem)
        End If
    End Sub

End Class

jueves, 9 de marzo de 2017

Determinar que numero es mayor

    Almacenar 3 números en 3 variables, decir cual número es mayor y cual es menor

Inicio
Pedir numero 1
Guardar numero 1
Pedir numero 2
Guardar numero 2
Pedir numero 3
Guardar numero 3
Comparar N1>=N2 si n1 es mayor
Comparar N1>=N3 si n1 es mayor
Imprimir N1 es mayor
Sino
Comparar N2>=N1 si n2 es mayor
Comparar N2>=N3 si n2 es mayor
Imprimir N2 es mayor
Si no imprimir  N3 es mayor
Comparar N1<=N2 si n1 es menor
Comparar N1<=N3 si n1 es menor
Imprimir N1 es menor
Sino
Comparar N2<=N1 si n2 es menor
Comparar N2<=N3 si n2 es menor
Imprimir N2 es menor
Si no imprimir  N3 es menor

Fin