Está en la página 1de 125

UNIVERSIDAD NACIONAL DE

CAJAMARCA
Escuela Académico Profesional de Ingeniería
de Sistemas

DOCENTE: Ing. Lisi Janet Vásquez Fernández

Alumno: Chávez Briceño, Franklin Duver

Grupo: B

14 de diciembre de 2017
Contenido
I. INTRODUCCION:............................................................................................................................3
II. OBJETIVOS:....................................................................................................................................3
III. PROGRAMA DONDE TRABAJAREMOS:.......................................................................................3
IV. ACCESO AL SOFWARE:...............................................................................................................4
V. CONCEPTOS DE PROGRAMACION ORIENTADA A OBJETOS...........................................................6
VI. CONTROLES USADOS:................................................................................................................7
VII. PROPIEDADES DE CONTROL:.....................................................................................................8
VIII. EVENTOS:...................................................................................................................................9
IX. FUNCIONES:.............................................................................................................................10
X. EJERCICIOS REALIZADOS DURANTE EL CICLO:..............................................................................11
Ejercicio 1:.......................................................................................................................................11
Ejercicio 2:.......................................................................................................................................13
Ejercicio 3:.......................................................................................................................................15
Ejercicio 4:.......................................................................................................................................17
Ejercicio 5:.......................................................................................................................................20
Ejercicio 7:.......................................................................................................................................22
Ejercicio 8:.......................................................................................................................................24
Ejercicio 9:.......................................................................................................................................27
Ejercicio 10: (Practica Calificada I)...................................................................................................31
Ejercicio 11: (Practica Calificada I)...................................................................................................31
Ejercicio 12: (Practica Calificada I)...................................................................................................31
Ejercicio 13:.....................................................................................................................................31
Ejercicio 14:.....................................................................................................................................33
Ejercicio 15:.....................................................................................................................................34
Ejercicio 16:.....................................................................................................................................36
Ejercicio 17:.....................................................................................................................................39
Ejercicio 18:.....................................................................................................................................43
Ejercicio 19:.....................................................................................................................................45
Ejercicio 20:.....................................................................................................................................48
Ejercicio 21:.....................................................................................................................................53
Ejercicio 22:.....................................................................................................................................57
Ejercicio 23:.....................................................................................................................................62
Ejercicio 24:.....................................................................................................................................66
Ejercicio 25:.....................................................................................................................................73

pág. 1
Ejercicio 26:.....................................................................................................................................77
Ejercicio 27:.....................................................................................................................................80
Ejercicio 28:.....................................................................................................................................83
Ejercicio 29:.....................................................................................................................................86
Ejercicio 30:.....................................................................................................................................90
Ejercicio 31......................................................................................................................................93
Ejercicio 32......................................................................................................................................95
Ejercicio 33:...................................................................................................................................100
Ejercicio 34:...................................................................................................................................102
Ejercicio 35:...................................................................................................................................106
Ejercicio 36:...................................................................................................................................109
Ejercicio 37:...................................................................................................................................114
Ejercicio 38:...................................................................................................................................115
Ejercicio 39: (Practica Calificada)...................................................................................................120

pág. 2
I. INTRODUCCION:
El manual contiene información teórica tanto del programa usado, así
como de las herramientas, controles, eventos que utilizamos también están los
casos prácticos que fueron planteados en clase.

II. OBJETIVOS:
 Aprender a usar muchas herramientas que son de mucha ayuda en la vida
diaria.
 Analizar los casos prácticos planteados en clase y relacionarlos con la
realidad diaria en la que estamos.

III. PROGRAMA DONDE TRABAJAREMOS:


 Microsoft Visual Studio 2015 - C#

1. Definición: Microsoft Visual Studio es un entorno de desarrollo


integrado (IDE, por sus siglas en ingles) para sistemas operativos
Windows. Soporta múltiples lenguajes de programación tales como
C++, C#, Visual Basic .NET, F#, Java, Python, Ruby, PHP. Al sumarle las
nuevas capacidades online bajo Windows Azure en forma del editor
Monaco.

2. Función: Visual Studio permite a los desarrolladores crear sitios y


aplicaciones web, así como servicios web en cualquier entorno que
soporte la plataforma. Así se pueden crear aplicaciones que se
comuniquen entre estaciones de trabajo, páginas web, dispositivos
móviles, consolas, etc.

pág. 3
IV. ACCESO AL SOFWARE:
Para acceder al software debemos seguir los siguientes pasos:
 Clic en botón inicio:

 Accedemos a todos programas:

 Ubicamos Microsoft Visual Studio 2015 y le damos clic para que se abra.

pág. 4
 Aparecerá la siguiente ventana, la cual indica que ya vamos a acceder al
programa:

 Se mostrará, finalmente, la Página Principal de Microsoft Visual Studio


2015 en la cual vamos a elegir si iniciar con un nuevo proyecto o abrir un
proyecto ya hecho anteriormente.

pág. 5
V. CONCEPTOS DE PROGRAMACION ORIENTADA A
OBJETOS
Denominada también programación orientada a objetos o POO (OOP
según sus siglas en inglés) es un paradigma de programación que usa objetos y
sus interacciones, para diseñar aplicaciones y programas informáticos. Está
basado en varias técnicas, incluyendo herencia, abstracción, polimorfismo y
encapsulamiento. Su uso se popularizó a principios de la década de los años
1990.

 OBJETO: Es una entidad provista de un conjunto de propiedades o


atributos (datos) y de comportamiento o funcionalidad (métodos) los
mismos que consecuentemente reaccionan a eventos. Se corresponde
con los objetos reales del mundo que nos rodea, o a objetos internos del
sistema (del programa). Es una instancia a una clase.

 CLASE: Es una construcción que se utiliza como un modelo (o plantilla)


para crear objetos de ese tipo.

 PROPIEDADES: Características de los objetos.

 METODO: Desde el punto de vista del comportamiento, es lo que el


objeto puede hacer. Un método puede producir un cambio en las
propiedades del objeto, o la generación de un "evento" con un nuevo
mensaje para otro objeto del sistema.

 EVENTO: Es un suceso en el sistema (tal como una interacción del


usuario con la máquina, o un mensaje enviado por un objeto). El sistema
maneja el evento enviando el mensaje adecuado al objeto pertinente.
También se puede definir como evento, a la reacción que puede
desencadenar un objeto, es decir la acción que genera.

pág. 6
VI. CONTROLES USADOS:

HERRAMIENTA FUNCION

Button Genera un evento cuando un usuario hace clic en él.


CheckBox Permite al usuario seleccionar o quitar la opción asociada.

CheckedListBox Muestra una lista de elementos con una casilla a la izquierda de cada
elemento.

LinkLabel Muestra un control de etiqueta que admite funcionabilidad de


hipervínculo, formato y seguimiento.

ComboBox Muestra un cuadro de texto editable con una lista desplegable de los
valores permitidos.

HScrollBar Permite al componente principal desplegarse por el contenido


horizontalmente.
Label Proporciona información en tiempo de ejecución o texto descriptivo para
un control.
ListBox Muestra una lista entre los que el usuario puede elegir elementos .

ListView Muestra una colección de elementos en una de cinco vistas diferentes .

MaskedTextBo Utiliza una máscara para distinguir si los datos que especifica el usuario
con apropiados o inapropiados.
x

Panel Permite agrupar colecciones de controles

PictureBox Muestra una imagen.


RadioButton Permite al usuario seleccionar una sola opción de entre un grupo de
opciones cuando están emparejadas con otros RadioButtons.

TextBox Permite al usuario especificar texto así como funciones de edición de


varias líneas y marcas de caracteres para contraseñas.

Timer Componente que genera un evento a intervalos definido por el usuario.

pág. 7
VII. PROPIEDADES DE CONTROL:

PROPIEDAD FUNCION
Name Indica el nombre utilizado en el código para identificar el objeto.

AutoSizeMode Especifica el modo mediante el que el elemento de interfaz del usuario


cambia de tamaño automáticamente.

Locked Indica o determina si se puede cambiar de tamaño o mover el control.


MaxLength Especifica el número máximo de caracteres que se pueden introducir
en el control de edición.

Click Ocurre cuando el usuario presiona y suelta un botón del mouse sobre
un objeto.
Text Se modifica el texto asociado con el control.

BackColor Color de fondo del componente.


BackgroundImag Diseño de imagen de fondo utilizado para el componente.
e
Enabled Indica si el control está habilitado.

FlatStyle Determina la apariencia del control cuando un usuario mueve el mouse


sobre el control y hace clic.

Font Fuente utilizada para mostrar el texto en el control.


ForeColor Color de primer plano de este componente, utilizado para mostrar
texto.
Interval Frecuencia de los eventos elapsed en milisegundos.(es una propiedad
propia de Timer)

Locatión Coordenadas de la esquina superior del control respecto de la esquina


superior izquierda de su contenedor.

MaximumSize Especifica el tamaño máximo del control.

MinimumSize Especifica el tamaño mínimo del control


Size Tamaño del control, en pixeles.

Tag Datos definidos por el usuario asociado con el objeto.


Visible Determina si el control esta visible u oculto.
MaxLength Especifica el número máximo de caracteres que se pueden introducir
en el control de edición.

Multiline Controla si el texto en el control de edición puede abarcar más de una


línea.

AutoScroll Indica si las barras de desplazamiento aparecen automáticamente


cuando el contenido del control es mayor que su área visible.

pág. 8
BorderStyle Indica si un panel debe tener borde.
AllowDrop Indica si el control puede aceptar datos que el usuario arrastre.

VIII. EVENTOS:

EVENTO FUNCION
Clic Tiene lugar cuando se hace clic en el componente.

CheckedChange Tiene lugar cuando la propiedad Checked cambia de valor.


d
DragDrop Tiene lugar cuando se completa una operación de arrastrar y colocar.
DragEnter Tiene lugar cuando el mouse arrastra un elemento en el área cliente
para ese control.

Enter Tiene Lugar cuando el control se convierte en el control activo del


formulario.

KeyDown Tiene lugar cuando se persona una tecla por primera vez.

KeyPress Tiene lugar cuando el control tiene foco y el usuario presiona y suelta
una tecla.

KeyUp Tiene lugar cuando se suelta la tecla.


Load Tiene lugar cuando el usuario carga el formulario.

MouseClick Tiene lugar cuando se hace clic con el mouse en el control.


MouseDown Tiene lugar cuando el puntero del mouse se encuentra sobre el
componente y se pulsa un botón del mouse.

MouseEnter Tiene lugar cuando el mouse entra a la parte visible del control.

MouseMove Tiene lugar cuando el puntero del mouse de mueve sobre el


componente.
MouseUp Tiene lugar cuando el puntero del mouse se encuentra sobre el
componente y se suelta un botón del mouse.

Tick Tiene lugar cuando ha transcurrido el intervalo de tiempo especificado.


(es un control propio de timer)

pág. 9
IX. FUNCIONES:

NOMBRE DE FUNCION FUNCION QUE CUMPLE


String Datos que pueden tener texto o cualquier caracter.
Integer Datos que pueden tener cualquier número entero, o sea, no
tiene punto decimal. Puede tener valores desde –32,768 hasta
32,767.
Equals Devuelve un valor que indica si esta instancia es igual a un
objeto.

ToString Convierte el valor de una instancia en representación en


cadena de texto.

MessageBox Muestra un cuadro de mensaje que puede contener un texto,


botones o símbolos que informan o instruyen al usuario.

Math Proporciona constantes y métodos estáticos para operaciones


trigonométricas, logarítmicas y otras funciones matemáticas
comunes.
Convert Estas funciones se compilan en línea, es decir, el código de
conversión forma parte del código que evalúa la expresión.
Cada función convierte una expresión a un tipo de datos
específico.
Color Es una función la cual sirve para cambiar el color de cualquier
parte del código o respuesta que suela dejar al correr el
programa.
SelectedIndex Obtiene o establece el índice ordinal inferior de los elementos
seleccionados en la lista. (ListBox)

Random Devuelve un número aleatorio de tipo Single.


IsLetter Indica si un carácter está categorizado como una letra

IsLower Indica si un carácter está categorizado como una letra


minúscula.

IsNumber Devuelve un valor Boolean que indica si una expresión puede


evaluarse como un número.

Add Agrega un elemento a un objeto Collection


Upper Convierte caracteres a mayúscula

Bitman Es un objeto que se utiliza para trabajar con imágenes


definidas mediante datos de píxeles.

AllowDrop Obtiene o establece un valor que indica si arrastrar y colocar y


la reordenación de elementos se controlan mediante eventos

pág. 10
que implementa

X. EJERCICIOS REALIZADOS DURANTE EL CICLO:

Ejercicio 1:
Calcular las raíces de una ecuación cuadrática.

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 WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
// datos de entrada

pág. 11
double a = Convert.ToDouble(c1.Text);
double b = Convert.ToDouble(c2.Text);
double c = Convert.ToDouble(c3.Text);
double d, x1, x2;
//proceso
if (a != 0)
{
d = b * b - 4 * a * c;
if (d >= 0)
{
x1 = (-b + Math.Sqrt(d)) / (2 * a);
x2 = (-b - Math.Sqrt(d)) / (2 * a);
//salida
raiz.Text = "x1= " + x1.ToString();
raiz2.Text = "x2= " + x2.ToString();
}
else
MessageBox.Show("Raices Imaginarias");
}
else
MessageBox.Show("El coeficiente cuadrático debe ser diferente de 0");
}
private void button2_Click(object sender, EventArgs e)
{
c1.Text = "";
c2.Text = "";
c3.Text = "";
raiz.Text = "";
raiz2.Text = "";
c1.Focus();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

pág. 12
Ejercicio 2:
Calcular el promedio de 3 notas, indicar con un mensaje si está aprobado o no y mostrar el
promedio de color azul si está aprobado o rojo si esta desaprobado. Eliminar la menor nota .

pág. 13
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 WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form2()
{
InitializeComponent();
}

private void button2_Click_1(object sender, EventArgs e)


{
n1.Text = "";
n2.Text = "";
n3.Text = "";
Promedio.Text = "";
n1.Focus();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
// datos de entrada
double a = Convert.ToDouble(n1.Text);
double b = Convert.ToDouble(n2.Text);
double c = Convert.ToDouble(n3.Text);
double menor, promedio;
if (a < b && b < c)
{
menor = a;
promedio = (a + b + c - menor) / 2;
}
else if (b < c)
{
menor = b;
promedio = (a + b + c - menor) / 2;
}
else
{
menor = c;
promedio = (a + b + c - menor) / 2;
}
if (promedio >= 10.5)

pág. 14
{
Promedio.ForeColor = Color.Blue;
Promedio.Text = promedio.ToString();
MessageBox.Show("Esta Aprobado!");
}
else
{
Promedio.ForeColor = Color.Red;
Promedio.Text = promedio.ToString();
MessageBox.Show("Esta desaprobado :(!");
}
}
}
}

Ejercicio 3:
Calcular el sueldo neto de un empleado, según los siguientes descuentos:
Entre 750 y 3500 dscto: 10%
Más que 3500 y hasta 5000 dscto: 15%
Más que 5000 y hasta 8000 dscto: 20%
Validar que el sueldo ingresado este entre 750 y 8000

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

pág. 15
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Ejercicio03: Form
{
public Ejercicio03()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
double a = Convert.ToDouble(textBox1.Text);
double d, d1, su; if (a < 750)
{
MessageBox.Show("Ingresar un monto mayor o igual a 750");
}
else if
(a <= 3500)
{
d = 10; d1 = ((a * 10) / 100);
su = a - d1;
textBox2.Text = d.ToString();
textBox3.Text = d1.ToString();
textBox4.Text = su.ToString();
}
else if (a <= 5000)
{
d = 13;
d1 = ((a * 13) / 100);
su = a - d1;
textBox2.Text = d.ToString();
textBox3.Text = d1.ToString();
textBox4.Text = su.ToString();
}
else if (a <= 8000)
{
d = 15; d1 = ((a * 15) / 100);
su = a - d1;
textBox2.Text = d.ToString();
textBox3.Text = d1.ToString();
textBox4.Text = su.ToString();
}
else if (a > 8000)
{
MessageBox.Show("Ingresar un monto menor o igual a 8000");
}
}
}
}

pág. 16
Ejercicio 4:
Crear un formulario que permita calcular el pago adicional y el monto total a pagar, a partir
de un precio base y un porcentaje adicional según el tipo de servicio del Courier. Mostrar un
mensaje si el monto es negativo.

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 WindowsFormsApplication4
{
public partial class Ejercicio04: Form
{

pág. 17
public Ejercicio05()
{
InitializeComponent();
}
double precio;
double ma = 0, mp;
private void button1_Click(object sender, EventArgs e)
{
double precio = Convert.ToDouble(textBox1.Text);
if (precio > 0)
{
if (radioButton1.Checked)
ma = precio * 0.25;
else if (radioButton2.Checked)
ma = precio * 0.2;
else if (radioButton3.Checked)
ma = precio * 0.10;
else if (radioButton4.Checked)
ma = precio * 0.30;
mp = precio + ma;
textBox2.Text = ma.ToString();
textBox3.Text = mp.ToString();
if (checkBox1.Checked)
label4.Text = "Pago con tarjeta";
else
label4.Text = "Pago en efectivo";
}
else
MessageBox.Show("Precio debe ser mayor que 0");
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
checkBox1.Checked = false;
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
label4.Text = "";
textBox1.Focus();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void textBox4_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)Keys.Enter)
{
precio = Convert.ToDouble(textBox1.Text);
mp = precio + ma;
textBox2.Text = ma.ToString();
textBox3.Text = mp.ToString();
}
}
}
}

pág. 18
Ejercicio 5:
Agregar al ejercicio anterior una opción “Otro servicio” donde el costo adicional en soles
será ingresado por teclado. El pago adicional y el monto total a pagar se calcularán al

pág. 19
seleccionar una de las opciones o al presionar Enter en el caso de la última opción. Además,
mostrar si el pago es en efectivo o con tarjeta, la caja de la última opción estará
deshabilitada hasta que seleccione la opción “Otros”.

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 WindowsFormsApplication4
{
public partial class Ejercicio6: Form
{
public Ejercicio6()
{
InitializeComponent();
}

double preciobase;
double madi = 0, mpag;
private void button1_Click(object sender, EventArgs e)
{
double preciobase = Convert.ToDouble(textBox1.Text);
double madi = 0, mpag;
if (preciobase > 0)
{
if (radioButton1.Checked)
madi = preciobase * 0.25;
else if
(radioButton2.Checked)
madi = preciobase * 0.20;
else if
(radioButton3.Checked)
madi = preciobase * 0.10;
else if

pág. 20
(radioButton4.Checked)
madi = preciobase * 0.30;
else if
(radioButton5.Checked)
madi = preciobase * (Convert.ToDouble(textBox4.Text)) / 100;
mpag = preciobase + madi;
textBox2.Text = madi.ToString();
textBox3.Text = mpag.ToString();
if (checkBox1.Checked)
label4.Text = "Pago con tarjeta";
else
if (radioButton4.Checked)
label4.Text = "Pago efectivo";
}
else
MessageBox.Show("PRECIO DEBE SER MAYOR A CERO");
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox4.Enabled = false;
checkBox1.Checked = false;
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
radioButton5.Checked = false;
label4.Text = "";
textBox1.Focus();
}
private void button3_Click(object sender, EventArgs e)
{
//se puede habilitar en este lugar tambien la caja de texto
textBox4.Enabled = true;
this.Close();
}
private void Ejercicio05_Load(object sender, EventArgs e)
{
textBox4.Enabled = false;
}
private void radioButton5_CheckedChanged(object sender, EventArgs e)
{
textBox4.Enabled = false;
}
private void radioButton5_Click(object sender, EventArgs e)
{
textBox4.Enabled = true;
}
private void textBox4_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)Keys.Enter)
{
preciobase = Convert.ToDouble(textBox1.Text);
madi = preciobase * (Convert.ToDouble(textBox4.Text)) / 100;
mpag = preciobase + madi;
textBox2.Text = madi.ToString();
textBox3.Text = mpag.ToString();
}
}

pág. 21
}
}

Ejercicio 7:
En una tienda de ropa deportiva, se permite seleccionar los productos a comprar y al dar clic
en Calcular se mostrará la cantidad de productos y el total a pagar. Incluir botones para
seleccionar todo y desmarcar todo.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

pág. 22
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Ejercicio7()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
checkBox1.Checked = true;
checkBox2.Checked = true;
checkBox3.Checked = true;
checkBox4.Checked = true;
checkBox5.Checked = true;
}
private void button2_Click(object sender, EventArgs e)
{
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
checkBox4.Checked = false;
checkBox5.Checked = false;
}
private void button3_Click(object sender, EventArgs e)
{
int c = 0, suma = 0;
if (checkBox1.Checked)
{
c++;
suma = suma + 50;
}
if (checkBox2.Checked)
{
c++;
suma = suma + 150;
}
if (checkBox3.Checked)
{
c++;
suma = suma + 40;
}
if (checkBox4.Checked)
{
c++;
suma = suma + 20;
}
if (checkBox5.Checked)
{
c++;
suma = suma + 80;
}
textBox1.Text = c.ToString();
textBox2.Text = suma.ToString();
}
private void button4_Click(object sender, EventArgs e)

pág. 23
{
this.Close();
}
}
}

