Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
html He escrito (y grabado videos) sobre muchas cosas respecto a Visual Basic .net (versin 2005, 2008 y 2010, que es casi lo mismo). Alguna vez hice un pequeo video mostrando como crear una aplicacin desde cero (llamado Un programa sencillo para ir calentando que adivina un nmero al azar entre 1 y 10), sin embargo creo que con el puro video no queda claro para muchos, as que en esta ocasin voy a mostrar, paso a paso, como crear un programa sencillo en Visual Basic 2010.
Ahora haz clic sobre el botn de nuevo proyecto. Recuerda que un proyecto para Visual Studio es toda la bola de archivos necesarios para crear un programa (o sea que es una carpeta con muchas archivos y subcarpetas). Este es el botn:
Hay que elegir el lenguaje de la barra izquierda (Visual Basic), vamos a elegir Windows Forms Application (que hace un programa como los que estamos acostumbrados a ver en Windows) y le ponemos un nombre a la aplicacin. En el ejemplo que voy a hacer, solo cambio el nombre (lo dems est seleccionado como lo necesito: si el tuyo aparece un poco diferente, solo selecciona lo que aqu indiqu). Mi aplicacin se va a llamar 00-Ejemplo. Nota: en algunas versiones te pregunta la carpeta donde lo vas a guardar.
3. Ambiente de programacin. Nota: la flecha que no tiene texto apunta hacia la ventana como la ver el usuario.
Antes de hablar de los pasos siguientes, quiero que te familiarices con el entorno de trabajo. Aunque las cosas pueden cambiar (Visual Studio te da la oportunidad de configurar tu entorno de trabajo como quieras), generalmente a la izquierda est un panel con los diferentes controles que puedes dibujar en la ventana: botones, cajas de texto, etc. Arriba est la barra de men y algunos botones de funciones (como el de Nuevo Proyecto que presionamos antes). De lado derecho, tenemos el explorador de soluciones (que muestra todos los archivos que componen el proyecto) y abajo una ventana que tiene las propiedades del objeto seleccionado (colores, etc.). En la parte inferior hay una ventana donde me pueden aparecer mensajes (sobre todo a la hora de compilar y correr un programa) y en la parte central es el rea de trabajo. Para este ejemplo, solo voy a dibujar 3 controles: una etiqueta (conocidos como Label), una caja de texto (Textbox) y un botn (Button). Pero antes que nada, voy a modificar la ventana principal al cambiar sus propiedades. Para empezar, arriba de la ventana le va a aparecer el texto que dice Form1 (como se ve en la figura). Yo quiero cambiarlo para que diga Saludos.
Para hacer esto hago clic sobre la ventana en la vista diseo y cambia la ventana de propiedades para mostrar las que se relacionan a la ventana (o Form). Ahora busco la propiedad que se llama Text y le modifico el valor para que diga Saludos.
Una vez que escribo Saludos en lugar de Form1, mi ventana se ve as (en la vista diseo):
Ahora voy a cambiar propiedades de la ventana (Form1) para que ya no tenga botn de minimizar ni de maximizar. Esto lo hago modificando las propiedades MinimizeBox y MaximizeBox respectivamente. Al cambiar True (verdadero, o sea que s tiene esa caja) por false (falso, que lo oculte) resuelvo la situacin. Aqu est la ventana con estas dos propiedades sealadas y abajo est la ventana ya sin cajas de minimizar ni maximizar.
Ahora voy a dejar la ventana por la paz y voy a dibujar la etiqueta. Voy al panel de los controles (lado izquierdo) y selecciono la que dice Label como se muestra en la imagen:
9. Herramienta Label.
Luego hago clic sobre la ventana en el lugar donde quiero que quede
Y en este momento ya tengo un control en mi ventana, llamado Label1, que contiene un texto. Ahora, aprovechando que est seleccionado (y si no, solo haz clic sobre la etiqueta), voy a modificar su propiedad Text para que diga Nombre en lugar de Label1
De la misma manera voy a dibujar una caja de texto. Selecciono la caja de texto del panel de controles (o herramientas) y lo dibujo sobre la ventana. Generalmente a los controles que voy a programar me gusta cambiarles el nombre para no hacerme bolas, as que a este le cambio la propiedad (Name) para que diga txtNombre. La parte txt me dice que es una caja de texto si quieres profundizar en esto, busca la notacin hngara. Aqu hay imgenes con todo el proceso:
De la misma manera dibujo un botn abajo de la caja de texto. Aqu estn las imgenes que describen paso por paso:
Por lo pronto no le hagas caso al cdigo que aparece, ya luego lo iremos hablando (o lo puedes ver en varios de mis posts sobre Visual Basic .net). Por lo pronto, aparece el cdigo listo para escribir lo que queremos que haga cuando el usuario haga clic sobre el botn. Este es el cdigo que escrib:
No te preocupes si no entendiste todas las instrucciones (esto es un primer acercamiento y poco a poco podrs ir profundizando en lo que hace cada cosa). La instruccin MsgBox se encarga de abrir una ventana y mostrar un texto (bueno, puede hacer un poco ms que eso, pero para empezar hace esto). En medio escribo lo que quiero que diga, en este caso el texto Adis, seguido por el nombre que teclearon en la caja de texto (recuerdas que le cambiamos el nombre por txtNombre?). El ampersand (&) sirve para unir dos textos: en este
caso, el texto Adis, y el nombre tecleado. Despus de hacer esto, se encuentra la instruccin End que termina la ejecucin del programa.
Selecciona una carpeta (botn Browse) y, si es necesario, cambia el nombre. Luego haz clic sobre el botn Save. En las prximas ocasiones que presiones Save All ya no aparece esta ventana.
Paso 8. La ejecucin
No, esta ejecucin no tiene que ver con violencia, sino con ver si el programa hace lo que queremos que haga. Para esto, presiona el botn para comenzar la depuracin (Start debugging):
Al presionar el botn Aceptar (o presionar la tecla Enter), se termina la ejecucin y regreso a Visual Studio.
Click on Windows Form Application, and name the project "Your name's Dictionary" and then click Ok.
Change the text property of the form to "your name's dictionary". Add a label, textbox and a button to the form. Change the text of the label to Word, and change the text of the button to Search.
Add another text box to the form and change it's property to Multiline:
Resize the textbox you just added and add a label above it. Change the label text to Definition:
Add a listbox to the form and place it like the picture below:
Page 2
The dictionary will show the English words once it launches. We will add a code to fill up the list box with English words. Double click on the form and add the following highlighted code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ListBox1.Items.Add("aardvark") ListBox1.Items.Add("aardwolf") ListBox1.Items.Add("aaron") ListBox1.Items.Add("aback")
ListBox1.Items.Add("abacus") ListBox1.Items.Add("abaft") ListBox1.Items.Add("abalone") ListBox1.Items.Add("abandon") ListBox1.Items.Add("abandoned") ListBox1.Items.Add("abandonment") ListBox1.Items.Add("abandons") ListBox1.Items.Add("abase") ListBox1.Items.Add("abased") ListBox1.Items.Add("abasement") ListBox1.Items.Add("abash") ListBox1.Items.Add("abashed") ListBox1.Items.Add("abate") ListBox1.Items.Add("abated") ListBox1.Items.Add("abatement") End Sub
Notice how the English words are inserted into the code. You can add all English words to the dictionary. Adding the list of English words to the dictionary will take a lot of time, specially that you have to insert every single word in the codes. It would be easier if we use a database to store the words and retrieve them. But think about it this way: if you are programming a dictionary, you know exactly what words to add and what definitions, so the user will not update words and add definitions and that's why we do not need a database. Don't worry about the list of English words and how to insert them into the codes. If you are reading this tutorial you are probably want to learn programming using Visual Basic. Why don't you learn how to convert the English words to codes in less than 2 minutes? Click here to learn how to convert the English words that are available on this website to codes. Expand your knowledge!!! We want to make sure the words are listed in alphabetical order. To do that add the following code between the last English word inside the code and End sub:
We will add a code that when you start typing in the search box, the listbox will highlight or select a matching word. Double click on the textbox and add the following highlighted code:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged Dim Item As String = TextBox1.Text.ToString() Dim index As Integer = ListBox1.FindString(Item) If index = -1 Then ListBox1.SelectedIndex = ListBox1.SelectedIndex Else ListBox1.SetSelected(index, True) End If End Sub
When you type a word in the search box, the word will highlight in the listbox Let's program the Search button, so when the user types a word an clicks the button, they get the definition in the big text box. Let's say the user wants the definition of the word ABACUS, so they types the word abacus in the search box and they hit the search button. They suppose to get the following definition: A manual computing device consisting of a frame holding parallel rods strung with movable counters. (Excerpted from American Heritage Talking Dictionary Copyright 1997 The Learning Company, Inc. All Rights Reserved.) Double click on the search button and add the following highlighted code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If TextBox1.Text = "abacus" Then TextBox2.Text = "A manual computing device consisting of a frame holding parallel rods strung with movable counters." ElseIf TextBox1.Text = "abash" Then TextBox2.Text = "To make ashamed or uneasy; disconcert." Else 'A message box will show up if the entered word is not found MsgBox("No mathcing results where found")
You can add as many definitions as you can to the dictionary. We will make the search button also accepts the Enter key as a trigger to the search button: Right click on the form and click on properties: Change AcceptButton property to Button1 as follows:
You might also add a feature to the dictionary that when the user double clicks on a word in the listbox, the definition will show for the selected word. To do that: on the designer page, single click on listbox1, change the properties window to events like follows:
Look for DoubleClick event, and double click on the empty bar next to it: