Practica en Visual Basic.pdf

Embed Size (px)

Citation preview

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #1 En la siguiente prctica realizaremos un ejercicio sencillo, en cual analizares, la funcin de un Option

    Button, con sus diferentes cdigos, utilizando cdigos de color y alineacin:

    Para comenzar deben crear un formulario como el que continuacin se les muestra.

    Utilizaremos los siguientes OBJETOS:

    1 Textbox

    2 Frame

    6 Option Button

    Ya colocados en nuestro formulario les daremos las siguientes propiedades:

    OBJETO NAME CAPTION Frame 1 fraColores Colores

    Option 1 optAzul Azul

    Option 2 optRojo Rojo

    Option 3 optVerde Verde

    Option 4 optAmarillo Amarillo

    Frame 2 fraPosicion Posicin

    Option 4 optArriba Arriba

    Option 4 optAbajo Abajo

    Text 1 txtCaja Caja

    Formulario frmColores Colores

    Ahora colocaremos el siguiente cdigo:

    Damos dos clic en el formulario aparecer el

    nombre del botn o comando seleccionado:

    Private Sub Form_Load()

    End Sub

    Dentro de la misma opcin colocamos la

    siguiente lnea de cdigo:

    Private Sub Form_Load()

    txtCaja.Top = 0

    End Sub

    Y dado clic en el respectivo botn colocamos

    su cdigo:

    Option Explicit

    Private Sub Form_Load()

    txtCaja.Top = 0

    End Sub

    Private Sub optArriba_Click()

    txtCaja.Top = 0

    End Sub

    Private Sub optAbajo_Click()

    txtCaja.Top = Form1.ScaleHeight -

    txtCaja.Height

    End Sub

    Private Sub optAzul_Click()

    txtCaja.BackColor = vbBlue

    End Sub

    Private Sub optRojo_Click()

    txtCaja.BackColor = vbRed

    End Sub

    Private Sub optVerde_Click()

    txtCaja.BackColor = vbGreen

    End Sub

    Private Sub optAmarillo_Click()

    txtCaja.BackColor = vbYellow

    End Sub

    Despus procedemos a guardar:

    1. Nos vamos al Men Archivo >> Guardar

    formulario/Aceptar y Guardar proyecto/Aceptar

    NOTA: Es necesario guardar el formulario y el

    proyecto al mismo tiempo que guarda uno, ya

    que si no lo haces, y despus quieres abrir tu

    archivo no se reproducir.

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #2 Realizar una calculadora elemental que permite hacer las cuatro opciones aritmticas bsicas, los ficheros de este

    proyecto se pueden llamar Minicalculadora.vbp el usuario introduce los datos y clica sobre el botn

    correspondiente a la operacin que desea realizar, apareciendo inmediatamente el resultado en la caja de texto de

    la derecha.

    Este ser el formulario que realizaremos:

    A continuacin se darn los siguientes valores para los OBJETOS que introduciremos en el formulario:

    OBJETO NAME CAPTION o TEXT

    Formulario frmMinacalc Minicalculadora

    Text1 txtOper1

    Label 1 lblOp

    Text2 txtOper2

    Label 2 lblEqual =

    Text3 txtResult

    Comand 1 cmdSuma +

    Comand 2 cmdResta -

    Comand 3 cmdProd *

    Comand 4 cmdDiv /

    Ahora proceda a ingresa el cdigo de los botones:

    Private Sub cmdDiv_Click()

    txtResult.Text = Val(txtOper1.Text) / Val(txtOper2.Text)

    lblOp.Caption = "/"

    End Sub

    Private Sub cmdProd_Click()

    txtResult.Text = Val(txtOper1.Text) * Val(txtOper2.Text)

    lblOp.Caption = "*"

    End Sub

    Private Sub cmdResta_Click()

    txtResult.Text = Val(txtOper1.Text) - Val(txtOper2.Text)

    lblOp.Caption = "-"

    End Sub

    Private Sub cmdSuma_Click()

    txtResult.Text = Val(txtOper1.Text) + Val(txtOper2.Text)

    lblOp.Caption = "+"

    End Sub

    Ahora procedemos a guardar nuestra prctica:

    En esta prctica se ha utilizado repetidamente la funcin Val() de Visual Basic. Esta funcin convierte una serie

    de caracteres (un texto formado por cifras). Sin llamada a la funcin Val() el operador + aplicado a cadenas de

    caracteres las concatena, y como resultado por ejemplo, 3+4 dara 34. No es lo mismo los caracteres 1 y 2 formando la cadena o String 12 que el numero 12; la funcin Val() convierte cadenas de caracteres numricos con los que se pueden realizar operaciones aritmticas en los nmeros correspondientes con los que

    opera matemticamente Visual Basic 6.0 transforma de modo automtico nmeros en cadenas de caracteres y

    viceversa.

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #3 Realizar programas sencillos que permite ver que la equivalencia entre las escalas de temperaturas en grados

    Centgrados y Fahrenheit. Los ficheros de este proyecto se pueden llamar Temperat.vbp y desplazarse con

    incrementos pequeos de 1C y grandes de 10C. Como es habitual, tambin puede cambiarse el valor arrastrando

    el con el ratn del cursor de la barra. Los valores mximos y mnimos de la barra son 100C y -100C.A ambos

    lados de la barra aparecen dos cuadros de texto (color de fondo blanco) donde aparecen los grados

    correspondientes a la barra en ambas escalas. Encima aparecen dos rtulos (labels) que indican la escala de

    temperaturas correspondientes. Completan la aplicacin un botn salir que termina la ejecucin y el men File con

    la nica opcin Exit que termina as mismo la ejecucin del programa.

    Estos son los valores de los OBJETOS:

    CONTROL NAME CAPTION o TEXT

    Formulario frmConversor Conversor de temperaturas

    Label 1 lblCent Centgrados

    Text 1 txtCent

    Comand 1 cmdSalir Salir

    Label 2 lblFahr Fahrenheit

    Text 2 txtFahr

    CONTROL NAME MIN MAX SMALL CHANGE LARGE CHANGE VALUE

    VScroll 1 vsbTemp 100 -100 1 10 0

    Este ser el formulario que realizaremos:

    El cdigo correspondiente a esta prctica es el siguiente:

    Private Sub cmbSalir_Click ( )

    Beep

    End

    End Sub

    Private Sub vsbTemp_Change ( )

    txtCent.Text = vsbTemp.Value

    txtFahr.Text = 32 + 1.8 * vsbTemp.Value

    End Sub

    Sobre esta prctica se puede comentar lo siguiente:

    1. Se ha utilizado la propiedad Valu de la barra de desplazamiento, la cual da el valor actual de la misma con

    respecto a los lmites inferior y superior, previamente establecidos. (100 y 100).

    2. Mediante el procedimiento cmbSalir_Click ( ); se cierra el programa gracias a la instruccin End. El cometido

    del Beep no es otro que el de emitir un pitido atreves del altavoz del ordenador, que indicara que en efecto se ha

    salido del programa.

    3. Finalmente la funcin vsbTemp_Change ( ) se activa al cambiar el valor de la barra de desplazamiento; su

    efecto es modificar el valor de la propiedad Text en las cajas de texto muestran la temperatura en cada una de las

    dos escalas.

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #4 En esta prctica se repiten procedimientos parecidos a los se vio en la primera prctica, en diferentes aplicaciones:

    Estos son los valores de los OBJETO:

    Estos son los valores de los HScroll:

    A continuacin se muestra el cdigo de la prctica:

    Este es el formulario que realizaremos:

    Public Brojo, Bverde, Bazul As Integer

    Public Frojo, Fverde, Fazul As Integer

    Private Sub cmdSalir_Click()

    End

    End Sub

    Private Sub Form_Load()

    Brojo = 0

    Bverde = 0

    Bazul = 0

    Frojo = 255

    Fverde = 255

    Fazul = 255

    lblCuadro.BackColor = RGB(Brojo, Bverde, Bazul)

    lblCuadro.ForeColor = RGB(Frojo, Fverde, Fazul)

    End Sub

    Private Sub hsbColor_Change(Index As Integer)

    If optColor(0).Value = True Then

    lblCuadro.BackColor = RGB(hsbColor(0).Value, hsbColor(1).Value, hsbColor(2).Value)

    Dim i As Integer

    For i = 0 To 2

    txtColor(i).Text = hsbColor(i).Value

    Next i

    Else

    lblCuadro.ForeColor = RGB(hsbColor(0).Value, hsbColor(1).Value, hsbColor(2).Value)

    For i = 0 To 2

    txtColor(i).Text = hsbColor(i).Value

    Next i

    End If

    End Sub

    Private Sub optColor_Click(Index As Integer)

    If Index = 0 Then

    Frojo = hsbColor(0).Value

    Fverde = hsbColor(1).Value

    Fazul = hsbColor(2).Value

    hsbColor(0).Value = Brojo

    hsbColor(1).Value = Bverde

    hsbColor(2).Value = Bazul

    Else

    Brojo = hsbColor(0).Value

    Bverde = hsbColor(1).Value

    Bazul = hsbColor(2).Value

    hsbColor(0).Value = Frojo

    hsbColor(1).Value = Fverde

    hsbColor(2).Value = Fazul

    End If

    End Sub

    OBJETO NAME CAPTION o TEXT

    Formulario frmColores Colores

    Frame 1 fraOpcin

    Comand 1 cmdSalir Salir

    Label 1 lblRojo Rojo

    Label 1 lblVerde Verde

    Label 1 lblAzul Azul

    Text 1 txtColor 0

    Text 2 txtColor 0

    Text 1 txtColor 0

    OBJETO NAME MIN MAX SMALL CHANGE LARGE CHANGE VALUE

    HScroll 1,2,3 hsbColor 0 255 1 16 0

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #5 En la siguiente prctica realizaremos carga y descarga de formularios, este proceso se realiza en una serie de dos

    pasos el primer evento y el segundo evento se debern realizar dos formularios como los marcan las siguientes

    imgenes:

    (PRIMER EVENTO)

    a) Carga y descarga de formularios: Cuando se arranca una aplicacin, o ms en concreto, cuando se visualiza por

    primera vez un formulario, se producen varios eventos ejecutivos, Initializate, Load, Activate, Paint. Cada uno

    de estos eventos se puede aprovechar para realizar ciertas operaciones correspondientes.

    Este es su cdigo Correspondiente:

    Primer Formulario:

    Private Sub cmdCargar_Click()

    frmSecundario.Show

    End Sub

    Private Sub cmdSalir_Click()

    End

    End Sub

    Segundo Formulario:

    Private Sub cmdHide_Click()

    Hide

    End Sub

    Private Sub cmdUnload_Click()

    Unload Me

    End Sub

    Private Sub cmdTerminate_Click()

    Hide

    Set frmSecundario = Nothing

    End Sub

    (SEGUNDO EVENTO)

    Al ocultar, cerrar o eliminar un formulario se produce otra serie de eventos.

    Desactivate, Query, Unload, Terminate.

    Este es el cdigo correspondiente a esta opcin y se coloca despus de probar el segundo

    formulario, y se coloca en el segundo formulario:

    Private Sub Form_Activate()

    MsgBox ("Evento Activate")

    End Sub

    Private Sub Form_Deactivate()

    MsgBox ("Evento Deactivate")

    End Sub

    Private Sub Form_Initialize()

    MsgBox ("Evento Initialize")

    End Sub

    Private Sub Form_Load()

    MsgBox ("Evento Load")

    End Sub

    Private Sub Form_Paint()

    MsgBox ("Evento Paint")

    End Sub

    Private Sub Form_QueryUnload(Cancel As

    Integer, UnloadMode As Integer)

    MsgBox ("Evento QueryUnload")

    End Sub

    Private Sub Form_Terminate()

    MsgBox ("Evento Terminate")

    End Sub

    Private Sub Form_Unload(Cancel As Integer)

    MsgBox ("Evento Unload")

    End Sub

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #6 En esta prctica aprenderos a utilizar los comandos como son Limpiar y Borrar, con los mismos

    procedimientos de las prcticas anteriores:

    OBJETO NAME CAPTION o TEXT

    Formulario frmLista Lista

    Label 1 lblIntroducir Introducir Datos

    Text1 txtEntrada

    Label 2 lblLista Lista de Datos

    ListBox lstLista

    Label 3 lblMedia Valor medio

    Text2 txtMedia

    Comand 1 cmdAgregar Agregar

    Comand 2 cmdEliminarU Eliminar Ultimo

    Comand 3 cmdEliminarT Eliminar Todo

    Comand 4 cmdSalir Salir

    Comand 5 cmdCalcular Calcular

    Text3 txtDesv

    Label 4 lblDesv Desviacin tpica

    A continuacin se muestra el cdigo del formulario:

    Private Sub cmdAgregar_Click() Este es nuestro formulario:

    If IsNumeric(txtEntrada.Text) Then

    lstLista.AddItem Val(txtEntrada.Text)

    Else

    MsgBox ("Un valor nmerico, por favor!")

    End If

    txtEntrada.Text = ""

    txtMedia.Text = ""

    txtDesv.Text = ""

    txtEntrada.SetFocus

    End Sub

    Private Sub cmdCalcular_Click()

    Dim I As Integer

    Dim media, desv As Double

    media = 0#: desv = 0#

    If lstLista.ListCount > 1 Then

    For I = 0 To lstLista.ListCount - 1

    media = media + lstLista.List(I)

    Next I

    media = media / lstLista.ListCount

    For I = 0 To lstLista.ListCount - 1

    desv = desv + (lstLista.List(I) - media) ^ 2

    Next I

    desv = desv / (lstLista.ListCount - 1)

    Else

    MsgBox ("Por favor, agregar un valor")

    End If

    txtMedia.Text = Format(media, "###0.00")

    txtDesv.Text = Format(Sqr(desv), "###0.00")

    txtEntrada.SetFocus

    End Sub

    Private Sub cmdEliminarT_Click()

    lstLista.Clear

    txtMedia.Text = ""

    txtDesv.Text = ""

    txtEntrada.Text = ""

    txtEntrada.SetFocus

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    End Sub

    Private Sub cmdEliminarU_Click()

    If lstLista.ListCount > 0 Then

    lstLista.RemoveItem (lstLista.ListCount - 1)

    End If

    txtMedia.Text = ""

    txtDesv.Text = ""

    txtEntrada.SetFocus

    End Sub

    Private Sub cmdSalir_Click()

    End

    End Sub

    Private Sub Form_Load()

    lstLista.Clear

    End Sub

    Private Sub Form_Paint()

    txtEntrada.SetFocus

    End Sub

    Private Sub txtEntrada_KeyPress(KeyAscii As Integer)

    If (KeyAscii = 13) Then

    If IsNumeric(txtEntrada.Text) Then

    lstLista.AddItem Val(txtEntrada.Text)

    Else

    MsgBox ("Un valor nmerico, por favor!")

    End If

    txtEntrada.Text = ""

    txtMedia.Text = ""

    txtDesv.Text = ""

    txtEntrada.SetFocus

    End If

    End Sub Despus proceda a guarda su proyecto y su formulario:

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #7

    En esta prctica se muestra en el formulario diferentes comandos, el fin de esta prctica es aprender el

    funcionamiento de cada uno de ellos e incorporando el uso de mdulos, viendo cul es su funcin. Primero

    se crea el formulario y luego se agrega el modulo.

    Este es nuestro formulario:

    Este es su cdigo:

    Option Explicit

    Private Sub cmdAgregar_Click()

    If IsNumeric(txtEntrada.Text) Then

    lstNum.AddItem Val(txtEntrada.Text)

    Else

    MsgBox ("A numeric value, please!")

    End If

    txtEntrada.SetFocus

    txtEntrada.Text = ""

    txtMax.Text = ""

    txtMin.Text = ""

    txtSum.Text = ""

    End Sub

    Private Sub cmdLimpiar_Click()

    lstNum.Clear

    txtEntrada.SetFocus

    txtMax.Text = ""

    txtMin.Text = ""

    txtSum.Text = ""

    End Sub

    Private Sub cmdSalir_Click()

    End

    End Sub

    Private Sub cmdMaximo_Click()

    Dim Nums(1 To 30) As Integer

    Dim i As Integer

    For i = 1 To lstNum.ListCount

    lstNum.ListIndex = i - 1

    Nums(i) = lstNum.List(lstNum.ListIndex)

    Next i

    txtMax.Text = Max(Nums, lstNum.ListCount)

    lstNum.ListIndex = -1

    txtEntrada.SetFocus

    End Sub

    Private Sub cmdMinimo_Click()

    Dim Nums(1 To 30) As Integer

    Dim i As Integer

    For i = 1 To lstNum.ListCount

    lstNum.ListIndex = i - 1

    Nums(i) = lstNum.List(lstNum.ListIndex)

    Next i

    txtMin.Text = Min(Nums, lstNum.ListCount)

    lstNum.ListIndex = -1

    txtEntrada.SetFocus

    End Sub

    Private Sub cmdEliminarU_Click()

    lstNum.RemoveItem lstNum.ListCount - 1

    txtEntrada.SetFocus

    txtMax.Text = ""

    txtMin.Text = ""

    txtSum.Text = ""

    End Sub

    Private Sub cmdOrdenar_Click()

    Dim Nums(1 To 30) As Integer

    Dim i As Integer

    For i = 1 To lstNum.ListCount

    lstNum.ListIndex = i - 1

    Nums(i) = lstNum.List(lstNum.ListIndex)

    Next i

    Call Ordenar(Nums, lstNum.ListCount)

    For i = 1 To lstNum.ListCount

    lstNum.ListIndex = i - 1

    lstNum.List(lstNum.ListIndex) = Nums(i)

    Next i

    lstNum.ListIndex = -1

    txtEntrada.SetFocus

    End Sub

    Private Sub cmdSuma_Click()

    Dim sum, i As Integer

    For i = 0 To lstNum.ListCount - 1

    sum = sum + Val(lstNum.List(i))

    Next i

    txtSum.Text = sum

    txtEntrada.SetFocus

    End Sub

    Private Sub Form_Paint()

    txtEntrada.SetFocus

    End Sub

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    Private Sub txtEntrada_KeyPress(KeyAscii As Integer)

    If (KeyAscii = 13) Then

    If IsNumeric(txtEntrada.Text) Then

    lstNum.AddItem Val(txtEntrada.Text)

    Else

    MsgBox (Solo Numeros, por favor!") End If

    txtEntrada.Text = ""

    txtMax.Text = ""

    txtMin.Text = ""

    txtSum.Text = ""

    End If

    End Sub

    Ahora veremos como insertar un mdulo:

    Y este es su cdigo:

    Public Sub Ordenar(Numbers() As Integer, N As Integer)

    Dim Temp As Integer

    Dim i, j As Integer

    For i = 1 To N - 1

    For j = i + 1 To N

    If Numbers(i) > Numbers(j) Then

    Temp = Numbers(i)

    Numbers(i) = Numbers(j)

    Numbers(j) = Temp

    End If

    Next j

    Next i

    End Sub

    Public Function Max(Numbers() As Integer, N As Integer) As Integer

    Dim i As Integer

    maximum = Numbers(1)

    For i = 2 To N

    If Numbers(i) > maximum Then

    maximum = Numbers(i)

    End If

    Next i

    End Function

    Public Function Min(Numbers() As Integer, N As Integer) As Integer

    Dim i As Integer

    minimum = Numbers(1)

    For i = 2 To N

    If Numbers(i) < minimum Then

    minimum = Numbers(i)

    End If

    Next i

    End Function

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #8

    Para poder realizar esta prctica, primero deber crear un formulario principal, y luego crear de uno por uno

    los dems, aqu aplicaremos varios comandos ya utilizados anteriormente.

    ESTE ES EL FORMULARIO PRINCIPAL:

    Estas son las propiedades del formulario principal:

    Ahora agregamos un nuevo formulario:

    SEGUNDO FORMULARIO:

    Este ser el nuevo formulario:(Para realizar

    este formulario deber insertar algunas

    imgenes de semforo y son tres).

    Estas son sus propiedades:

    OBJETO NAME CAPTION O PICTURE

    Formulario frmButton Semforo

    ImgRed imgRed Icono

    ImgVerde imgVerde Icono

    ImgAmarillo imgAmarillo Icono

    Comandd1 cmdChange Cambiar lu&z

    Comandd2 cmdClose &Cerrar

    El formulario siguiente es el que a continuacin se muestra TERCER FORMULARIO:

    OBJETO NAME CAPTION

    Formulario frmMain Ejemplos de controles

    Men File mnuFile File

    Men File Options mnuFileOp Options

    Comandd1 cmdButtons &Semforo

    Comandd2 cmdWordWrap &Etiquetas

    Comandd3 cmdCheck &Botones de Selecci

    Comandd4 cmdOption Botones de O&pcin

    Comandd5 cmdExit E&xit

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    Estas son sus propiedades:

    CONTROL NAME CAPTION

    Formulario frmWordWrap WordWrap and Autosize

    Label1 lblDisplay Ejemplo de uso de las

    propiedades AutoSize y

    WordWrap en las Labels.

    Frame1 Frame1 Alineacin:

    Option 1 optIzda Izquierda

    Option 2 optDcha Derecha

    Option 3 optCentro Centrado

    Frame2 Frame2

    Check1 chkAutoSize &AutoSize

    Check2 chkWordWrap &WordWrap

    Comandd1 cmdClose &Cerrar

    Este es el CUARTO FORMULARIO:

    Este es el QUINTO FORMULARIO:

    Ya terminados todos nuestros formularios procedamos a ingresar el cdigo:

    PRIMER FORMULARIO:

    Private Sub cmdBotones_Click() mnuSemaforo_Clic

    End Sub

    Private Sub cmdCajaVerificacion_Click() mnuCheck_Click

    End Sub

    Private Sub cmdSalir_Click() Unload Me

    End

    End Sub

    Private Sub cmdBotonesOpcion_Click()

    mnuOption_Click

    End Sub

    Private Sub cmdWordWrap_Click()

    mnuLabel_Click

    End Sub

    Private Sub Form_Load()

    frmMain.Height = 3600 frmMain.Width = 4965

    End Sub

    Private Sub mnuSemaforo_Click() frmBotones.Show

    End Sub

    Private Sub mnuCheck_Click() frmCajasVerificacion.Show

    End Sub

    Private Sub mnuFileExit_Click()

    cmdSalir_Click

    End Sub

    Private Sub mnuOption_Click()

    frmOptiones.Show

    End Sub

    Private Sub mnuLabel_Click()

    frmWordWrap.Show

    End Sub

    SEGUNDO FORMULARIO:

    Private Sub CambiarLuz()

    If imgGreen.Visible = True Then

    imgGreen.Visible = False

    imgYellow.Visible = True

    ElseIf imgYellow.Visible = True Then imgYellow.Visible = False

    imgRed.Visible = True Else

    imgRed.Visible = False

    imgGreen.Visible = True End If

    End Sub

    Private Sub cmdCambiarLuz_Click() Call CambiarLuz

    End Sub

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    Private Sub cmdSalir_Click() Unload Me

    End Sub

    Private Sub Form_Load() imgGreen.Visible = True

    imgYellow.Visible = False

    imgRed.Visible = False

    End Sub

    Private Sub imgGreen_Click()

    Call CambiarLuz

    End Sub

    Private Sub imgRed_Click()

    Call CambiarLuz

    End Sub

    Private Sub imgYellow_Click()

    Call CambiarLuz

    End Sub

    TERCER FORMULARIO:

    Private Sub chkAutoSize_Click()

    lblDisplay.Left = 480 lblDisplay.Width = 1730

    lblDisplay.Height = 225

    lblDisplay.AutoSize = Not lblDisplay.AutoSize

    End Sub

    Private Sub chkWordWrap_Click() lblDisplay.Left = 480

    lblDisplay.Width = 1730

    lblDisplay.Height = 225 lblDisplay.WordWrap = Not lblDisplay.WordWrap

    End Sub

    Private Sub cmdSalir_Click()

    Unload Me

    End Sub

    Private Sub Form_Load()

    lblDisplay.Left = 480

    lblDisplay.Top = 480 lblDisplay.Width = 1730

    lblDisplay.Height = 225

    lblDisplay.AutoSize = False

    lblDisplay.WordWrap = False

    lblDisplay.Alignment = 0

    End Sub

    Private Sub optCentro_Click()

    lblDisplay.Alignment = 2

    End Sub

    Private Sub optDerecha_Click()

    lblDisplay.Alignment = 1

    End Sub

    Private Sub optIzquierda_Click()

    lblDisplay.Alignment = 0

    End Sub

    CUARTO FORMULARIO:

    Private Sub chkNegritas_Click() txtDisplay.FontBold = Not txtDisplay.FontBold

    End Sub

    Private Sub chkItalica_Click() txtDisplay.FontItalic = Not txtDisplay.FontItalic

    End Sub

    Private Sub cmdSalir_Click() Unload Me

    End Sub

    QUINTO FORMULARIO:

    Dim tipoPC As String

    Dim tipoSO As String

    Sub Escribir()

    lblDisplay.Caption = "Ha seleccionado un " & _ tipoPC & " con " & tipoSO

    End Sub

    Private Sub cmdSalir_Click() Unload Me

    End Sub

    Private Sub Form_Load()

    optAMD_Click

    optWin95_Click

    End Sub

    Private Sub opt686_Click()

    tipoPC = "Pentium II/III" Call Escribir

    End Sub

    Private Sub optAMD_Click() tipoPC = "AMD"

    Call Escribir

    End Sub

    Private Sub opt586_Click()

    tipoPC = "Pentium"

    Call Escribir

    End Sub

    Private Sub optWin95_Click()

    tipoSO = "Windows 95/98" Call Escribir

    End Sub

    Private Sub optWinNT_Click() tipoSO = "Windows NT"

    Call Escribir

    End Sub

    NOTA: Para guardar este proyecto deber guardar los formularios de uno por uno y al final el proyecto.

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #9

    En esta prctica se utiliza varios comandos diseados especialmente para las barras de desplazamiento, y

    utilizaremos los Picture Box o (Cajas de dibujo), Aprenders a formar figuras mediante un cdigo:

    Este es su cdigo:

    Option Explicit

    Dim vx, vy, t, altura, anchura, xpos As Double

    Private Sub cmdDispara_Click()

    vx = Val(txtV.Text) * Cos(Val(txtAngulo.Text) * 3.141592 / 180#)

    vy = Val(txtV.Text) * Sin(Val(txtAngulo.Text) * 3.141592 / 180#)

    Timer1.Interval = 50

    Timer1.Enabled = True

    t = 0 Este ser nuestro formulario:

    End Sub

    Private Sub cmdSalir_Click()

    End

    End Sub

    Private Sub Form_Load()

    pctBox.Scale (0, 100)-(200, 0)

    t = 0

    txtV.Text = 35

    txtAngulo.Text = 50

    pctBox.Circle (190, 10), 10, vbRed

    pctBox.Line (100, 0)-(120, 50), vbRed, BF

    altura = 50

    vsbAltura.Value = 100 - altura

    anchura = 20

    hsbAnchura.Value = anchura

    xpos = 100

    hsbXpos.Value = xpos

    End Sub

    Private Sub hsbXpos_Change()

    xpos = hsbXpos.Value

    pctBox.Cls

    pctBox.Circle (190, 10), 10, vbRed

    pctBox.Line (xpos, 0)-(xpos + anchura, altura), vbRed, BF

    End Sub

    Private Sub Timer_Timer()

    Dim x, y As Double

    Dim distancia As Double

    pctBox.Cls

    pctBox.Circle (190, 10), 10, vbRed

    pctBox.Line (xpos, 0)-(xpos + anchura, altura), vbRed, BF

    t = t + 0.1

    x = vx * t

    y = vy * t - 9.81 / 2# * t * t

    pctBox.DrawWidth = 3

    pctBox.PSet (x, y), vbRed

    pctBox.DrawWidth = 1

    If x > xpos Then

    If y > 0 Then

    If x < xpos + anchura Then

    If y < altura Then

    MsgBox ("Ha tocado el bloque")

    Timer1.Enabled = False

    End If

    End If

    End If

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    End If

    distancia = Sqr((x - 190) ^ 2 + (y - 10) ^ 2)

    If distancia < 10 Then

    Beep

    MsgBox ("Ganaste")

    Timer1.Enabled = False

    End If

    End Sub

    Private Sub vsbAltura_Change()

    altura = 100 - vsbAltura.Value

    pctBox.Cls

    pctBox.Circle (190, 10), 10, vbRed

    pctBox.Line (xpos, 0)-(xpos + anchura, altura), vbRed, BF

    End Sub

    Private Sub hsbAnchura_Change()

    anchura = hsbAnchura.Value

    pctBox.Cls

    pctBox.Circle (190, 10), 10, vbRed

    pctBox.Line (xpos, 0)-(xpos + anchura, altura), vbRed, BF

    End Sub

    *Ahora guardamos nuestra aplicacin*

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    PRACTICA #10

    Esta prctica tiene varios formularios como la practica 8, pero en esta aplicacin veremos como introducir

    imgenes, que no son de utilidad para crear mejores bases de datos e incluso agendas electrnicas:

    Este ser el primer formulario: Este es su cdigo: Option Explicit

    Dim Por(1 To 3) As String

    Dim Def(1 To 12) As String

    Dim Med(1 To 12) As String

    Dim Del(1 To 12) As String

    Dim nPor As Integer, nTotalPor As Integer

    Dim nDef As Integer, nTotalDef As Integer

    Dim nMed As Integer, nTotalMed As Integer

    Dim nDel As Integer, nTotalDel As Integer

    Function BuscarAlin(jug As String) As Boolean

    BuscarAlin = False

    Dim i As Integer

    For i = 0 To lstAlin.ListCount - 1

    If jug = lstAlin.List(i) Then BuscarAlin = True

    Next i

    End Function

    Sub AddJugadores(Juga() As String, n As Integer)

    Dim i As Integer

    For i = 1 To n

    lstJuga.AddItem (Juga(i))

    Next

    End Sub

    Function id(jugador As String) As String Este ser el segundo formulario: Dim i As Integer

    For i = 1 To nTotalPor

    If StrComp(jugador, Por(i)) = 0 Then

    id = "Portero"

    Exit Function

    End If

    Next i

    For i = 1 To nTotalDef

    If StrComp(jugador, Def(i)) = 0 Then

    id = "Defensa"

    Exit Function

    End If

    Next i

    For i = 1 To nTotalMed Este ser el tercer formulario:

    If StrComp(jugador, Med(i)) = 0 Then

    id = "Medio"

    Exit Function

    End If

    Next i

    For i = 1 To nTotalDel

    If StrComp(jugador, Del(i)) = 0 Then

    id = "Delantero"

    Exit Function

    End If

    Next i

    End Function

    Sub Imprimir()

    lblPor.Caption = nPor

    lblDef.Caption = nDef

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    lblMed.Caption = nMed

    lblDel.Caption = nDel

    Dim nJug As Integer

    nJug = nPor + nDef + nMed + nDel

    If nJug > 11 Then

    nJug = MsgBox("Desea alinear ms de 11 jugadores?" + vbCrLf + _

    "Recuerde que tendr que convencer al rbitro y al otro equipo")

    End If

    End Sub

    Sub AnadirSiNoEstaYa(jug As String)

    Dim puesto As String

    If BuscarAlin(jug) = False Then

    lstAlin.AddItem (jug)

    puesto = id(jug)

    If puesto = "Portero" Then nPor = nPor + 1

    If puesto = "Defensa" Then nDef = nDef + 1

    If puesto = "Medio" Then nMed = nMed + 1

    If puesto = "Delantero" Then nDel = nDel + 1

    End If

    End Sub

    Private Sub cmdAuto_Click()

    vanGaal.Show

    End Sub

    Private Sub cmdClear_Click()

    lstAlin.Clear

    nPor = 0

    nDef = 0

    nMed = 0

    nDel = 0

    Call Imprimir

    End Sub

    Private Sub cmdJugadores_Click()

    frmBarsa.Show

    End Sub

    Private Sub cmdSalir_Click()

    End

    End Sub

    Private Sub Form_Load()

    Por(1) = "Hesp"

    Por(2) = "Andreu"

    nTotalPor = 2

    Def(1) = "Abelardo"

    Def(2) = "Dehu"

    Def(3) = "Sergi"

    Def(4) = "Ronald de Boer"

    Def(5) = "Reiziger"

    Def(6) = "Bogarde"

    Def(7) = "Puyol"

    Def(8) = "Frank de Boer"

    nTotalDef = 8

    Med(1) = "Litmanen"

    Med(2) = "Guardiola"

    Med(3) = "Xavi"

    Med(4) = "Gabri"

    Med(5) = "Cocu"

    Med(6) = "Mario"

    nTotalMed = 6

    Del(1) = "Figo"

    Del(2) = "Rivaldo"

    Del(3) = "Luis Enrique"

    Del(4) = "Dani"

    Del(5) = "Kluiwer"

    Del(6) = "Zenden"

    Del(7) = "Simao"

    Del(8) = "Nano"

    Del(9) = "Amunike"

    nTotalDel = 9

    nPor = 0

    nDef = 0

    nMed = 0

    nDel = 0

    Call AddJugadores(Por, 3)

    Call Imprimir

    End Sub

    Private Sub lblDef_Change()

    Dim resp As Integer

    If nDef > 5 Then

    resp = MsgBox("Desea jugar con ms de 5 defensas?", vbOKOnly)

    End If

    End Sub

    Private Sub lblPor_Change()

    Dim resp As Integer

    If nPor > 1 Then

    resp = MsgBox("Desea jugar con ms de un portero?" _

    + vbCrLf + "Recuerde que slo uno podr tocar el baln con la mano", vbOKOnly)

    End If

    End Sub

  • VISUAL BASIC CECYTEM TECAMAC

    P. Ing. Ren Domnguez Escalona

    Private Sub lstAlin_Click()

    Dim jug As String, puesto As String

    jug = lstAlin.List(lstAlin.ListIndex)

    lstAlin.RemoveItem (lstAlin.ListIndex)

    puesto = id(jug)

    If puesto = "Portero" Then nPor = nPor - 1

    If puesto = "Defensa" Then nDef = nDef - 1

    If puesto = "Medio" Then nMed = nMed - 1

    If puesto = "Delantero" Then nDel = nDel 1

    Call Imprimir

    End Sub

    Private Sub lstJuga_Click()

    Dim jug As String

    jug = lstJuga.List(lstJuga.ListIndex)

    Call AnadirSiNoEstaYa(jug)

    Call Imprimir

    End Sub

    Private Sub optDef_Click()

    lstJuga.Clear

    Call AddJugadores(Def, nTotalDef)

    End Sub

    Private Sub optDel_Click()

    lstJuga.Clear

    Call AddJugadores(Del, nTotalDel)

    End Sub

    Private Sub optMed_Click()

    lstJuga.Clear

    Call AddJugadores(Med, nTotalMed)

    End Sub

    Private Sub optPor_Click()

    lstJuga.Clear

    Call AddJugadores(Por, nTotalPor)

    End Sub

    Ahora guardamos los cambios realizados en nuestra aplicacin y hasta aqu terminan nuestro primer bloque de

    prcticas.