Ejercicio 8:
En el ejercicio anterior, agregar cajas de texto y botones a cada opción, con la finalidad de
que al dar clic en se habilite la caja de texto correspondiente, y se permita modificar el
costo del producto dando clic en y la caja de texto se volverá a inhabilitar. Luego se
podrá calcular la cantidad de productos y el total a pagar. El botón “…” y “Ok” es el mismo.

using System;
using System.Collections.Generic;

pág. 24
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Ejercicio08: Form
{
public Ejercicio08()
{
InitializeComponent();
}

private void button6_Click(object sender, EventArgs e)


{
checkBox1.Checked = true;
checkBox2.Checked = true;
checkBox3.Checked = true;
checkBox4.Checked = true;
checkBox5.Checked = true;
}
private void button7_Click(object sender, EventArgs e)
{
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
checkBox4.Checked = false;
checkBox5.Checked = false;
}
private void button8_Click(object sender, EventArgs e)
{
double c = 0, suma = 0;
if (checkBox1.Checked)
{
c++;
suma = suma + Convert.ToDouble(textBox1.Text);
}
if (checkBox2.Checked)
{
c++;
suma = suma + Convert.ToDouble(textBox2.Text);
}
if (checkBox3.Checked)
{
c++;
suma = suma + Convert.ToDouble(textBox3.Text);
}
if (checkBox4.Checked)
{
c++;
suma = suma + Convert.ToDouble(textBox4.Text);
}
if (checkBox5.Checked)
{
c++;
suma = suma + Convert.ToDouble(textBox5.Text);
}
textBox6.Text = c.ToString();

pág. 25
textBox7.Text = suma.ToString();
}
private void button9_Click(object sender, EventArgs e)
{
this.Close();
}
private void Ejercicio08_Load(object sender, EventArgs e)
{
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
textBox5.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Enabled = !textBox1.Enabled;
if (textBox1.Enabled)
{
button1.Text = "OK";
}
else
button1.Text = "...";
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Enabled = !textBox2.Enabled;
if (textBox2.Enabled)
{
button2.Text = "OK";
}
else
button2.Text = "...";
}
private void button3_Click(object sender, EventArgs e)
{
textBox3.Enabled = !textBox3.Enabled;
if (textBox3.Enabled)
{
button3.Text = "OK";
}
else
button3.Text = "...";
}
private void button4_Click(object sender, EventArgs e)
{
textBox4.Enabled = !textBox4.Enabled;
if (textBox4.Enabled)
{
button4.Text = "OK";
}
else
button4.Text = "...";
}
private void button5_Click(object sender, EventArgs e)
{
textBox5.Enabled = !textBox5.Enabled;
if (textBox5.Enabled)
{
button5.Text = "OK";
}
else

pág. 26
button5.Text = "...";
}
}
}

Ejercicio 9:
Calcular el total a pagar de un Cliente, en base al precio del producto, al descuento según el
tipo de cliente y a los adicionales de la compra, tal es así que al dar clic en Calcular, se
mostrará el total de descuentos, el total de adicionales y el total a pagar del cliente
ingresado. Las cajas de la opción Otro, se habilitarán sólo cuando se seleccione dicha
opción.Utilizando arreglos y métodos.

using System;
using System.Collections.Generic;

pág. 27
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Ejercicio12: Form
{
RadioButton[] cliente = new RadioButton[4];
CheckBox[] adicional = new CheckBox[4];
TextBox[] cajatexto = new TextBox[6];

public Ejercicio12()
{
InitializeComponent();
}
cliente[0] = radioButton1;
cliente[1] = radioButton2;
cliente[2] = radioButton3;
cliente[3] = radioButton4;
adicional[0] = checkBox1;
adicional[1] = checkBox2;
adicional[2] = checkBox3;
adicional[3] = checkBox4;
cajatexto[0] = textBox1;
cajatexto[1] = textBox2;
cajatexto[2] = textBox3;
cajatexto[3] = textBox4;
cajatexto[4] = textBox5;
cajatexto[5] = textBox6;
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
string nombre = Convert.ToString(textBox5.Text);
}
private void Ejercicio12_Load(object sender, EventArgs e)
{
textBox3.Enabled = false;
textBox4.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
double a = Convert.ToDouble(textBox6.Text);
double descuento = 0;
if (radioButton1.Checked)
descuento = descuento + a * 0.20;
if (radioButton2.Checked)
descuento = descuento + a * 0.15;
if (radioButton3.Checked)
descuento = descuento + a * 0.10;
if (radioButton4.Checked)
{
textBox1.Enabled = true;
descuento = descuento + Convert.ToDouble(textBox1.Text);

pág. 28
}
textBox3.Text = descuento.ToString();
double adicional = 0;
if (checkBox1.Checked)
adicional = adicional + 5;
if (checkBox2.Checked)
adicional = adicional + 10;
if (checkBox3.Checked)
adicional = adicional + 25;
if (checkBox4.Checked)
{
textBox2.Enabled = true;
adicional = adicional + Convert.ToDouble(textBox2.Text);
}
textBox4.Text = adicional.ToString();
label6.Text = "Sr(a)" + "" + "" + textBox5.Text + ", Total a pagar:" + ((a -
descuento) + adicional).ToString() + "Nuevos Soles";
}
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
textBox1.Enabled = true;
}
private void radioButton4_Click(object sender, EventArgs e)
{
textBox1.Enabled = true;
}
private void checkBox4_Click(object sender, EventArgs e)
{
textBox2.Enabled = true;
}
}

private void button2_Click(object sender, EventArgs e)


{
textBox1.Text = ""; //textBox1.Clear();
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
checkBox4.Checked = false;
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
textBox5.Focus();
}
private void button1_Click(object sender, EventArgs e)
{
double a = Convert.ToDouble(textBox6.Text);
double descuento = 0;
if (radioButton1.Checked)
descuento = descuento + a * 0.20;
if (radioButton2.Checked)
descuento = descuento + a * 0.15;
if (radioButton3.Checked)
descuento = descuento + a * 0.10;
if (radioButton4.Checked)
{

pág. 29
textBox1.Enabled = true;
descuento = descuento + Convert.ToDouble(textBox1.Text);
}
textBox3.Text = descuento.ToString();
double adicional = 0;
if (checkBox1.Checked)
adicional = adicional + 5;
if (checkBox2.Checked)
adicional = adicional + 10;
if (checkBox3.Checked)
adicional = adicional + 25;
if (checkBox4.Checked)
{
textBox2.Enabled = true;
adicional = adicional + Convert.ToDouble(textBox2.Text);
}
textBox4.Text = adicional.ToString();
label6.Text = "Sr(a)" + "" + "" + textBox5.Text + ", Total a pagar:" + ((a -
descuento) + adicional).ToString();
}
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
textBox1.Enabled = true;
}
private void radioButton4_Click(object sender, EventArgs e)
{
textBox1.Enabled = true;
}
private void checkBox4_Click(object sender, EventArgs e)
{
textBox2.Enabled = true;
}
}
}

pág. 30
Ejercicio 10: (Practica Calificada I)
Ejercicio 11: (Practica Calificada I)
Ejercicio 12: (Practica Calificada I)
Ejercicio 13:
Elaborar un formulario que permita cambiar una imagen a través de un radioButton y un
botón.

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 WindowsFormsApplication4
{
public partial class Ejercicio13: Form
{

public Ejercicio13()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{

pág. 31
if (radioButton1.Checked) pictureBox1.Image =
Image.FromFile(Application.StartupPath + "\\anime\\itachi.jpg");
else if (radioButton2.Checked) pictureBox1.Image =
Image.FromFile(Application.StartupPath + "\\anime\\pain.png");
else if (radioButton3.Checked) pictureBox1.Image =
Image.FromFile(Application.StartupPath + "\\anime\\ichigo.png");
else MessageBox.Show("DEBE SELECCIONAR UNA OPCION!!");
}
}
}

pág. 32
Ejercicio 14:
ELABORAR UN FORMULARIO QUE PERMITA CAMBIAR UNA IMAGEN UNA OPCIÓN DE
RADIOBUTTON.

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 WindowsFormsApplication4
{
public partial class Ejercicio 14: Form
{

public Ejercicio14()
{
InitializeComponent();
}

private void radioButton1_Click(object sender, EventArgs e)


{
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\im\\tv.jpg");
}
private void radioButton2_Click(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\im\\computadora.jpg");
}
}
}

pág. 33
Ejercicio 15:
Crear un formulario, que muestre la imagen de un producto (pictureBox) y su detalle, al
seleccionar una opción.

