Manual de prácticas en C - Mtro. Cesar Espinoza Jiménez

Anuncio
Manual de prácticas en C#
Sólo código
Autor: L.I. José Raymundo Ceja Vázquez
L.I.A. Cesar Espinoza Jiménez
INTRODUCCIÓN
Bienvenido al mundo de la programación, el presente manual de
prácticas contiene algunos ejemplos en C#; de los cuales algunos de ellos
muestran algunos diseños interesantes y un poco fuera de lo común.
Cabe resaltar que el manual contiene sólo el código utilizado en
los diferentes ejemplos y la vista final de los formularios; es necesario
que cada uno de los controles, incluyendo los formularios se renombren
conforme el nombre utilizado en el código para que funcionen
correctamente (espero no haya problema con ello). Gran parte del
código viene comentado para explicar las líneas agregadas al mismo.
La idea central del manual es mostrar de manera rápida y sencilla
el uso de algunos controles y sus propiedades; el manejo de los
diferentes códigos en otros ejemplos pueden darte como resultado
cosas interesantes, sólo se creativo y utiliza tu imaginación. Recuerda
que, si se puede imaginar, se puede programar, ok! Espero que el
manual sea de tu agrado.
INDICE
PRACTICA NO. 1 – Controles y cuadro de dialogo ...........................................................................1
PRACTICA NO. 2 – Manejo de formularios ......................................................................................2
PRACTICA NO. 3 - Agenda ...............................................................................................................3
PRACTICA NO. 4 – Operaciones básicas con dos números ..............................................................4
PRACTICA NO. 5 –Controles de Dialogo ..........................................................................................6
PRACTICA NO. 6 – Insertar Calendario y Fecha ...............................................................................7
PRACTICA NO. 7 – Dar formas a los formularios..............................................................................8
PRACTICA NO. 8 – Mostrar documentos de Word ..........................................................................9
PRACTICA NO. 9 – Cargar documentos de Office ..........................................................................10
PRACTICA NO. 10 – Mostrar Sitios Web ........................................................................................11
PRACTICA NO. 11 – Generar números aleatorios ..........................................................................12
PRACTICA NO. 1 –
using
using
using
using
using
using
using
Controles y cuadro de dialogo
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
namespace Primer_aplicacion
{
public partial class frmHola : Form
{
public frmHola()
{
InitializeComponent();
}
private void btnMostrar_Click(object sender, EventArgs e)
{
//Doble diagonal, nos permite realizar comentarios de una linea
/*
*
*
*
}
}
}
Diagonal + asterisco,
nos permite realizar
comentarios de varias
lineas*/
MessageBox.Show("Bienvenidos a C# \n\nEspero sea de su agrado");
lblLetrero.Text = "Bienvenidos a C#, Espero sea de su agrado";
txtLetrero.Text = "Bienvenidos a C#, Espero sea de su agrado";
UTIM | José Raymundo Ceja Vázquez
1
PRACTICA NO. 2 –
using
using
using
using
using
using
using
using
Manejo de formularios
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace Manejo_de_formularios
{
public partial class frmFormulario1 : Form
{
public frmFormulario1()
{
InitializeComponent();
}
private void btnNext_Click(object sender, EventArgs e)
{
new frmFormulario2().ShowDialog();
}
}
}
using
using
using
using
using
using
using
using
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace Manejo_de_formularios
{
public partial class frmFormulario2 : Form
{
public frmFormulario2()
{
InitializeComponent();
}
}
}
private void btnPrevius_Click(object sender, EventArgs e)
{
this.Close();
}
UTIM | José Raymundo Ceja Vázquez
2
PRACTICA NO. 3 - Agenda
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace Agenda
{
public partial class frmAgenda: Form
{
String Nombre, Apellido;
public frmAgenda()
{
InitializeComponent();
}
private void btnMostrar_Click(object sender, EventArgs e)
{
Nombre = txtNombre.Text;
Apellido = txtApellido.Text;
}
MessageBox.Show("Bienvenido " + txtNombre.Text);
//MessageBox.Show("Bienvenido " + txtNombre.Text + " " + txtApellido.Text +
"\n\nTu edad es: " + txtEdad.Text);
MessageBox.Show("Bienvenido " + Nombre + " " + Apellido);
private void btnLimpiar_Click(object sender, EventArgs e)
{
txtNombre.Text = " ";
txtApellido.Text = " ";
txtNombre.Focus();
}
private void btnClear_Click(object sender, EventArgs e)
{
//Limpiar de manera rapida
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
c.Text = "";
//Colocar el cursor en el primer TextBox
this.txtNombre.Focus();
}
}
}
}
}
UTIM | José Raymundo Ceja Vázquez
3
PRACTICA NO. 4 –
using
using
using
using
using
using
using
using
Operaciones básicas con dos números
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace Calculadora
{
public partial class frmCalculadora : Form
{
int num1, num2, resp;
string opc;
double res;
public frmCalculadora()
{
InitializeComponent();
}
private void btnResultado_Click(object sender, EventArgs e)
{
num1 = Convert.ToInt32(txtNum1.Text);
num2 = Convert.ToInt32(txtNum2.Text);
/*num1 = int.Parse(txtNum1.Text);
num2 = int.Parse(txtNum2.Text);
num1 = Convert.ToDouble(txtNum1.Text);
num2 = Convert.ToDouble(txtNum2.Text);*/
resp = num1 + num2;
}
//txtResultado.Text = Convert.ToString(resp);
MessageBox.Show("El resultado es: " + resp);
private void btnSalir_Click(object sender, EventArgs e)
{
//this.Visible = false;
this.Close();
}
private void btnTotal_Click(object sender, EventArgs e)
{
try
{
num1 = Convert.ToInt32(txtNum1.Text);
num2 = Convert.ToInt32(txtNum2.Text);
opc = cmbOperacion.SelectedItem.ToString();
if (opc == "+")
{
res = num1 + num2;
UTIM | José Raymundo Ceja Vázquez
4
}
MessageBox.Show("La suma de la Cantidad es " + res.ToString());
if (opc == "-")
{
res = num1 - num2;
MessageBox.Show("La Resta de la Cantidad es " + res.ToString());
}
res.ToString());
if (opc == "*")
{
res = num1 * num2;
MessageBox.Show("La Multiplicacion de las Cantidades es " +
}
if (opc == "/")
{
res = num1 / num2;
MessageBox.Show("La Division de las Cantidades es " + res.ToString());
}
}
catch (DivideByZeroException)
{
MessageBox.Show("Error la división no es divisible entre 0", "Mensaje de
Error");
}
}
txtNum1.Text = "";
txtNum2.Text = "";
txtNum1.Focus();
cmbOperacion.Text = "";
catch (FormatException)
{
MessageBox.Show("Error Escriba los datos correctamente", "Mensaje de
Error");
}
/*txtNum1.Text = "";
txtNum2.Text = "";
txtNum1.Focus();
cmbOperacion.Text = "";*/
}
}
txtNum1.Text = "";
txtNum2.Text = "";
txtNum1.Focus();
UTIM | José Raymundo Ceja Vázquez
5
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.IO;
PRACTICA NO. 5 – Controles de Dialogo
namespace Practica07
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnColor_Click(object sender, EventArgs e)
{
ColorDialog MyDialog = new ColorDialog();
// Keeps the user from selecting a custom color.
MyDialog.AllowFullOpen = false;
// Allows the user to get help. (The default is false.)
MyDialog.ShowHelp = true;
// Sets the initial color select to the current text color.
MyDialog.Color = txtColor.ForeColor;
// Update the text box color if the user clicks OK
if (MyDialog.ShowDialog() == DialogResult.OK)
txtColor.ForeColor = MyDialog.Color;
}
private void btnFont_Click(object sender, EventArgs e)
{
fontDialog1.ShowColor = true;
fontDialog1.Font = txtColor.Font;
fontDialog1.Color = txtColor.ForeColor;
if (fontDialog1.ShowDialog() != DialogResult.Cancel)
{
txtColor.Font = fontDialog1.Font;
txtColor.ForeColor = fontDialog1.Color;
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
string foto;
//Definimos los filtros de archivos a permitir, en este caso imagenes
openFileDialog1.Filter = "Bitmap files (*.bmp)|*.bmp|Gif files (*.gif)|*.gif|JGP files
(*.jpg)|*.jpg|All (*.*)|*.* |PNG (*.paisaje)|*.png ";
//Establece que filtro se mostrará por defecto en este caso, 3=jpg
openFileDialog1.FilterIndex = 3;
//Esto aparece en el Nombre del archivo a seleccionar, se puede quitar no es fundamental
openFileDialog1.FileName="Seleccione una imagen";
//El titulo de la Ventana....
openFileDialog1.Title = "Paisaje";
//El directorio que por defecto abrirá, para cada contrapleca del Path colocar \\
C:\\Fotitos\\Wizard y así sucesivamente
openFileDialog1.InitialDirectory = "c:\\";
/// Evalúa que si al aparecer el cuadro de dialogo la persona presionó Ok
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
/// Si esto se cumple, capturamos la propiedad File Name y la guardamos en la variable foto
foto = openFileDialog1.FileName;
//Por ultimo se la asignamos al PictureBox
pctImagen.Image = Image.FromFile(@foto);
}
}
}
}
UTIM | José Raymundo Ceja Vázquez
6
using
using
using
using
using
using
using
PRACTICA NO. 6 –
Fecha
Insertar Calendario y
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
namespace Fecha_hora
{
public partial class frmFechahora : Form
{
public frmFechahora()
{
InitializeComponent();
}
private void frmFechahora_Load(object sender, EventArgs e)
{
/*this.dtpHora.Format = DateTimePickerFormat.Time;
this.dtpHora.Width = 100;
this.dtpHora.ShowUpDown = true;*/
}
private void mcrCalendario_DateChanged_1(object sender, DateRangeEventArgs e)
{
this.lblFecha.Text =
this.mcrCalendario.SelectionRange.Start.ToShortDateString();
}
private void btnHora_Click_1(object sender, EventArgs e)
{
this.dtpHora.Value = DateTime.Now;
}
}
}
private void btnSalir_Click_1(object sender, EventArgs e)
{
this.Close();
}
UTIM | José Raymundo Ceja Vázquez
7
using
using
using
using
using
using
using
PRACTICA NO. 7 –
formularios
Dar formas a los
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
namespace Formas
{
public partial class frmDrawing : Form
{
public frmDrawing()
{
InitializeComponent();
Graphics dc = this.CreateGraphics();
this.Show();
Pen BluePen = new Pen(Color.Blue, 3);
dc.DrawRectangle(BluePen, 100, 300, 300, 50);
Pen RedPen = new Pen(Color.Red, 5);
dc.DrawEllipse(RedPen, 220, 200, 60, 60);
dc.DrawEllipse(RedPen, 150, 100, 60, 60);
dc.DrawEllipse(RedPen, 300, 100, 60, 60);
}
private void frmDrawing_Load(object sender, EventArgs e)
{
System.Drawing.Drawing2D.GraphicsPath objDraw = new
System.Drawing.Drawing2D.GraphicsPath();
objDraw.AddEllipse(0, 0, this.Width, this.Height);
this.Region = new Region(objDraw);
}
}
}
/*System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics = this.CreateGraphics();
formGraphics.DrawEllipse(myPen, new Rectangle(0, 0, 200, 300));
myPen.Dispose();
formGraphics.Dispose();*/
private void btnSalir_Click(object sender, EventArgs e)
{
this.Close();
}
UTIM | José Raymundo Ceja Vázquez
8
using
using
using
using
using
using
using
using
PRACTICA NO. 8 –
Word
Mostrar documentos de
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
Microsoft.Office.Interop.Word;
namespace Office
{
public partial class frmOffice : Form
{
public frmOffice()
{
InitializeComponent();
}
private void btnWord_Click_1(object sender, EventArgs e)
{
object missing = System.Reflection.Missing.Value;
object Visible = true;
object start1 = 0;
object end1 = 0;
ApplicationClass WordApp = new ApplicationClass();
Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Range rng = adoc.Range(ref start1, ref missing);
try
{
rng.Font.Name = "Georgia";
rng.InsertAfter("Bienvenido!");
object filename = @"D:\MyWord.doc";
adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref
missing, ref missing);
WordApp.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnAbrir_Click_1(object sender, EventArgs e)
{
string foto;
openFileDialog1.Filter = "Documentos de Word (*.doc)|*.doc|Documentos de Excel
(*.xls)|*.xls|Documentos de PowerPoint (*.pnt)|*.pnt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.FileName = "Seleccione un archivo";
openFileDialog1.Title = "Archivo";
openFileDialog1.InitialDirectory = "C:\\Documents and Settings\\José Raymundo Ceja\\My
Documents";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foto = openFileDialog1.FileName;
//pnlContenedor.Container = Container.Add(@foto);
}
}
}
}
UTIM | José Raymundo Ceja Vázquez
9
using
using
using
using
using
using
using
using
PRACTICA NO. 9 –
Office
Cargar documentos de
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
System.Reflection;
namespace OfficeWindows
{
public partial class Form1 : Form
{
public Object oDoc;
public string FileName;
public Form1()
{
InitializeComponent();
this.webBrowser1.DocumentCompleted += new
WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted_1);
}
private void abrirDocumentoDeOfficeToolStripMenuItem_Click_1(object sender,
EventArgs e)
{
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
FileName = openFileDialog1.FileName;
}
if (FileName.Length != 0)
{
Object refmissing = System.Reflection.Missing.Value;
oDoc = null;
webBrowser1.Navigate(FileName);
}
private void webBrowser1_DocumentCompleted_1(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
oDoc = e.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, e,
null);
Object oApplication = e.GetType().InvokeMember("Application",
BindingFlags.GetProperty, null, oDoc, null);
}
private void Form1_Load_1(object sender, EventArgs e)
{
openFileDialog1.Filter = "Documentos de Office (*.docx, *.xlsx,
*.pptx)|*.docx;*.xlsx;*.pptx";
openFileDialog1.FilterIndex = 1;
}
}
}
UTIM | José Raymundo Ceja Vázquez
10
using
using
using
using
using
using
using
PRACTICA NO. 10 –
Web
Mostrar Sitios
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
namespace Explorador_Web
{
public partial class frmNavegador : Form
{
public frmNavegador()
{
InitializeComponent();
}
private void btnIr_Click(object sender, EventArgs e)
{
wbrContenedor.Navigate(new Uri(cmbUrl.SelectedItem.ToString()));
}
private void inicioToolStripMenuItem_Click(object sender, EventArgs e)
{
wbrContenedor.GoHome();
}
private void haciaAtrásToolStripMenuItem_Click(object sender, EventArgs e)
{
wbrContenedor.GoForward();
}
private void haciaDelanteToolStripMenuItem_Click(object sender, EventArgs e)
{
wbrContenedor.GoBack();
}
}
}
private void frmNavegador_Load(object sender, EventArgs e)
{
cmbUrl.SelectedIndex = 0;
wbrContenedor.GoHome();
}
Enlaces para prueba:
http://www.microsoft.com.mx
http://www.frasesweb.com
http://mx.encarta.msn.com
http://www.pumasunam.com.mx
http://www.ciencia.net
http://www.elrollo.com.mx
http://www.atlixco.com
http://www.enciclomedia.edu.mx
http://www.pipoclub.com
http://www.mundodisney.net
http://www.ricolino.com
http://www.bimbo.com.mx
UTIM | José Raymundo Ceja Vázquez
11
PRACTICA NO. 11 –
Generar números aleatorios
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//using System.
namespace Numeros_aleatorios
{
public partial class frmAleatorios : Form
{
public frmAleatorios()
{
InitializeComponent();
}
private Random obj = new Random();
}
}
//Método ejecutado al presionar el botón
private void btnGenerar_Click(object sender, EventArgs e)
{
lblContenedor.Text = " ";
for(int i = 0; i < 4 ; i++)
{
//for(int j = 0; j < 4 ; j++)
lblContenedor.Text += obj.Next(1, 10) + "
|
//lblContenedor.Text += "\n\n";
}
}
";
UTIM | José Raymundo Ceja Vázquez
12
Descargar