Está en la página 1de 15

Manual de prctlcas en C#

Slo cdlgo
Autor: L.l. !ose 8aymundo Ce[a vzquez
L.l.A. Cesar Lsplnoza !lmenez
IN1kCDUCCICN
8lenvenldo al mundo de la programacln, el presente manual de
prctlcas contlene algunos e[emplos en C#, de los cuales algunos de ellos
muestran algunos dlsenos lnteresantes y un poco luera de lo comun.
Cabe resaltar que el manual contlene slo el cdlgo utlllzado en
los dllerentes e[emplos y la vlsta llnal de los lormularlos, es necesarlo
que cada uno de los controles, lncluyendo los lormularlos se renombren
conlorme el nombre utlllzado en el cdlgo para que lunclonen
correctamente (espero no haya problema con ello). Cran parte del
cdlgo vlene comentado para expllcar las llneas agregadas al mlsmo.
La ldea central del manual es mostrar de manera rplda y sencllla
el uso de algunos controles y sus propledades, el mane[o de los
dllerentes cdlgos en otros e[emplos pueden darte como resultado
cosas lnteresantes, slo se creatlvo y utlllza tu lmaglnacln. 8ecuerda
que, s| se puede |mag|nar, se puede programar, ok! Lspero que el
manual sea de tu agrado.
INDICL
8AC1lCA nC. 1 - Controles y cuadro de dlalogo ...........................................................................1
8AC1lCA nC. 2 - Mane[o de lormularlos ......................................................................................2
8AC1lCA nC. 3 - Agenda ...............................................................................................................3
8AC1lCA nC. 4 - Cperaclones bslcas con dos numeros ..............................................................4
8AC1lCA nC. 3 -Controles de ulalogo ..........................................................................................6
8AC1lCA nC. 6 - lnsertar Calendarlo y lecha ...............................................................................7
8AC1lCA nC. 7 - uar lormas a los lormularlos..............................................................................8
8AC1lCA nC. 8 - Mostrar documentos de Word ..........................................................................9
8AC1lCA nC. 9 - Cargar documentos de Clllce ..........................................................................10
8AC1lCA nC. 10 - Mostrar Sltlos Web........................................................................................11
8AC1lCA nC. 11 - Cenerar numeros aleatorlos ..........................................................................12
u1lM | !ose 8aymundo Ce[a vzquez 1
PRACTICA NO. 1 Controles y cuadro de dialogo
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using 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";
}
}
}
u1lM | !ose 8aymundo Ce[a vzquez 2
PRACTICA NO. 2 Manejo de formularios
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using 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();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using 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();
}
}
}
u1lM | !ose 8aymundo Ce[a vzquez 3
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Agenda
{
PRACTICA NO. 3 - 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();
}
}
}
}
}
u1lM | !ose 8aymundo Ce[a vzquez 4
PRACTICA NO. 4 Operaciones bsicas con dos nmeros
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using 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;
u1lM | !ose 8aymundo Ce[a vzquez 3
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());
}
if (opc == "*")
{
res.ToString());
}
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());
}
/*txtNum1.Text = "";
txtNum2.Text = "";
txtNum1.Focus();
cmbOperacion.Text = "";*/
}
catch (DivideByZeroException)
{
Error");
MessageBox.Show("Error la divisin no es divisible entre 0", "Mensaje de
txtNum1.Text = "";
txtNum2.Text = "";
txtNum1.Focus();
cmbOperacion.Text = "";
}
catch (FormatException)
{
Error");
}
}
MessageBox.Show("Error Escriba los datos correctamente", "Mensaje de
txtNum1.Text = "";
txtNum2.Text = "";
txtNum1.Focus();
}
}
u1lM | !ose 8aymundo Ce[a vzquez 6
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Practica07
{
PRACTICA NO. 5 Controles de Dialogo
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:\\";
/// Evala 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);
}
}
}
}
u1lM | !ose 8aymundo Ce[a vzquez 7
PRACTICA NO. 6 Insertar Calendario y
Fecha
using
using
using
using
using
using
using
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();
}
}
}
PRACTICA NO. 7 Dar formas a los
formularios
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
u1lM | !ose 8aymundo Ce[a vzquez 8
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();
}
}
}
PRACTICA NO. 8 Mostrar documentos de
Word
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
u1lM | !ose 8aymundo Ce[a vzquez 9
using System.Windows.Forms;
using 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);
}
}
}
}
u1lM | !ose 8aymundo Ce[a vzquez 10
PRACTICA NO. 9 Cargar documentos de
Office
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
using 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)
{
null);
oDoc = e.GetType().InvokeMember("Document", BindingFlags.GetProperty, null, e,
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;
}
}
}
PRACTICA NO. 10 Mostrar Sitios
Web
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
u1lM | !ose 8aymundo Ce[a vzquez 11
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 haciaAtrsToolStripMenuItem_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
u1lM | !ose 8aymundo Ce[a vzquez 12
PRACTICA NO. 11 Generar nmeros 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();
//Mtodo ejecutado al presionar el botn
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";
}
}
}
}

También podría gustarte