pág. 34
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 WindowsFormsApplication4
{
public partial class Ejercicio15: Form
{

public Ejercicio15()
{
InitializeComponent();
}

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
if (radioButton1.Checked)
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\Imagenes\\Imagen5.jpg");
textBox1.Text = "1247";
richTextBox1.Text = "hermoso color con facilidad de manejo";
textBox3.Text = " S/. 125.00";
textBox4.Text = "50";
}
private void radioButton2_CheckedChanged_1(object sender, EventArgs e)
{
if (radioButton2.Checked)
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\Imagenes\\Imagen6.jpg");
textBox1.Text = "1248";
richTextBox1.Text = "color plomo incluye bateria";
textBox3.Text = " S/. 50.00";
textBox4.Text = "13";
}
private void radioButton3_CheckedChanged_1(object sender, EventArgs e)
{
if (radioButton3.Checked)
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\Imagenes\\Imagen7.jpg");
textBox1.Text = "1244";
richTextBox1.Text = "Alta resolucion de imagen empotrable con facilidad en
pared";
textBox3.Text = " S/. 325.00";
textBox4.Text = "17";
}
private void radioButton4_CheckedChanged_1(object sender, EventArgs e)
{
if (radioButton4.Checked)
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\Imagenes\\Imagen8.jpg");
textBox1.Text = "1245";
richTextBox1.Text = "mutifuncional con caracteristicas unicas";
textBox3.Text = " S/. 325.00";
textBox4.Text = "25";
}
private void textBox1_TextChanged(object sender, EventArgs e)

pág. 35
{
double a = Convert.ToDouble(textBox1.Text);
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Ejercicio 16:
Elaborar un programa
que simule un juego
de imágenes, si se
obtiene 2 imágenes
iguales el participante
gana 5 puntos y si
obtiene 3 imágenes
iguales, 15 puntos. Las
imágenes y el puntaje
se actualizan al dar
clic en el botón
Mostrar. El juego
termina si el
participante obtiene
50 puntos, para lo cual se muestra un mensaje de “GANASTE”. El botón Mostrar está en
Iniciar juego al inicio del juego y en Reiniciar juego al terminar el juego (Utilizar la función
Ramdom, y nombrar a las imágenes con número del 1 al 10).

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;

pág. 36
namespace WindowsFormsApplication4
{
public partial class Ejercicio16: Form
{
int puntaje = 0;

public Ejercicio16()
{
InitializeComponent();
button1.Visible = true;
button2.Visible = false;
}
private void button2_Click(object sender, EventArgs e)
{
Random r = new Random();
int n1, n2, n3;
n1 = r.Next(1, 10);
n2 = r.Next(1, 10);
n3 = r.Next(1, 10);
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\imagenes\\" + n1 + ".jpg");
pictureBox2.Image = Image.FromFile(Application.StartupPath +
"\\imagenes\\" + n2 + ".jpg");
pictureBox3.Image = Image.FromFile(Application.StartupPath +
"\\imagenes\\" + n3 + ".jpg");

if (n1 == n2 & n2 == n3) puntaje = puntaje + 15;


else if (n1 == n2 || n1 == n3 || n2 == n3) puntaje = puntaje + 10;
label1.ForeColor = Color.Red;
label1.Text = "Puntaje :" + puntaje.ToString();
if (puntaje >= 50)
{
MessageBox.Show("Win!!", "messagebox", MessageBoxButtons.OK,
MessageBoxIcon.Information);
button2.Text = "reiniciar juego"; if (button2.Text == "reiniciar
juego")
{
puntaje = 0; button2.Text = "mostrar";
}
}
}
private void button1_Click(object sender, EventArgs e)
{ button1.Visible = false;
button2.Visible = true; }
private void Form14_Load(object sender, EventArgs e)
{ button1.Visible = true;
button2.Visible = false; }
}
}

pág. 37
pág. 38
Ejercicio 17:
Elaborar un programa que simule un juego, en el cual se adivine la relación (“>”, “<” o “=”)
entre 2 cartas de diferente color al dar clic en Verificar. El juego termina cuando se llega a
un máximo de 21 intentos o cuando el participante llega a 7 aciertos. En cada verificación se
mostrará un mensaje de que si acertó o no, además de indicar la cantidad de aciertos e
intentos. Incorpore al programa el poder elegir si salir del juego o volver a jugar, con un
MessageBox que tenga las opciones de Si, No y Cancelar.

pág. 39
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 WindowsFormsApplication4
{
public partial class Ejercicio17: Form
{

public Ejercicio17()
{
InitializeComponent();

}
Int32 aciertos = 0;
Int32 intentos = 0;
private void Verificar_Click(object sender, EventArgs e)
{
Int32 num1, num2;
Boolean band = false;
String msj = "";
intentos++;
Random azar = new Random();
num1 = azar.Next(1, 13);
num2 = azar.Next(1, 13);
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\ImagenesCartas\\" + num1 + ".png");
pictureBox2.Image = Image.FromFile(Application.StartupPath +
"\\ImagenesCartas\\" + num2 + ".png");
if (Mayor_que.Checked || Menor_que.Checked || Igual_que.Checked)
{
if (Mayor_que.Checked && num1 > num2)
{
aciertos++;
label1.Text = "ACERTÓ";
}
else if ((Menor_que.Checked && num1 < num2))
{
aciertos++;
label1.Text = "ACERTO";
}
else if (Mayor_que.Checked && num1 == num2)
{
aciertos++;
label1.Text = "ACERTÓ";
}
else label1.Text = "NO ACERTÓ";
label2.Text = aciertos + " aciertos / " + intentos + " intentos";
if (intentos <= 21 && aciertos >= 7)
{
msj = "GANÓ EL JUEGO!!!. Desea continuar jugando?";
band = true;
}
if (intentos == 21 && aciertos < 7)
{
msj = "PERDIÓ!!!. Desea continuar jugando?";

pág. 40
band = true;
}
if (band == true)
{
DialogResult res = MessageBox.Show(msj, "Mensaje",
MessageBoxButtons.YesNoCancel);
if (res == DialogResult.Yes)
{
intentos = 0;
aciertos = 0;
label1.Text = "";
label2.Text = "";
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\ImagenesCartas\\14.png");
pictureBox2.Image = Image.FromFile(Application.StartupPath +
"\\ImagenesCartas\\14.png");
}
else if (res == DialogResult.No)
this.Close();
}
}
}
private void Ejercicio19_Load(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\ImagenesCartas\\14.png"); pictureBox2.Image =
Image.FromFile(Application.StartupPath +
"\\ImagenesCartas\\14.png");
}

private void button1_Click(object sender, EventArgs e)


{
this.Close();
}
}
}

pág. 41
pág. 42
Ejercicio 18:
Calcular el promedio de un alumno, ingresando sus calificaciones con sus respectivos pesos,
los cuales se mostrarán en unas listas.

using System;
using

System.Collections.Generic;

pág. 43
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Ejercicio18: Form
{

public Ejercicio18()
{
InitializeComponent();

}
private void button1_Click(object sender, EventArgs e)
{
lista1.Items.Add(textBox1.Text);
lista2.Items.Add(textBox2.Text);
textBox1.Clear();
textBox2.Clear();
textBox1.Focus();
}
private void button2_Click(object sender, EventArgs e)
{
double s = 0, sp = 0;
for (int i = 0; i < lista1.Items.Count; i++)
{
s += Convert.ToDouble(lista1.Items[i]) *
Convert.ToDouble(lista2.Items[i]);
sp += Convert.ToDouble(lista2.Items[i]);
}
textBox3.Text = Math.Round((s / sp), 2).ToString();
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
lista1.Items.Clear();
lista2.Items.Clear();
textBox1.Focus();
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

pág. 44
Ejercicio 19:
Elaborar un formulario, que permita agregar cursos a una lista (botón o Enter), y que se
pueda pasar los cursos de una lista a otra lista.

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 WindowsFormsApplication4

pág. 45
{
public partial class Ejercicio19 : Form
{

public Ejercicio19()
{
InitializeComponent();

}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar))
{ e.Handled = true; MessageBox.Show("Solo puede ingresar valores de tipo
cadena");
}
else if (char.IsLetter(e.KeyChar)) e.Handled = false;
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
textBox1.Text = "";
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)(Keys.Enter))
{ listBox1.Items.Add(textBox1.Text);
textBox1.Text = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{ listBox2.Items.Add(listBox1.Items[i]);
}
listBox1.Items.Clear();
}
private void button3_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{ listBox2.Items.Add(listBox1.SelectedItem);
listBox1.Items.Remove(listBox1.SelectedItem);
}
else MessageBox.Show("Seleccione un curso");
}
private void button4_Click(object sender, EventArgs e)
{
if (listBox2.SelectedItem != null)
{
listBox1.Items.Add(listBox2.SelectedItem);
listBox2.Items.Remove(listBox2.SelectedItem);
}
else MessageBox.Show("Seleccione un curso");
}
private void button5_Click(object sender, EventArgs e)
{
for (int i = 0; i < listBox2.Items.Count; i++)
listBox1.Items.Add(listBox2.Items[i]); listBox2.Items.Clear();
}
}
}

pág. 46
pág. 47
Ejercicio 20:
Elaborar un formulario, que permita matricular estudiantes, seleccionando un grupo,
además se podrá pasar 1 o más estudiantes de un grupo a otro (selección múltiple), para lo
cual se actualizará el total de estudiantes de cada grupo. Además se podrá buscar a un
estudiante (el cual se mostrará seleccionado), dando clic en el botón Buscar, en caso de no
encontrarlo se mostrará un mensaje: “No se encontró al estudiante”.

pág. 48
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 WindowsFormsApplication4
{
public partial class Ejercicio20: Form
{

public Ejercicio20()
{
InitializeComponent();

}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.Text == "A")
listBox1.Items.Add(textBox1.Text);
else
listBox2.Items.Add(textBox1.Text);
textBox1.Text = "";
comboBox1.Text = "";
textBox1.Focus();
CalcularTotales();
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex >= 0)
{
foreach (string item in listBox1.SelectedItems)
listBox2.Items.Add(item);
for (int i = listBox1.SelectedItems.Count - 1; i >= 0; i--)
listBox1.Items.Remove(listBox1.SelectedItems[i]);
}
else
MessageBox.Show("Seleccione!!");
CalcularTotales();
}
private void button3_Click(object sender, EventArgs e)
{
if (listBox2.SelectedIndex >= 0)
{
foreach (string item in listBox2.SelectedItems)
listBox1.Items.Add(item);
for (int i = listBox2.SelectedItems.Count - 1; i >= 0; i--)
listBox2.Items.Remove(listBox2.SelectedItems[i]);
}
else
MessageBox.Show("Seleccione!!");
CalcularTotales();
}
private void CalcularTotales()
{
label5.Text = "Total Grupo A: " + (listBox1.Items.Count);
label6.Text = "Total Grupo B: " + (listBox2.Items.Count);
}

pág. 49
private void button4_Click(object sender, EventArgs e)
{
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
Int32 indice = (listBox1.FindStringExact(textBox2.Text));
Int32 indice2 = (listBox2.FindStringExact(textBox2.Text));
if (indice >= 0)
{
listBox1.SetSelected(indice, true);
textBox2.Text = "";
textBox2.Focus();
}
else if (indice2 >= 0)
{
listBox2.SetSelected(indice2, true);
textBox2.Text = "";
textBox2.Focus();
}
else
MessageBox.Show("No se encontró al estudiante");
}
}
}

pág. 50
pág. 51
pág. 52
Ejercicio 21:
Elaborar un programa que permita ingresar los datos personales de los empleados de una
empresa. Al dar clic en Grabar, los datos personales se agregaran a las listas respectivas. Si
el usuario da un clic en algún item de las listas, todo el registro del empleado debe quedar
seleccionado y sus datos visualizados en las cajas de texto correspondientes. Se puede hacer
búsqueda por DNI o Apellidos, al presionar Enter o con el botón Buscar; si se encontró el
empleado, su registro debe aparecer seleccionado o en caso contrario mostrar un mensaje.
Para el DNI, sólo se debe permitir ingresar números y para los apellidos (en mayúsculas) y
nombres sólo letras.

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 WindowsFormsApplication4
{
public partial class Ejercicio21 : Form
{
public Ejercicio21()
{
InitializeComponent();
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)


{ if (char.IsLetter(e.KeyChar))

pág. 53
{
e.Handled = true;
MessageBox.Show("Debe ingresar valores numericos!");
}
else if (char.IsNumber(e.KeyChar))
{
e.Handled = false;
}
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Debe ingresar valores tipo cadena!");
}
else if (char.IsLetter(e.KeyChar))
{
e.Handled = false;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] nombres;
listBox1.SelectedIndex = -1;
int indice = listBox1.FindStringExact(textBox1.Text);
nombres = new string[listBox1.Items.Count];
int tam = textBox2.TextLength;
for (int i = 0; i < listBox1.Items.Count; i++) nombres[i] =
listBox1.Items[i].ToString();
listBox2.SelectedIndex = -1;
for (int i = 0; i < listBox1.Items.Count; i++) if (nombres[i].Substring(0,
tam) == textBox2.Text)
{
listBox1.SetSelected(i, true);
listBox2.SetSelected(i, true);
listBox3.SetSelected(i, true);
listBox4.SetSelected(i, true);
listBox5.SetSelected(i, true);
}
else if (indice >= 0)
{
listBox1.SetSelected(indice, true);
listBox2.SetSelected(indice, true);
listBox3.SetSelected(indice, true);
listBox4.SetSelected(indice, true);
listBox5.SetSelected(indice, true);
}
else MessageBox.Show(“No encontrado”);
}

private void button1_Click(object sender, EventArgs e)


{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
comboBox1.Text = "";
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
listBox1.SelectedIndex = -1;

pág. 54
listBox2.SelectedIndex = -1;
listBox3.SelectedIndex = -1;
listBox4.SelectedIndex = -1;
listBox5.SelectedIndex = -1;
textBox1.Focus();
}
private void button2_Click(object sender, EventArgs e)
{

if ((radioButton1.Checked || radioButton2.Checked || radioButton3.Checked)


&& comboBox1.Text != string.Empty)
{
listBox1.Items.Add(textBox1.Text);
listBox2.Items.Add(textBox2.Text + " " + textBox3.Text);
listBox3.Items.Add(textBox4.Text);
listBox4.Items.Add(comboBox1.Text);
if (radioButton1.Checked) listBox5.Items.Add(radioButton1.Text);
else if (radioButton2.Checked) listBox5.Items.Add(radioButton2.Text);
else listBox5.Items.Add(radioButton3.Text);
}
else MessageBox.Show("Debe asegurar de seleccionar un estado civil y
elegir una nivel de instruccion");
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
int indice = listBox1.FindStringExact(textBox1.Text);
if (indice >= 0)
{
listBox1.SetSelected(indice, true);
listBox2.SetSelected(indice, true);
listBox3.SetSelected(indice, true);
listBox4.SetSelected(indice, true);
listBox5.SetSelected(indice, true);
}

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

pág. 55
pág. 56
Ejercicio 22:
Elaborar un programa para dar mantenimiento a los productos de un almacén. Al dar clic en
Grabar, los datos del producto se agregarán a las listas respectivas, mostrándose el total de
productos y la cantidad total de productos en almacén. Se puede hacer búsqueda por
código o nombre, al presionar Enter o con el botón Buscar, seleccionándose el registro del
producto encontrado, caso contrario se mostrará mensaje de que no existe el producto.
Además, se puede actualizar o eliminar algún producto seleccionado. El código se generará
automáticamente con las 2 iniciales del producto más un número correlativo, al dar clic en
Grabar. Para cargar la imagen, se buscará la imagen al dar clic en el botón (…) para luego
visualizar el nombre de la imagen, o su ruta. El nombre se debe ingresar en mayúsculas y
sólo letras.

pág. 57
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 WindowsFormsApplication4
{
public partial class Ejercicio22: Form
{
public Ejercicio22()
{
InitializeComponent();
}
int c, suma = 0;
private void Nuevo_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox2.Focus();
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
listBox3.SelectedIndex = -1;
listBox4.SelectedIndex = -1;
listBox5.SelectedIndex = -1;
}
private void Grabar_Click(object sender, EventArgs e)
{
c++;
listBox1.Items.Add(textBox2.Text.Substring(0, 2) + c);//
listBox2.Items.Add(textBox2.Text);
listBox5.Items.Add(textBox4.Text);
if (radioButton1.Checked)
listBox3.Items.Add(radioButton1.Text);
else if (radioButton2.Checked)
listBox3.Items.Add(radioButton2.Text);
else
listBox3.Items.Add(radioButton3.Text);
listBox4.Items.Add(textBox3.Text);
suma = suma + Convert.ToInt32(textBox3.Text);
textBox5.Text = listBox1.Items.Count.ToString();
textBox6.Text = suma.ToString();
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsNumber(e.KeyChar) ||
Char.IsPunctuation(e.KeyChar) || Char.IsSymbol(e.KeyChar))
e.Handled = true;
}
private void Imagen_Click(object sender, EventArgs e)
{//cargar imagen
pictureBox1.Image = Image.FromFile(Application.StartupPath +
textBox4.Text);

pág. 58
}
private void Buscar_Click(object sender, EventArgs e)
{//buscar al pulsar el boton
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
Int32 indice = (listBox1.FindStringExact(textBox1.Text));
Int32 indice2 = (listBox2.FindStringExact(textBox2.Text));
if (indice >= 0)
{
listBox1.SetSelected(indice, true);
listBox2.SetSelected(indice, true);
listBox3.SetSelected(indice, true);
listBox4.SetSelected(indice, true);
listBox5.SetSelected(indice, true);
}
else if (indice2 >= 0)
{
listBox2.SetSelected(indice2, true);
listBox1.SetSelected(indice2, true);
listBox3.SetSelected(indice2, true);
listBox4.SetSelected(indice2, true);
listBox5.SetSelected(indice2, true);
}
else
{
MessageBox.Show("No se encontró producto");
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
listBox3.SelectedIndex = -1;
listBox4.SelectedIndex = -1;
listBox5.SelectedIndex = -1;
}
}
private void Eliminar_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
for (int i = 0; i <= listBox1.Items.Count; i++)
{
listBox1.Items.Remove(listBox1.SelectedItem);
listBox2.Items.Remove(listBox2.SelectedItem);
listBox3.Items.Remove(listBox3.SelectedItem);
listBox4.Items.Remove(listBox4.SelectedItem);
listBox5.Items.Remove(listBox5.SelectedItem);
}
}
else
{
MessageBox.Show("Seleccione un producto !!");
}
textBox5.Text = listBox1.Items.Count.ToString();
textBox6.Text = suma.ToString();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{//SELECCION PRODUCTO
int indice = listBox1.SelectedIndex;
if (indice >= 0)
{
listBox2.SetSelected(indice, true);
listBox3.SetSelected(indice, true);
listBox4.SetSelected(indice, true);
listBox5.SetSelected(indice, true);

pág. 59
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{//buscar enter por codigo
listBox1.SelectedIndex = -1;
Int32 indice = listBox1.FindStringExact(textBox1.Text);
if (e.KeyValue == (char)(Keys.Enter))
{
if (indice >= 0)
{
listBox1.SetSelected(indice, true);
listBox2.SetSelected(indice, true);
listBox3.SetSelected(indice, true);
listBox4.SetSelected(indice, true);
listBox5.SetSelected(indice, true);
}
else
{
MessageBox.Show("Producto no encontrado !!");
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
listBox3.SelectedIndex = -1;
listBox4.SelectedIndex = -1;
listBox5.SelectedIndex = -1;
}
}
}
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{//bUscar enter por nombre
listBox2.SelectedIndex = -1;
Int32 indice = listBox2.FindStringExact(textBox2.Text);
if (e.KeyValue == (char)(Keys.Enter))
{
if (indice >= 0)
{
listBox1.SetSelected(indice, true);
listBox2.SetSelected(indice, true);
listBox3.SetSelected(indice, true);
listBox4.SetSelected(indice, true);
listBox5.SetSelected(indice, true);
}
else
{
MessageBox.Show("No se encontro el producto !!!");
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
listBox3.SelectedIndex = -1;
listBox4.SelectedIndex = -1;
listBox5.SelectedIndex = -1;
}
}
}
private void Salir_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

pág. 60
pág. 61
Ejercicio 23:
Construir un programa que simule las elecciones de una provincia, en la cual existen 5
distritos y 4 candidatos, los votos por distrito y candidato serán llenados aleatoriamente, al
dar clic en el botón Simular votaciones. Los resultados por candidato serán mostrados
desde el más votado al menos votado, además de indicar cuál es el candidato “Ganador” si
obtuvo más del 50% de los votos o de caso contrario los 2 candidatos más votados que
pasarán a segunda vuelta, al dar clic en el botón Calcular resultados.

pág. 62
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 WindowsFormsApplication4
{
public partial class Ejercicio23 : Form
{
public Ejercicio23()
{
InitializeComponent();
votos = new TextBox[5, 4] { { textBox1, textBox2, textBox3, textBox4 },
{ textBox5, textBox6, textBox7, textBox8 },
{ textBox9, textBox10, textBox11, textBox12 },
{ textBox13, textBox14, textBox15, textBox16 },
{ textBox17, textBox18, textBox19, textBox20 } };
resul = new TextBox[4] { textBox21, textBox22, textBox23, textBox24 };
resul2 = new TextBox[4] { textBox25, textBox26, textBox27, textBox28 };
cand = new Label[4] { label12, label13, label14, label15 };
cand2 = new Label[4] { label17, label18, label19, label20 };
}
TextBox[,] votos;
TextBox[] resul;
Label[] cand;
TextBox[] resul2;
Label[] cand2;
Int32[] numeros = new Int32[4];

pág. 63
Char[] c;
Int32 cv, tv;
private void button1_Click(object sender, EventArgs e)
{
Random ale = new Random();
for (int i = 0; i < 5; i++) for (int j = 0; j < 4; j++)
{
votos[i, j].Text = ale.Next(10, 101).ToString();
}

}
private void button2_Click(object sender, EventArgs e)
{
tv = 0; c = new Char[4] { 'A', 'B', 'C', 'D' };
for (int j = 0; j < 4; j++)
{ cv = 0; for (int i = 0; i < 5; i++)
{ cv = cv + Convert.ToInt32(votos[i, j].Text);
tv = tv + Convert.ToInt32(votos[i, j].Text);
} resul[j].Text = cv.ToString();
numeros[j] = cv;
}
textBox26.Text = tv.ToString(); ordenar();
for (int i = 0; i < 4; i++)
{ resul2[i].Text = numeros[i].ToString();
cand2[i].Text = c[i].ToString();
}
if (Convert.ToInt32(resul2[0].Text) > (0.5 * tv))
{
label22.Text = "GANADOR: Candidato " + cand2[0].Text;
label21.Text = "";
}
else { label21.Text = "Candidatos " + c[0] + " y " + c[1] + " pasan a
segunda vuelta";
}
}
private void ordenar()
{
for (int k = 0; k < 3; k++)
{
for (int f = 0; f < 3 - k; f++)
{
if (numeros[f] < numeros[f + 1])
{
int aux; aux = numeros[f]; numeros[f] = numeros[f + 1];
numeros[f + 1] = aux;
char aux2; aux2 = c[f]; c[f] = c[f + 1]; c[f + 1] = aux2;
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{ this.Close();
}
}
}

pág. 64
pág. 65
Ejercicio 24:
Programar en un formulario un “Juego de memoria”, donde se tenga 6 pares de imágenes,
distribuidas en 3 filas y 3 columnas de manera aleatoria, al inicio todas las celdas tendrán
una imagen inicial (Ej. ?), las que se irán volteando al dar clic en cada una de ellas. Si las
imágenes son iguales se mostrará un mensaje de “Acertaste!!!”, en caso contrario las
imágenes se volverán a ocultar, el juego termina cuando todas las imágenes son
descubiertas. El juego puede volver a empezar.

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;
//Para la pausa
using System.Threading;

namespace WindowsFormsApplication4
{
public partial class Ejercicio24 : Form

pág. 66
{
public Ejercicio24()
{
InitializeComponent();
}
PictureBox img1 = new PictureBox();
PictureBox img2 = new PictureBox();
//DECLARAMOS LA MATRIZ
PictureBox[,] celda = new PictureBox[4, 4];
int contador = 0, intentos = 0;
private void crear_celdas()
{
for (int c = 0; c < 4; c++) for (int f = 0; f < 4; f++)
{
celda[f, c] = new PictureBox();
celda[f, c].Width = 100;
celda[f, c].Height = 100;
celda[f, c].Top = 105 * f;
celda[f, c].Left = 105 * c;
celda[f, c].SizeMode = PictureBoxSizeMode.StretchImage;
celda[f, c].Image = Image.FromFile(Application.StartupPath +
"\\IMAGES\\" + "img.jpg");
Controls.Add(celda[f, c]);
celda[f, c].Click += new System.EventHandler(this.celda_Click);
}
}
//CREAMOS EL EVENTO
private void celda_Click(object sender, EventArgs e)
{
contador++;
PictureBox c = sender as PictureBox;
c.Image = Image.FromFile(Application.StartupPath + "\\IMAGES\\" +
c.Tag.ToString());
if (contador == 1)
//primera imagen
img1 = c;
else //contador == 2
{
intentos++;
//segunda imagen
img2 = c;
contador = 0;
label1.Text = "Intentos = " + intentos.ToString();
if (img1.Tag.ToString().Equals(img2.Tag.ToString()))
{
MessageBox.Show("ACERTASTE!!"); img1.Enabled = false;
img2.Enabled = false;
}
//Si las imágenes no son iguales
else
{
//ACTUALIZAR imagen 2
img2.Refresh();
//pausa en milisegundos
Thread.Sleep(1200);
img1.Image = Image.FromFile(Application.StartupPath + "\\IMAGES\\"
+"img.jpg");
img2.Image = Image.FromFile(Application.StartupPath + "\\IMAGES\\"
+ "img.jpg");
}
}
}

pág. 67
private void llenar_nombres_en_vector()
{
for (int i = 1; i <= 8; i++)
{
//Asignamos la pareja de imágenes
listBox1.Items.Add(i.ToString() + ".jpg");
listBox1.Items.Add(i.ToString() + ".jpg");
}
}
//Creamos método para asignar imágenes
private void asignar_imagenes()
{
llenar_nombres_en_vector();
Random r = new Random();
int posicion;
for (int c = 0; c < 4; c++)
for (int f = 0; f < 4; f++)
{
//sacar un numero de 0 hasta el tamaño de la lista
posicion = r.Next(0, listBox1.Items.Count);
celda[f, c].Tag = listBox1.Items[posicion].ToString();
//asignar en el tag
listBox1.Items.RemoveAt(posicion);
}
}
private void Form1_Load(object sender, EventArgs e)
{ //llamamos al método
crear_celdas(); asignar_imagenes();
}
}
}

pág. 68
pág. 69
pág. 70
pág. 71
pág. 72
Ejercicio 25:
Elaborar un programa que simule el comportamiento de un semáforo.

pág. 73
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 WindowsFormsApplication4
{
public partial class Ejercicio25: Form
{
char color = ' ';
public Ejercicio25()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
panel1.BackColor = Color.Red;
panel2.BackColor = Color.Black;
panel3.BackColor = Color.Black;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (panel1.BackColor == Color.Red)
{
panel1.BackColor = Color.Black;
panel2.BackColor = Color.Yellow;
color = 'R';
}
else if (panel2.BackColor == Color.Yellow)
{
if (color == 'R')
{ panel2.BackColor = Color.Black;
panel3.BackColor = Color.Green;
}
else if (color == 'V')
{
panel2.BackColor = Color.Black;
panel1.BackColor = Color.Red;
}
}
else
{
panel3.BackColor = Color.Black;
panel2.BackColor = Color.Yellow;
color = 'V'; }
}
}
}

pág. 74
pág. 75
pág. 76
Ejercicio 26:
Elaborar un formulario que simule un semáforo peatonal, con cuenta regresiva a partir de 5
segundos.

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 WindowsFormsApplication4
{
public partial class Ejercicio26 : Form
{

public Ejercicio26()
{
InitializeComponent();
panel1.BackColor = Color.Red;
}
int contador = 6, contador1 = 6;
private void timer1_Tick(object sender, EventArgs e)
{
if (panel1.BackColor == Color.Red)
{

pág. 77
contador--;
textBox1.Text = contador.ToString();
label1.Text = contador.ToString();
if (contador == 0)
{
panel2.BackColor = Color.Green;
panel1.BackColor = Color.Black;
contador1 = 6;
}
}
else if (panel2.BackColor == Color.Green)
{
contador1--;
textBox2.Text = contador1.ToString();
label2.Text = contador1.ToString();
if (contador1 == 0)
{
panel1.BackColor = Color.Red;
panel2.BackColor = Color.Black;
}
contador = 6;
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
}
}

pág. 78
pág. 79
Ejercicio 27:
Elaborar un programa que simule a una persona pateando una pelota hacia una pared. La
velocidad de la pelota se puede incrementar o disminuir con un ScrollBar.

pág. 80
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 WindowsFormsApplication4
{
public partial class Ejercicio27: Form
{
public Ejercicio27()
{
InitializeComponent();
}
Int32 temp = 1;
private void timer1_Tick(object sender, EventArgs e)
{
if (temp == 1)
{
if ((pictureBox2.Left + pictureBox2.Width) <= pictureBox3.Left)
pictureBox2.Left = pictureBox2.Left + 20;
else
temp = 0;
}
else

pág. 81
{
if (pictureBox2.Left >= (pictureBox1.Left + pictureBox1.Width))
pictureBox2.Left = pictureBox2.Left - 20;
else
temp = 1;
}
}
private void Pared_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
timer1.Interval = 100 - hScrollBar1.Value;
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}

pág. 82
Ejercicio 28:
Realizar un formulario que simule a una persona cruzando la calle (ida o vuelta), para lo cual
tomará en cuenta las luces del semáforo peatonal, y las del semáforo vehicular para algún
vehículo (opcional). La velocidad de la persona se puede incrementar. (Considere a su
criterio los demás aspectos necesarios para tal simulación).

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 WindowsFormsApplication4
{
public partial class Ejercicio28: Form
{
int temp = 1;
char color = ' ';
public Ejercicio28()
{
InitializeComponent();
}
private void Form6_Load(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\image\\calle.jpg");

pág. 83
pictureBox2.Image = Image.FromFile(Application.StartupPath +
"\\image\\persona.jpg");
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer2.Enabled = true;
}
private void timer2_Tick(object sender, EventArgs e)
{
if (temp == 1)
{ if ((pictureBox2.Left + pictureBox2.Width) <= (pictureBox1.Width))
{ pictureBox2.Left = pictureBox2.Left + 25;
} else
{
temp = 0;
}
}
else if (temp == 0)
{
pictureBox2.Left = pictureBox2.Left - 25;
if (((2 * pictureBox2.Left) - pictureBox2.Width) <=
(pictureBox1.Left / 20))
{
temp = 1;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (panel1.BackColor == Color.Red)
{
panel1.BackColor = Color.Black; panel2.BackColor = Color.DarkOrange;
color = 'R'; timer2.Enabled = true;
}
else if (panel2.BackColor == Color.DarkOrange)
{
if (color == 'R')

{
panel2.BackColor = Color.Black; panel3.BackColor = Color.Green;
timer2.Enabled = true;
}
else if (color == 'V')
{
panel2.BackColor = Color.Black;
panel1.BackColor = Color.Red;
timer2.Enabled = false;
}
}
else
{
panel3.BackColor = Color.Black;
panel2.BackColor = Color.DarkOrange;
color = 'V'; timer2.Enabled = true;
}
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
timer2.Interval = 300 - 3 * hScrollBar1.Value;
}
private void button2_Click(object sender, EventArgs e)

pág. 84
{
this.Close();
}
}
}

pág. 85
Ejercicio 29:
Elaborar un programa que simule el movimiento de 2 pelotas en distintas direcciones,
dentro de un formulario. Sus velocidades se podrán controlar con barras de desplazamiento.

pág. 86
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 WindowsFormsApplication4
{
public partial class Ejercicio29 : Form
{
bool movDerechaRed, movArribaRed;
bool movDerechaBlue, movArribaBlue;
public Ejercicio29()
{
InitializeComponent();
}
private void Form7_Load(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\imag\\redball.jpg");
pictureBox2.Image = Image.FromFile(Application.StartupPath +
"\\imag\\blueball.png");
timer1.Start(); timer2.Start();

pág. 87
}
private void timer1_Tick(object sender, EventArgs e)
{
if (movDerechaRed == true) pictureBox1.Left += 20;
else pictureBox1.Left -= 20;
if (movArribaRed == true) pictureBox1.Top -= 20;
else pictureBox1.Top += 20;
if (pictureBox1.Left <= this.ClientRectangle.Left) movDerechaRed = true;
if (pictureBox1.Left + pictureBox1.Width >= this.ClientRectangle.Right)
movDerechaRed = false;
if (pictureBox1.Top <= this.ClientRectangle.Top) movArribaRed = false;
if (pictureBox1.Top + pictureBox1.Height >= this.ClientRectangle.Bottom)
movArribaRed = true;
}
private void timer2_Tick(object sender, EventArgs e)
{
if (movDerechaBlue == true) pictureBox2.Left += 20;
else pictureBox2.Left -= 20;
if (movArribaBlue == true) pictureBox2.Top -= 20;
else pictureBox2.Top += 20;
if (pictureBox2.Left <= this.ClientRectangle.Left) movDerechaBlue = true;
if (pictureBox2.Left + pictureBox2.Width >= this.ClientRectangle.Right)
movDerechaBlue = false;
if (pictureBox2.Top <= this.ClientRectangle.Top) movArribaBlue = false;
if (pictureBox2.Top + pictureBox2.Height >= this.ClientRectangle.Bottom)
movArribaBlue = true;
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
timer1.Interval = 300 - 3 * hScrollBar1.Value;
}
private void hScrollBar2_Scroll(object sender, ScrollEventArgs e)
{
timer2.Interval = 300 - 3 * hScrollBar1.Value;
}
}
}

pág. 88
pág. 89
Ejercicio 30:
Elaborar un programa, que permita copiar una imagen de un pictureBox a otro.

pág. 90
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 WindowsFormsApplication4
{
public partial class Ejercicio30 : Form
{
public Ejercicio30()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\imagen\\dk.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.AllowDrop = true;
pictureBox2.AllowDrop = true;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
PictureBox pbx = (PictureBox)sender;
origen = sender;
if (e.Button == MouseButtons.Left)
{
if (pbx.Image != null)
{
pbx.DoDragDrop(pbx.Image, DragDropEffects.Move);
}
}
}
private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
{
PictureBox pbx = (PictureBox)sender;
origen = sender;
if (e.Button == MouseButtons.Left)
{
if (pbx.Image != null) { pbx.DoDragDrop(pbx.Image,
DragDropEffects.Move);
}
}
}
private void pictureBox2_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
e.Effect = DragDropEffects.Move;
}
else e.Effect = DragDropEffects.None;
}
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{

pág. 91
e.Effect = DragDropEffects.Move;
}
else e.Effect = DragDropEffects.None;
}
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
PictureBox p = (PictureBox)sender;
PictureBox org = (PictureBox)origen;
if (p.Name != org.Name)
{
p.Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
org.Image = null;
}

}
private void pictureBox2_DragDrop(object sender, DragEventArgs e)
{
PictureBox p = (PictureBox)sender; PictureBox org = (PictureBox)origen;
if (p.Name != org.Name)
{
p.Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
org.Image = null;
}
}
}
}

pág. 92
Ejercicio 31.
Elaborar un programa, que permita mover una imagen de un pictureBox a otro. Utilizar
métodos.

pág. 93
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 WindowsFormsApplication4
{
public partial class Ejercicio31 : Form
{
object origen;
public Ejercicio31()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\imagenes\\kunka.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.AllowDrop = true;
pictureBox2.AllowDrop = true;
}
private void mover_imagen(object sender, MouseEventArgs e)
{
PictureBox pbx = (PictureBox)sender; origen = sender;
if (e.Button == MouseButtons.Left)
{
if (pbx.Image != null)
{
pbx.DoDragDrop(pbx.Image, DragDropEffects.Move);
}
}
}
private void enter_imagen(object sender, DragEventArgs e)
{ if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
e.Effect = DragDropEffects.Move;
}
else e.Effect = DragDropEffects.None;
}
private void image_DragDrop(object sender, DragEventArgs e)
{
PictureBox p = (PictureBox)sender;
PictureBox org = (PictureBox)origen;
if (p.Name != org.Name)
{
p.Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
org.Image = null;
}
}
}
}

pág. 94
Ejercicio 32.
Elaborar un juego de tres en raya, con arrastre de imágenes.

pág. 95
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 WindowsFormsApplication4
{
public partial class Ejercicio32 : Form
{
public Ejercicio32()
{
InitializeComponent();
}
object origen;
PictureBox[,] px = new PictureBox[3, 3];
private void Juego_TresenRaya_Load(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(Application.StartupPath +
"\\Imagenes\\img1.png");
pictureBox2.Image = Image.FromFile(Application.StartupPath +
"\\Imagenes\\img2.png");
pictureBox3.BorderStyle = BorderStyle.FixedSingle;
pictureBox4.BorderStyle = BorderStyle.FixedSingle;
pictureBox5.BorderStyle = BorderStyle.FixedSingle;
pictureBox6.BorderStyle = BorderStyle.FixedSingle;
pictureBox7.BorderStyle = BorderStyle.FixedSingle;

pág. 96
pictureBox8.BorderStyle = BorderStyle.FixedSingle;
pictureBox9.BorderStyle = BorderStyle.FixedSingle;
pictureBox10.BorderStyle = BorderStyle.FixedSingle;
pictureBox11.BorderStyle = BorderStyle.FixedSingle;

pictureBox1.AllowDrop = true;
pictureBox2.AllowDrop = true;
pictureBox3.AllowDrop = true;
pictureBox4.AllowDrop = true;
pictureBox5.AllowDrop = true;
pictureBox6.AllowDrop = true;
pictureBox7.AllowDrop = true;
pictureBox8.AllowDrop = true;
pictureBox9.AllowDrop = true;
pictureBox10.AllowDrop = true;
pictureBox11.AllowDrop = true;

px[0, 0] = pictureBox3;
px[0, 1] = pictureBox4;
px[0, 2] = pictureBox5;
px[1, 0] = pictureBox6;
px[1, 1] = pictureBox7;
px[1, 2] = pictureBox8;
px[2, 0] = pictureBox9;
px[2, 1] = pictureBox10;
px[2, 2] = pictureBox11;
button1.Enabled = false;
}
private void move_image(object sender, MouseEventArgs e)
{
PictureBox pbx = (PictureBox)sender;
origen = sender;
if (e.Button == MouseButtons.Left)
{
if (pbx.Image != null)
{
pbx.DoDragDrop(pbx.Image, DragDropEffects.Move);
}
}
}
private void enter_image(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Bitmap))
{
e.Effect = DragDropEffects.Move;
}
}
private void image_DragDrop(object sender, DragEventArgs e)
{
PictureBox p = (PictureBox)sender;
PictureBox org = (PictureBox)origen;
if (p.Name != org.Name)
{
p.Image = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
p.Enabled = false;
org.Enabled = false;
}
if (org.Name == "pictureBox1")
{
pictureBox2.Enabled = true;
}
if (org.Name == "pictureBox2")

pág. 97
{
pictureBox1.Enabled = true;
}
int cont = 0;
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
if (px[k, l].Image != null)
{
cont++;
}
if (px[k, 0].Image == pictureBox1.Image && px[k, 1].Image ==
pictureBox1.Image && px[k, 2].Image == pictureBox1.Image
|| px[0, l].Image == pictureBox1.Image && px[1, l].Image ==
pictureBox1.Image && px[2, l].Image == pictureBox1.Image
)
{
k = 2; l = 2;
MessageBox.Show("JUGADOR 1 ES EL GANADOR!");
pictureBox1.Enabled = false;
pictureBox2.Enabled = false;
button1.Enabled = true;
}
else if (px[k, 0].Image == pictureBox2.Image && px[k, 1].Image ==
pictureBox2.Image && px[k, 2].Image == pictureBox2.Image
|| px[0, l].Image == pictureBox2.Image && px[1, l].Image == pictureBox2.Image && px[2,
l].Image == pictureBox2.Image)
{
k = 2; l = 2;
MessageBox.Show("JUGADOR 2 ES EL GANAADOR!");
pictureBox1.Enabled = false;
pictureBox2.Enabled = false;
button1.Enabled = true;
}
else if (px[0, 0].Image == pictureBox1.Image && px[1, 1].Image ==
pictureBox1.Image && px[2, 2].Image == pictureBox1.Image
|| px[0, 2].Image == pictureBox1.Image && px[1, 1].Image ==
pictureBox1.Image && px[2, 0].Image == pictureBox1.Image
)
{
k = 2; l = 2;
MessageBox.Show("JUGADOR 1 ES EL GANADOR!");
pictureBox1.Enabled = false;
pictureBox2.Enabled = false;
button1.Enabled = true;
}
else if (px[0, 2].Image == pictureBox2.Image && px[1, 1].Image ==
pictureBox2.Image && px[2, 0].Image == pictureBox2.Image
|| px[0, 0].Image == pictureBox2.Image && px[1, 1].Image == pictureBox2.Image && px[2,
2].Image == pictureBox2.Image)
{
k = 2; l = 2;
MessageBox.Show("JUGADOR 2 ES EL GANADOR!");
pictureBox1.Enabled = false;
pictureBox2.Enabled = false;
button1.Enabled = true;
}
else
{
if (cont == 9)
{

pág. 98
MessageBox.Show("Empate!!! Reiniciar Juego para determinar
Ganador :)");
pictureBox1.Enabled = false;
pictureBox2.Enabled = false;
button1.Enabled = true;
}
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (pictureBox1.Enabled == false && pictureBox2.Enabled == false)
{
pictureBox1.Enabled = true;
pictureBox2.Enabled = true;
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
px[k, l].Image = null;
px[k, l].Enabled = true;
}
}
}
button1.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

pág. 99
Ejercicio 33:
Crear un formulario donde una figura siga al mouse, además que se muestre la posición del
mouse en el formulario.

pág. 100
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 WindowsFormsApplication4
{
public partial class Ejercicio33 : Form
{
public Ejercicio33()
{
InitializeComponent();
}
private void Ejercicio33_Load(object sender, EventArgs e)
{
panel1.Location = new Point(this.ClientRectangle.Width / 2,
this.ClientRectangle.Height / 2);
}
private void Ejercicio33_MouseMove(object sender, MouseEventArgs e)
{
label1.Text = "posicion ---> X:" + e.Location.X + ", Y:" + e.Location.Y;
panel1.Location = new Point(e.X, e.Y);
}
}
}

pág. 101
Ejercicio 34:
Elaborar un juego de un Laberinto, en donde se tenga que cruzar dando clic con el mouse. Si
se llega a cruzar el laberinto mostrar un mensaje y si se moviliza por una ruta sin salida
también mostrar un mensaje.

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 WindowsFormsApplication4
{
public partial class Ejercicio34 : Form
{
public Ejercicio34()
{
InitializeComponent();
}

List<Point> lista = new List<Point>();


private void Laberinto_Load(object sender, EventArgs e)
{

pág. 102
pictureBox1.Location = new Point(25, 35);
}
private void Ejercicio34_MouseClick(object sender, MouseEventArgs e)
{
int x = e.Location.X;
label1.Text = "posicion ---> X:" + e.Location.X + ", Y:" + e.Location.Y;
pictureBox1.Location = new Point(e.X, e.Y);
if (x >= 335)
{
MessageBox.Show("ganaste");
}
}
private void mensaje()
{
MessageBox.Show("sin salida");
}
private void panel4_MouseClick(object sender, MouseEventArgs e)
{
pictureBox1.Location = new Point(e.X, e.Y);
mensaje();
}
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
pictureBox1.Location = new Point(e.X, e.Y);
mensaje();
}
private void panel2_MouseClick(object sender, MouseEventArgs e)
{
pictureBox1.Location = new Point(e.X, e.Y);
mensaje();
}
private void panel3_MouseClick(object sender, MouseEventArgs e)
{
pictureBox1.Location = new Point(e.X, e.Y);
mensaje();
}
}
}

pág. 103
pág. 104
pág. 105
Ejercicio 35:
Realizar el ejercicio anterior, dibujando la ruta que se sigue para cruzar el laberinto. Validar
para que no cruce por los muros.

pág. 106
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 WindowsFormsApplication4
{
public partial class Ejercicio35 : Form
{
public Ejercicio35()
{
InitializeComponent();
}
List<Point> lista = new List<Point>();
private void Ejercicio34_Load(object sender, EventArgs e)
{
pictureBox1.Location = new Point(25, 35);
}
private void Laberinto_MouseClick(object sender, MouseEventArgs e)
{
int x = e.Location.X;
label1.Text = "posicion ---> X:" + e.Location.X + ", Y:" + e.Location.Y;
pictureBox1.Location = new Point(e.X, e.Y);

pág. 107
if (x >= 335)
{
MessageBox.Show("ganaste");
}
}
private void mensaje()
{
MessageBox.Show("sin salida");
}
private void panel4_MouseClick(object sender, MouseEventArgs e)
{
pictureBox1.Location = new Point(e.X, e.Y);
mensaje();
}
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
pictureBox1.Location = new Point(e.X, e.Y);
mensaje();
}
private void panel2_MouseClick(object sender, MouseEventArgs e)
{
pictureBox1.Location = new Point(e.X, e.Y);
mensaje();
}
private void panel3_MouseClick(object sender, MouseEventArgs e)
{
pictureBox1.Location = new Point(e.X, e.Y);
mensaje();
}
private void Laberinto_MouseDown(object sender, MouseEventArgs e)
{
Graphics G = this.CreateGraphics();
Pen lapiz = new Pen(Color.Coral, 3);
G.DrawRectangle(lapiz, new Rectangle(e.X, e.Y, 3, 3));
lista.Add(new Point(e.X, e.Y));
if (lista.Count > 1)
{
G.DrawLine(lapiz, lista[lista.Count - 1], lista[lista.Count - 2]);
}
}
}
}

pág. 108
Ejercicio 36:
Crear un formulario en donde una imagen se mueva con las teclas A, D, W, S (izquierda,
derecha, arriba, abajo,).

using System;

pág. 109
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 WindowsFormsApplication4
{
public partial class Ejercicio36 : Form
{
public Ejercicio36()
{
InitializeComponent();
}
private void ejercicio35_KeyPress(object sender, KeyPressEventArgs e)
{
char tecla = char.ToUpper(e.KeyChar);
if (tecla == (char)Keys.W)
{
//top sube
panel1.Top -= 2;
}
else if (tecla == (char)Keys.S)
{
panel1.Top += 2;
}
else if (tecla == (char)Keys.D)
{
//left va de izquierda o derecha
panel1.Left += 2;
}
else if (tecla == (char)Keys.I)
{
panel1.Left -= 2;
}
}
}
}

pág. 110
pág. 111
pág. 112
pág. 113
Ejercicio 37:
Realizar el ejercicio anterior, pero con los movimientos generados por las fechas del teclado
y establecer como límites los extremos del formulario.

using System;

pág. 114
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 WindowsFormsApplication4
{
public partial class Ejercicio37 : Form
{
public Ejercicio37()
{
InitializeComponent();
}
private void ejercicio35_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up && panel1.Top > 0)
{
panel1.Top -= 2;
}
else if (e.KeyCode == Keys.Down && panel1.Top <
this.ClientRectangle.Height)
{
panel1.Top += 2;
}
else if (e.KeyCode == Keys.Left && panel1.Left > 0)
{
panel1.Left -= 2;
}
}
else if (e.KeyCode == Keys.Right&&
panel1.Left<this.ClientRectangle.Width)
{
panel1.Left += 2;

Ejercicio 38:
Simular un juego de Pin pon, si el jugador supera los 30 segundos sin dejar caer la pelota
gana y si se deja caer la pelota pierde. Mostrar los mensajes correspondientes.

pág. 115
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 WindowsFormsApplication4
{
public partial class Ejercicio38 : Form
{
public int velocidad_left = 4;
public int velocidad_top = 4;
public int punto = 0;
public Ejercicio38()
{
InitializeComponent();
timer1.Enabled = true;
Cursor.Hide();
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.Bounds = Screen.PrimaryScreen.Bounds;
Raqueta.Top = Patio_de_Recreo.Bottom - (Patio_de_Recreo.Bottom / 10);
label3.Left = (Patio_de_Recreo.Width / 2) - (label3.Width / 2);

pág. 116
label3.Top = (Patio_de_Recreo.Height / 2) - (label3.Height / 2);
label3.Visible = false;
label5.Visible = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
Raqueta.Left = Cursor.Position.X - (Raqueta.Width / 2);
Pelota.Left += velocidad_left;
Pelota.Top += velocidad_top;
if (Pelota.Bottom >= Raqueta.Top && Pelota.Bottom <= Raqueta.Bottom &&
Pelota.Left >= Raqueta.Left && Pelota.Right <= Raqueta.Right)
{
velocidad_top += 2;
velocidad_left += 2;
velocidad_top = -velocidad_top;
punto += 1;
tem -= 1;
label2.Text = punto.ToString();
label6.Text = tem.ToString();
Random r = new Random();
Patio_de_Recreo.BackColor = Color.FromArgb(r.Next(150, 255),
r.Next(150, 255), r.Next(150, 255));
}
if (Pelota.Left <= Patio_de_Recreo.Left)
{
velocidad_left = -velocidad_left;
}
if (Pelota.Right >= Patio_de_Recreo.Right)
{
velocidad_left = -velocidad_left;
}
if (Pelota.Top <= Patio_de_Recreo.Top)
{
velocidad_top = -velocidad_top;
}
if (Pelota.Bottom >= Patio_de_Recreo.Bottom)
{
timer1.Enabled = false;
label3.Visible = true;
}
if (tem == 0 && Pelota.Bottom <= Patio_de_Recreo.Bottom)
{
timer1.Enabled = false;
label3.Visible = false;
label5.Visible = true;
timer2.Enabled = false;
MessageBox.Show("ganaste con: " + label2.Text + " Puntos");
}
}
private void Pin_Pon_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape) { this.Close(); }
if (e.KeyCode == Keys.F1)
{
Pelota.Left = 50;
Pelota.Top = 50;
velocidad_left = 4;
velocidad_top = 4;
punto = 0;
tem = 31;
label2.Text = "0";
timer1.Enabled = true;

pág. 117
label3.Visible = false;
label5.Visible = false;
label6.Text = tem + " Segundo(s)";
Patio_de_Recreo.BackColor = Color.White;
timer2.Start();
}
}
int tem;
private void timer2_Tick(object sender, EventArgs e)
{
if (tem > 0)
{
tem--;
label6.Text = tem + " Segundo(s)";
}
else
{
timer2.Stop();
timer1.Stop();
MessageBox.Show("ganaste con: " + label2.Text + " Puntos");
}
}
private void Pin_Pon_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
punto = 0;
tem = 31;
timer2.Start();
}
}
}

pág. 118
pág. 119
Ejercicio 39: (Practica Calificada)
Elaborar un programa que simule un juego de dados entre 2 jugadores. Se ingresarán sus
nombres y se cargarán sus imágenes desde la ventana del explorador. Al iniciar juego se
activarán los controles inferiores del juego y se desactivarán los controles de registro. Inicia
el jugador 1, cada jugador tendrá 4 turnos y tirará el dado 1 veces en c/turno, registrándose
los intentos y los puntajes en las listas respectivas. Los turnos se manejan de manera
automática y de manera intercalada. Al finalizar el juego se calcularán los puntajes totales y
aparecerá un mensaje que indique el nombre del ganador, además se preguntará si se
desea seguir jugando, si vuelve a jugar se limpian las cajas y listas, se activan las opciones de
registro y se desactivan los controles de juego.

pág. 120
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 WindowsFormsApplication4
{
public partial class Ejercicio39 : Form
{

public Ejercicio39()
{
InitializeComponent();
}

String jugador1, jugador2;


int f = 0;
int d = 1;
int l = 1;
int suma1 = 0, suma2 = 0;
string ganador;

pág. 121
private void label6_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Equals("") && !textBox2.Text.Equals(""))
{
label6.Text = "SCORE:" + textBox1.Text;
label5.Text = "SCORE:" + textBox2.Text;
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog busimagen = new OpenFileDialog();
busimagen.Filter = "archivos de imagen|*.jpg";
busimagen.InitialDirectory = "//";
if (busimagen.ShowDialog() == DialogResult.OK)
{
string dir = busimagen.FileName;
pictureBox1.ImageLocation = dir;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void Iniciar_Juego_Click(object sender, EventArgs e)
{
jugador1 = "SCORE:" + " " + Convert.ToString(textBox1.Text);
jugador2 = "SCORE:" + " " + Convert.ToString(textBox2.Text);
label6.Text = jugador1;
label6.ForeColor = Color.Blue;
label5.Text = jugador2;
label5.ForeColor = Color.Red;
}

private void button3_Click(object sender, EventArgs e)


{
OpenFileDialog busimagen = new OpenFileDialog();
busimagen.Filter = "archivos de imagen|*.jpg";
busimagen.InitialDirectory = "//";
if (busimagen.ShowDialog() == DialogResult.OK)
{ string dir = busimagen.FileName;
pictureBox2.ImageLocation = dir;
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void button4_Click(object sender, EventArgs e)
{
Random a = new Random();
int n1; n1 = a.Next(1, 7);
if (f <= 2)
{
textBox3.Text = textBox1.Text;
listBox2.Items.Add(n1);
label6.Text = jugador1;
listBox1.Items.Add(l);
l++;
suma1 = suma1 + n1;
textBox4.Text = Convert.ToString(suma1);
}
else if (f <= 5)
{
textBox3.Text = textBox2.Text;
listBox4.Items.Add(n1);
label5.Text = jugador2;
listBox3.Items.Add(d);
d++;

pág. 122
suma2 = suma2 + n1;
textBox5.Text = Convert.ToString(suma2);
}
else if (f <= 8)
{
textBox3.Text = textBox1.Text;
listBox2.Items.Add(n1);
label6.Text = jugador1;
listBox1.Items.Add(l);
l++;
suma1 = suma1 + n1;
textBox4.Text = Convert.ToString(suma1);
}
else if (f <= 11)
{
textBox3.Text = textBox2.Text;
listBox4.Items.Add(n1);
label5.Text = jugador2;
listBox3.Items.Add(d);
d++;
suma2 = suma2 + n1;
textBox5.Text = Convert.ToString(suma2);
}
else
{
if (suma1 > suma2) ganador = textBox1.Text;
else
ganador = textBox2.Text;
DialogResult opcion;
opcion = MessageBox.Show("el ganador es " + ganador + ". Desea
continuar el juego", "fin del juego", MessageBoxButtons.YesNoCancel);
if (opcion == DialogResult.Yes)
{
textBox1.Clear();
textBox2.Clear();
label5.Text = " ";
textBox5.Text = " ";
textBox4.Text = " ";
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
listBox4.Items.Clear();
pictureBox1.Image = null;
pictureBox2.Image = null;
textBox1.Focus();
}
else if (opcion == DialogResult.No) this.Close();
else MessageBox.Show("juego cancelado");
}
f++;
}
}
}

pág. 123
pág. 124

También podría gustarte