Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Paletas Delphi 7
Delphi XE
Conceptos bsicos.
Proyecto. Un proyecto es un conjunto de mdulos de formulario, de cdigos y de
archivos que componen una aplicacin. La ventana View Project Manager muestra
todos los archivos que componen una aplicacin.
Formulario. Ventana con el diseo y el cdigo asociado a dicho formulario.
Componentes. Los componentes son objetos como cuadros, botones, etiquetas que
se disponen en un formulario o ventana para manipular o mostrar datos. Para poner los
componentes en un formulario usar la Tool Palette.
Propiedades. Usando la ventana de Object inspector (F11) se definen las propiedades
de formularios y controles. Las propiedades especifican los valores iniciales de las
caractersticas, tales como tamao, nombre y posicin.
Eventos: Es la respuesta a las acciones del usuario que desencadena una accin en el
programa.
Concepto de cdigo:
Es el texto escrito en un programa. El programa se divide en distintos apartados o
subrutinas generalmente como respuesta a un evento y se divide en procedimientos
(subrutinas) o funciones.
Acciones o subrutinas: Trozos de cdigo como respuesta a un evento o accin. No
recoge ni devuelve ningn dato.
Procedimientos: Trozos de cdigo como respuesta a un evento o accin. No
devuelven ningn valor pero s acepta o recoge uno o varios parmetros.
Funciones: Son procedimientos que adems devuelven un valor al procedimiento
desde donde se le llam
Diagrama de Flujo: Representa la esquematizacin grfica de un algoritmo, el cual
muestra grficamente los pasos o procesos a seguir para estructurar bien un programa.
Reglas de nomenclatura al declarar procedimientos o variables:
Deben comenzar por una letra
No pueden contener puntos
No puedes superar los 255 caracteres Propiedadesbsicasdelosobjetos:
Nombres de formularios no sobrepasar 40 caracteres Alignment Alineacin
No pueden tener el mismo nombre que una palabra clave BevelInner bordeinterior
Comentarios en el cdigo se inician con: // o entre { } BorderStyle estilodelborde
Caption rtulo
Eventos y acciones (sobre un componente): TabStop Saltotabulacin
Listadeeventos(Desencadenalaaccindeunobjeto) Color,Cursor Color,puntero
Enabled Activo
Evento Accin
Font Tipoletra
Click Alhacerclicconelmouse(oelteclado) Height Alturadelobjeto
DragDrop Alsoltaruncontrolarrastradoconelmouse Hint Etiquetaayuda
DragOver AlArrastraruncontrolconelmouse. Left Posicinizquierda
KeyDown Presionarunateclamientraselobjetotieneelfoco. Name Nombredelobjeto
KeyPress PresionarunateclaydevolversuvalorASCII. PopupMenu Mencontextual
KeyUp Liberarunateclamientraselobjetotieneelfoco. ShowHint Mostraretiquetas
MouseDown Presionarelbotndelmousesobreelobjeto. Top Posicinvertical
MouseMove Moverelpunterodelmouseporencimadelobjeto Visible Visible
MouseUp Liberarelbotndelmouseenelobjeto. Width Anchodelobjeto
Ejercicio 1. Crear una ventana hola mundo y un botn para cerrar.
Enprimerlugar,antesdetrabajarconDelphi,esaconsejablequecreesunacarpeta(subdirectorio)contu
nombreparaguardarahlosejercicios.
Crearunproyectonuevo:
Eligedelmen:FileNewAplication(oVCLFormsapplication)paracrearunnuevoproyecto.
Te aparecer una ventana o formulario vaco (Form). En el panel Inspector de objetos (Object Inspector),
verslaspropiedadesdelaventanaodelosobjetosqueenellapongas.
Cambiarelnombredelaventana:EnelpanelObjectInspector,pestaaProperties(Propiedades),hazclicen
Caption(rtulo)yensucasillaescribe:Ventanaparaponerunrtuloalaventana.
end;
Para indicar una accin a un objeto escribir el nombre del objeto, un punto y su accin: Form1.close;
Si no pones el nombre del objeto, te refieres a la ventana en general: slo debers escribir la palabra: close
(cerrar la ventana) en el lugar indicado:
Procedure TForm1.Button1Click(Sender: TObject);
Begin
close; // -> Al final de una lnea de cdigo, poner punto y coma (;)
end;
Compilar y probar el programa: Pulsa el botn Run o elige del men: Run - run. Comprueba su
funcionamiento correcto cerrando la ventana.
Guardar el proyecto y los archivos fuentes:
1. Para guardar la ventana del formulario y su cdigo asociado elige del men: File Save as...
Hola1.pas
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg3
2. Para guardar el proyecto creado: elige del men: File Save project as... Hola (*.dpr o *.pdroj)
Ejercicio 2. Crear un contador de botones. Cambiar el nombre de los botones.
Crea un nuevo proyecto.
FileNewApplication (oVCLForms
application).
Selecciona cada componente aadido y en el Objet inspector (F11) cambia las siguientes propiedades:
En el Button1.Caption: Poner a cero
En el Button2.Caption: Contar
En el Button3.Caption: Salir
En el Panel1. Caption: 0 ; Panel1.Color:clWhite (blanco)
Selecciona cada componente creado y en el Objet inspector (F11) cambia los siguientes eventos, pulsando
doble clic sobre el evento: On clic o directamente sobre el componente:
Eventos: (pulsar doble clic en cada objeto)
En el Botn1: procedureTForm1.Button1Click(Sender:TObject);
begin
Panel1.Caption:='0';
end;
En el Boton2: procedureTForm1.Button2Click(Sender:TObject);
begin
Panel1.caption:=IntToStr(Strtoint(Panel1.caption)+1);
end;
En el Boton3: procedureTForm1.Button3Click(Sender:TObject);
begin
Close;
end;
Cambialavariabledeltiponumricoenteroacadenadetexto
Comentarios al ejercicio: Algunos componentes tienen propiedades del tipo de texto, numrico o lgicas.
No se pueden igualar o comparar propiedades de tipos diferentes. Para ello se debe realizar una conversin
de un formato a otro:
IntToStr convierte un valor numrico en un valor de texto para que se puedra mostrar en el panel1
StrtoInt Convierte un valor de tipo texto en su valor numrico
Probar la aplicacin:
Pulsa el botn Run o elige del men: Run run para comprobar su funcionamiento.
Guardar el proyecto: Crea una carpeta que se llame: Contador.
Escoge: File Save as... Para guardar el archivo de cdigo en la carpeta con el nombre: Contador1.pas
Escoge: File Save project as... Para guarda el proyecto en la carpeta con el nombre contador.dpr
Conversiones de tipos
IntToStr (Integer to String) Cambia del tipo de nmero entero a cadena de texto
StrToInt (String to Integer) Cambia del tipo cadena de texto a nmero entero
Otros:
Eventos:
Pulsa doble clic sobre el evento Timer1 para mostrar el procedure y aade el cdigo:
procedureTForm1.Timer1Timer(Sender:TObject);
begin
ProgressBar1.position:=ProgressBar1.position+1;//>incrementalabarraunaposicin
ifProgressBar1.position=100then //>sillegaa100
begin
Timer1.Enabled:=False; //>Paraeltemporizador
Showmessage('Transferenciarealizada'); //>muestraunmensaje
Application.Terminate; //>terminaelprograma
end;
end;
Comentarios al ejercicio:
Para asignar un valor a un objeto o variable se indica con : = Ejemplo: ProgressBar1.position:=100;
Para comparar el valor de un objeto o variable se indica con = Ejemplo: ifProgressBar1.position=100..
Ejecutayprueba(Run):Alpulsarelbotn,activamoseltemporizadorTimerquedesplazaunpixelaladerechala
posicindelbotnacadapulsodesuintervalo,deduracin10milisegundos.
Paraguardarprimerolaunidadyluegoelproyecto,escogedelmen:FileSaveprojectas...
Uso de variables de fecha y decimal:
Una variable almacena un valor temporalmente para utilizarlo despus.
Se nombran o declaran al inicio del procedimiento en la seccin var y pueden ser de fecha (datetime),
numricas (integer), decimales sencillas o dobles (single o double), de texto (string), etc
CreaunanuevaaplicacinVCL(libreravisual)escogiendo
delmen:FileNewVCLFormApplicaton.
Aade un botn Button1, dos etiquetas, labels y dos
DatetimePickerdelapaletaWin32.
CambiaelnombredelosDatetimePickerpor:
Fecha_iniyFecha_fin
Pulsa doble clic sobre el botn y escribe en el evento del
botnOnClick:
Procedure ...Button1Click(Sender: TObject);
var
dias:double;//>creounavariabledecimaldoble
hoy:Tdatetime;//>creounavariabledefechahora
begin
dias:=Fecha_Fin.DateFecha_ini.date;//>restolasdosfechas
hoy:=date();
Showmessage('Hoyes'+datetostr(hoy)+'yhantranscurrido'+floattostr(dias)+'dias');
end;
PulsaRunoF9paracomprobarsufuncionamiento.
Variantedelejercicio.Calculatuedad:
Cambiaelformulariocomoenlaimagen
EscribeeneleventodelbotnOnClick:
procedureTForm1.Button1Click(Sender:TObject);
var
dias:double;//>creounavariableparaguardarlosdias
anos:double;//>creounavariableparaguardarlosaos
hoy:Tdatetime;//>creounavariableparaguardareldiadehoy
begin
hoy:=date();//>guardoenlavariableeldadehoy
dias:=hoyMonthCalendar1.Date;//>calculolosdastranscurridos
anos:=dias/365; //>calculolosaostranscurridos
Showmessage('Tienes'+FormatFloat('##0.##',dias)+'diaso'+FormatFloat('##0.##',anos)+'aos');
end;
Ejecutayguarda(Run):PulsaRunoF9paracomprobarsufuncionamiento.
Paraguardarprimerolaunidadyluegoelproyecto,escogedelmen:FileSaveprojectas...
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg7
Comentarios: Al pulsar la tecla INTRO en el edit1 pone en la direccin del navegador, el texto del Edit1
AlgunosCdigosdeteclaASCII: Valor
Retroceso{backspace}, #8
Tab{tab} #9
Supr{delete}o{del} #127
Entrar{enter}o~ #13
Esc{esc} #27
Probar la aplicacin: Pulsa Run para comprobar su funcionamiento.
Guardar el proyecto: Crea una carpeta que se llame: OfiChrome
o Escoge: File Save as... Para guardar el archivo: OfiChrome.pas
o Escoge: File Save project as... OfiChrome.dpr
Mejoras:
En la ventana: En la propiedad de la ventana Form1 cambia su estado por maximizado: WindowState:
wsMaximized y el texto de la ventana (Caption) por CutreChrome
El cdigo:
Botones adelante y atras:
WebBrowser1.GoBack;yWebBrowser1.GoForward;
Botn para ir:
procedureTHeaderFooterForm.btnIrClick(Sender:TObject);
begin
WebBrowser1.URL:=Direccion.Text;
end;
Al teclear en direccin:
procedureTHeaderFooterForm.DireccionKeyDown(Sender:TObject;varKey:Word;
varKeyChar:Char;Shift:TShiftState);
begin
ifKey=vkReturnthen
begin
WebBrowser1.URL:=Direccion.Text;
btnIr.SetFocus;//poneelfocoparaquitarelteclado
end;
Mejoras:
En el control Edit, optimizar el Virtual Keyboard seleecionando vktURL como el tipo de
teclado virtual adecuado en la propiedad KeyboardType.
Establecer la propiedad KillFocusByReturn a True
Cambiar el Edit por un EditCombobox al que podamos aadir elementos a modo de historial al pulsar en Ir:
encontrado:=false;
fori:=0toDireccion.Items.count1do
begin
ifDireccion.Items[i]=Direccion.Textthenencontrado:=true;
end;
ifencontrado=falsethen
begin
//limitalalistaa10
ifDireccion.Items.count>10thenDireccion.Items.Delete(0);
Direccion.Items.Add(Direccion.Text);//aadiralalista...
end;
Compilar:
Compilar por emulardor: Para probar la emulacin de Android se debe
instalar las android SDK manager y escoger en el Target el emulador:
rxe5_android (muy lento)
CambialapropiedaddelformularioForm1.Stylebook:porStyleBook1
Probarlaaplicacin:
PulsaelbotnRunoeligedelmen:Runrunparacomprobarsu
funcionamiento.
Guardarelproyecto:Creaunacarpetaquesellame:Contador.
Escoge:FileSaveas...Paraguardarelarchivodecdigoenlacarpeta
conelnombre:Areas1.pas
Escoge:FileSaveprojectas...Paraguardaelproyectoenlacarpeta
conelnombreAreas.dpr
Ejercicio FireMonkey2. Uso de los componentes de FireMonkey
Variacin al ejercicio anterior de reas del tringulo:
Cambia la propiedad del formulario Form1. Stylebook: por StyleBook1. Resource: Transparent
Pulsa doble clic sobre el botn Button1 y en el evento: OnClick del botn Button1 aadir el cdigo en negrita:
procedureTForm1.Button1Click(Sender:TObject);
begin
ifRadioButton1.IsChecked=truethen//siestaactivadorea
NumberBox1.Value:=SpinBox1.Value*SpinBox2.Value/2
elseNumberBox1.Value:=Sqrt(Sqr(SpinBox1.Value)+Sqr(SpinBox2.Value));
end;
Llamaremos al mismo evento: OnChange en los dos RadioButton y al evento OnCreat del formulario Form1
para que se cambie el texto de las etiquetas al empezar el programa o al cambiar de selector:
procedureTForm4.RadioButton1Change(Sender:TObject);
begin
ifRadioButton1.IsCheckedthen
begin
Label1.Text:='Base:';
Label2.Text:='Altura:';
Label3.Text:='rea:';
end
else
begin
Label1.Text:='Catetoa:';
Label2.Text:='Catetob:';
Label3.Text:='Hipotenusa:';
end;
end;
Probarlaaplicacin:
PulsaRunparacomprobarsufuncionamiento
Guardarelproyecto:Creaunacarpetaquesellame:Contador.
Escoge:FileSaveas...Paraguardarelarchivodecdigoenla
carpetaconelnombre:triangulos1.pas
Escoge:FileSaveprojectas...Paraguardaelproyectoenlacarpetaconelnombretriangulos.dpr
1. EnelpanelProjectManager,pulsaconelbotnDerechodelmousesobre
TargetPlatforms.
AddPlatform
Escoge64bitsWindows.
2. Pulsaconelbotnderechodelmousesobrelaplataforma64bitsyescoge:
Activate.
3. Compiladenuevolaaplicacinycompruebaquesemuestraenlacarpeta
Win64\Debuglaaplicacinexe.
Nota:SituFMRADStudiocorrebajox86(Win32)podrscompilaren64bitsperonopodrsejecutarlo.
1. Escogedelmen:Tools>Options>EnvironmentOptions>Connection
ProfileManagerpage.ClickenAdd
2. Escribeelnombredelprofile:ConexionMac.PlataformaOsX
3. PonelnombredetuequipoMacenlaredosuIP
4. EnelpanelProjectManager,pulsaconelbotnDerechodelmousesobre
TargetPlatforms.AddPlatformEscoge:OSX.
5. PulsaconelbotnderechodelmousesobrelaplataformaOSXyescoge:
AssignRemoteProfile.
6. SeleccionaAddparaabrirlaventanadeconexin
conunequipomacporred.
7. Escribeelnombredelaconexin:ConexionMac
Entonces,elIDEestarconectadocontuMac.
SipulsasF9seejecutarlaaplicacinentuMac
2 botones (Button)
1 etiqueta (Label)
Preparacin:
En el panel: Object Inspector (F11), pestaa de propiedades (Properties)
Edit 1 y Edit2: Cambiar su propiedad Text al valor: 0
Botones 1 y 2: Cambiar su propiedad Caption al texto de la figura superior.
Label 1: Cambiar la propiedad Caption al texto de la figura y la propiedad Font a
Negrita, tamao 12
Coccin:
Pulsar doble clic sobre el botn 1 para aadir al evento Onclic las siguientes lneas de comando:
(Lneasaaadirennegrita) Comentarios
procedure TForm1.Button1Click(Sender:
TObject); variablesautilizar:
var
nmero1ynmero2deltiponumricascondecimales
numero1,numero2:double;
begin
numero1:=strtofloat(edit1.text); Nmero1valeeltextodelEdit1convertido
numero2:=numero1/166.386; Nmero2=nmero2/166,386(ponerpuntodecimal)
edit2.text:=floattostr(numero2); EltextodelEdit2serelvalordelavariablenmero2
end; convertidaastring
Ejercicio Propuesto:
Pulsa doble clic sobre el botn 2 y aade el cdigo al botn2 para que multiplique el valor de Edit1 por
166,386
Variantes al programa:
Para evitar tener que crear variables que almacenen el valor temporalmente, podramos haber realizado la
conversin directamente del siguiente modo:
Edit2.text:=floattostr(strtofloat(edit1.text)/166.386)
Sin embargo, es ms seguro para su comprobacin en caso de error, dividir el cdigo en varias lneas.
Evitar errores al introducir una letra el lugar de un nmero en los edits:
Se puede controlar con un MaskEdit, usando la funcin Format, FormatFloat/FloatToStrF o evaluando si
es numrico antes de realizar operaciones matemticas: IsNan (Is Not a Number). Vanse todos en la ayuda.
Guarda el proyecto y su unidad (conversor1.pas) en una carpeta independiente, por ejemplo en
C:\Archivos de Programa\Borland\Delphi\Conversor con el nombre del proyecto: Conversor.dpr
Objetivo: Se trata de la estructura base para el movimiento de un objeto en un juego evaluando con un IF el
estado de la variable subir que como es lgica (booleriana) puede ser verdadera (true) o falsa (false).
Ingredientes:
7 Labels de la paleta Estandar
1 Image de la paleta Adicional
1 Timer (temporizador) de la paleta System
Preparacin:
En sus propiedades (Properties), los objetos tendrn el
nombre (Name) que se indica en la imagen de la izquierda.
Cambia las propiedades (Properties) de los elementos:
Label 1: Cambiar propiedad Caption: Altura
Label 2: Cambiar propiedad Caption: Choques
Label 3: Cambiar propiedad Caption: Toques
Timer1: Poner su estado Enabled: False y su Interval: 1
Labelaltura, Labeltoques y Labelchoques: poner caption a
cero.
Image1: Picture: Cargar el dibujo de una pelota. Strech: True
Comprueba pulsando F9 o el botn Run su funcionamiento. Si se bloquea escoge del men: Program
Reset.
Escoge del men: File Save all para guardar el proyecto y su unidad. Escoge tu carpeta de trabajo.
Guarda la unidad con el nombre: toques1.pas y luego guarda el proyecto con el nombre: Toques.pdr
Ejercicio Else If y variables. Adivina un nmero.
Ingredientes:
2 Labels
1 Edit
1 Button
Preparacin:
Creamos 2 variables en la seccin de
variables pblicas: Bueno e Intentos:
var
Form1: TForm1;
Bueno: integer;
Intentos: integer;
Inicializacin:
Al crearse el formulario se genera un nmero aleatorio del 1 al 100 y se guarda en la variable bueno:
procedure TForm1.FormCreate(Sender: TObject);
begin
Randomize; //baraja
bueno:=random(100); //crea un num aleatorio entre 0 y 100 y lo guarda en la variable
bueno
intentos:=0; //pone intentos a cero
end;
Acciones: Al pulsar el botn Vale, se crea una variable num y se evala si la variable num es igual o mayor a
la variable bueno:
procedure TForm1.Button1Click(Sender: TObject);
var
num:integer;
begin
intentos:=intentos+1;
If Edit1.text=' ' then showmessage('Escribe un nmero') // -> si no escriben nada
else
begin
num:=strtoint(Edit1.text); //-> Variable num guarda el dato del Edit1
if num>bueno then showmessage('Es ms bajo')
else if num<bueno then showmessage('Es ms alto')
else if num=bueno then acierto;
Edit1.text:=' '; //-> borra el nm del Edit1
end;
end;
Se crea un procedimiento manual llamado acierto sin parmetros:
procedure Tform1.acierto;
var
i:integer;
begin
Edit1.visible:=false;
Label2.Caption:='Acertaste, es el '+inttostr(bueno);
Label1.Caption:='Te ha costado ' + inttostr(intentos)+' intentos y has tardado '+ inttostr(60-
ProgressBar1.position)+' segundos';
for i:=1 to 100 do // Bucle finito: repite el bucle 100 veces
begin
with TButton.Create(self) do //se autocrea un botn que aparecer aleatoriamente en el form
begin
SetBounds (Random (panel1.Width-100), Random (Panel1.Height-50), 100, 50);
Parent := Panel1;
Caption := Label2.Caption;
end;
end;
Mejoras:
Procedure TForm1.Timer1Timer
Aadir una barra de progreso: progressbar1 begin
(paleta win32) Progressbar: Max: 60 Position: 60 ProgressBar1.Position:=ProgressBar1.Position-1;
Aadir un Temporizador: Timer (paleta system) if ProgressBar1.Position=0 then
begin
Interval: 1000 (Repetir el evento cada 1 segundo)
Showmessage('Se acab el tiempo');
En el evento del timer OnTimer aadir el cdigo de la Timer1.enabled:=false;
derecha para evaluar el tiempo tardado en acertar y close;
decrementar la barra de progreso.Guarda la unidad end;
(Adivina1.pas) y el proyecto (Adivina.DPR) end;
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg15
Ejercicio calculadora. Uso del parmetro sender y de las variables
Creamos un nuevo formulario. File New - Application
Ingredientes: (Componentes)
3 Labels: Valor 1 Valor 2 - Resultado
2 Edits: Edit1 Edit2
4 botones:
Button1: Sumar
Button2: Restar
Button3: Multiplicar
Button4: Dividir
1 Panel: Caption: 0
Acciones:
- Pulsar doble clic en el botn 1 para escribir la accin
dentro del procedure:
panel1.caption:=edit1.text + edit2.text; da error
procedureTForm1.Button5Click(Sender:TObject);
var
resultado:double;
begin
resultado:=strtofloat(edit1.text);
numero1:=resultado1;
whilenumero1>0do
begin
resultado:=resultado*numero1;
numero1:=numero11;
end;
panel1.caption:=floattostr(resultado);
end;
Alfinalizar,guardaesteproyectoentucarpetaconelnombre:CALCULADORA2
procedureTForm1.Button6Click(Sender:TObject);
var
resultado:double;
x,veces:integer;
begin
resultado:=strtofloat(edit1.text);
numero1:=resultado;
veces:=strtoint(edit2.text);
forx:=1tovecesdo
begin
resultado:=resultado*numero1;
end;
panel1.caption:=floattostr(resultado);
end;
Guardaesteproyectoentucarpetaconelnombre:CALCULADORA3
Botonesplanosconimgenes:
Sustituyelosbotonesdeltipobuttonporlosdeltipo
SpeedButtondelapaletaadicional.
PonsupropiedadFlat:True.
Cambiaeltextodelbotnporunaimagen
(propiedadGliph)diseadaportenPaint.
Aadirincrementadoresdevalor:
AadedoscomponentesUpDowndela
paletaWin32ycambialaspropiedadesque
seindicanenlafiguraparaincrementarlos
valoresdeleditconflechas.
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg17
Ejercicio 2. Lanzar un dado en un juego:
En este ejercicio al pulsar el botn Lanzar se activa
el timer y al pulsar el botn Parar desactiva el
timer y muestra el dato del timer. Por lo tanto, el programa
dispondr de tres eventos o acciones:
1. procedure botonLanzarClick(Sender: TObject);
2. procedure botonpararClick(Sender: TObject);
3. procedure Timer1Timer(Sender: TObject);
En los tres procedimientos siguientes, slo tendremos que escribir el texto en negrita El resto se escribe
automticamente al pulsar doble clic en el componente o sobre el evento adecuado del componente (F11)
procedureTMainForm.botonLanzarClick procedureTMainForm.botonpararClick
begin begin
timer1.enabled:=true; timer1.enabled:=false;
end; label1.caption:='hassacadoun'+inttostr(x);
end;
procedureTMainForm.Timer1Timer(Sender:TObject);
{poner interval del timer1 a 50
poner en el var general x: integer}
begin
ifx<6thenx:=x+1elsex:=1;{SiXesmenosque6suma1ysipasade6valdr1}
label1.caption:=inttostr(x); {Ponemosaltextodelaetiquetaelvalordex}
end;
Avanzado:
Utiliza el componente JVCL - JEDI en la paleta: JVVisual: JVDice
con sus propiedades: Autostop Interval: 800 y Rotate true
Ejercicio de Captura y pulsacin de botn de ratn:
Enloseventosdelratn(mouse):
Onmousedown,OnmouseupyOnmouseMove,
losparmetrosXyYsonautomticosynosdevuelvenla
informacindelaposicindelmouse.
Enloseventosdelratn(mouse)OnmousedownyOnmouseup,
tambinexisteelparmetroButtonquenosinformasielbotn
pulsadooliberadoeselizquierdom(mbleft)oelderecho
(mbright).
Crearunproyectonuevollamado:Mouse.dpryaadealformulario,loscomponentesquesemuestranenlafigura.
Conelformularioseleccionado,buscaenpetaaEvents,eleventoonMouseDownypulsadobleclicparacrearel
procedure.
Agregaelcdigosiguiente:
procedureTForm1.FormMouseDown(Sender:TObject;Button:TMouseButton;
Shift:TShiftState;X,Y:Integer);
begin
ifButton=mbLeftthen
begin
label1.Caption:='Izquierdo:'+inttostr(X); //guardaposicinXdelratn
label2.Caption:='Izquierdo:'+inttostr(Y); //guardaposicinYdelratn
end
elseifButton=mbRightthen
begin
label1.Caption:='derecho:'+inttostr(X);
label2.Caption:='derecho:'+inttostr(Y);
end;
end;
Comprueba(RunF9)yguardaelproyectoylaunidadentucarpetaalfinalizar.
Paradetectarcundoelusuariopulsaunatecla,seemplealoseventos:onkeypressyonkeydown(enlapestaaEvents
delObjectInspector)
Enloseventosonkeypressyonkeydown.Losproceduresnos
informan,conlavariablekey,delcdigodelateclapulsada.
Ord(Char)devuelveelvalornumricoASCIIquelecorresponde
uncaracter
Crearunproyectonuevollamado:Tecla.dpryaadeal
formulario,treslabelsconloscaptions(rtulos)quesemuestran
enlafigura:
Conelformularioseleccionado,buscaenpetaaEvents,el
eventoonkeypressypulsadobleclicparaaadirelprocedure.
Agregaelcdigosiguiente:
procedureTForm1.FormKeyPress(Sender:TObject;varKey:Char);
begin
label1.caption:=key;
label2.caption:=IntToStr(Ord(key));//Ord(key)devuelveelnmeroordinaldelateclapulsada(1a256)
ifkey=#27thenclose;//Sipulsanlateckaescapeseterminaelprograma
end;
Comprueba(RunF9)yguardaelproyectoylaunidadentucarpetaalfinalizar.
Variante al ejercicio de la
calculadora: procedureTForm1.FormKeyPress(Sender:TObject;varKey:Char);
var
Capturarlatecladelaoperacinconel num:integer;
teclado: begin
Recuperaelproyectodelacalculadora casekeyof
#13,#61:operarClick(opeigual);{teclasintro}
Asignaalformulariolapropiedad #43:Button1Click(mas);
KeyPreview=True #45:Button1Click(menos);
Aadeelsiguienteprocedureal #42:Button1Click(por);
#47:Button1Click(div);
eleventoOnKeyPressdelformulario end;
Crearunproyectonuevollamado:Tecla_encriptada.dpr,similaral
anteriorperoconlasvariacionesdelaimagen.
AadeelsiguienteprocedurealeleventoOnKeyDowndelformulario:
procedureTForm1.FormKeyDown(Sender:TObject;varKey:Word;
Shift:TShiftState);
var
codigo:byte;//variablenumricade256valores
begin
label2.Caption:=inttostr(key);
if(Key=VK_RETURN)thenLabel2.caption:='HaspulsadoEnter'; VirtualKeysCodes
if(Key=VK_ESCAPE)thenLabel2.caption:='HaspulsadoEsc'; VK_RETURN Enterkey
codigo:=key+spinedit1.Value;
labelEnc1.Caption:=inttostr(codigo); VK_SHIFT Shiftkey
labelEnc2.Caption:=chr(codigo); VK_CONTROL Ctrlkey
end; VK_LBUTTON Leftmouse
VK_RBUTTON Rightmouse
VK_CANCEL Control+Break
VK_BACK Backspacekey
VK_TAB Tabkey
VK_ESCAPE Esckey
VK_UP UpArrowkey
VK_RIGHT RightArrowkey
Encriptacin de caracteres de texto VK_DOWN DownArrowkey
Crearunproyectonuevollamado:Texto_encriptado.dpr,
similaralanteriorperoconlasvariacionesdelaimagen
Aadeelsiguienteprocedurealpulsarelbotn:
procedureTForm1.Button1Click(Sender:TObject);
var
original,encriptado:string; //variablesparaalmacenarlostextos
i:integer; //varnumericaenteraparaelvontadorfor
begin
original:=edit1.Text; //almacenaelvalordeledit1
fori:=1toLength(original)do //lohacelasvecesdelanchodeltexto
encriptado[i]:=chr(ord(original[i])+spinedit1.Value); //conviertedecharanmeroylesumaeldelspin
edit2.Text:=encriptado; //muestraelresultado
end;
Ejercicio 3. Crear un contador de tiempo. Practicar con tipos de variables.
Variables pblicas y privadas: Crearemos dos variables para almacenar dos datos: la hora de inicio y la
hora final. Si estas variables van a ser utilizadas en todo el programa, se crea al principio, en el apartado var
(pblicas), si no se crea el apartado var dentro del procedure (privadas).
ejemplo:
var
Form1:TForm1;
horainicio:double; //noexisteeltipotime,seeligeeltiponumricodoble.Permitedecimalesdobleprecisin
horafin:double;
I: Integer; (numrico entero)
S: string; (identificador del tipo cadena de texto)
otros tipos de variables:
Integer ShortintSmallIntLongint Byte Word
Cardinal BooleanByteBoolWordBoolLongBoolChar
Prctica:
Crear una nueva aplicacin llamada CRONO. Aade al formulario (ventana) los siguientes componentes:
3 botones
3 paneles de color blanco como se muestra en la figura:
Tipodecomponente:TButton
Name:button1
Caption:Empezar
Tipodecomponente:TButton
Name:button2
Caption:Parar
Tipodecomponente:TPanel
Name:Panel2
Caption:Horafin
Tipodecomponente:TPanel
Name:Panel1
Caption:Horainicio
Tipodecomponente:TPanel
Name:Panel3
Tipodecomponente:
Caption:Crono
Tbutton
Name:button3 var
Aadir las siguientes variables al inicio de la unidad: Form1: TForm1;
horainicio: double;
Aadir las lneas de cdigo a los procedures: horafin: double;
procedureTForm1.Button1Click(Sender:TObject);
begin
horainicio:=time; Nivel avanzado
panel1.Caption:='Horadeinicio:'+ Cmo crear un archivo INI que guarde la hora de
TimeToStr(Time); entrada.
end;
- Es necesario aadir INIFILES a la seccin USES
de la unidad.
procedureTForm1.Button2Click(Sender:TObject); procedure TForm1.Button1Click(Sender: TObject);
begin var
horafin:=time; datosini:TIniFile;
panel2.Caption:='Horadeparo:'+TimeToStr(Time); HORAENTRADA:STRING;
panel3.caption:='Crono:'+TimeToStr(horainicio begin
horafin); HORAENTRADA:=TIMETOSTR(TIME);
end; datosini:= TIniFile.Create('DATOS.INI');
-->crea el archivo datos.ini
datosini.WriteString('Eduardo', 'Entrada',
procedureTForm1.Button3Click(Sender:TObject); HORAENTRADA); -->aade a la seccin
begin [Eduardo] entrada=12:15
close; DATOSINI.FREE; --> cierra el archivo datos.ini
end;
end;
Variantes y mejoras: Aade el componente: XPManifest (Win32): permite a los botones tener tema-estilo
visual de Windows XP.
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg21
Ventanas de Mensajes y cuadros de dilogo directos.
Ventanasdemensaje:
ModoDelphi: Showmessage('Mensaje);
MessageDlg(Mensaje',mtInformation,[mbOk],0)
ModoWindows: Application.MessageBox(Mensaje,'Textoventana',MB_OK);
Ventanadepregunta:
Application.MessageBox('Pregunta','Textoventana',MB_YESNO)
MessageDlg(Mensaje',mtConfirmation,[mbYes,mbNo],0)Devuelve:mrYesomrNo
InputBox('Nombre_ventana','Texto_Dato','Respuesta_predeterminada');DevuelveVarString
InputQuery('Identificate!','Pontunombre,porfavor...',Nombre);DevuelveVarBolean
Otrosmensajes:
ShowMessageFmt(constMsg:string;Params:arrayofconst);
CreateMessageDialog(constMsg:string;DlgType:TMsgDlgType;Buttons:TMsgDlgButtons)
Ejercicios-ejemplo: Crea en un formulario nuevo 5 botones y asigna a cada uno de ellos el siguiente cdigo:
procedureTForm1.Button1Click(Sender:TObject);
var
Dato:string;
begin
Dato:=InputBox('Nombreventana','Nombre:','Antonio');
showmessage('Hola,'+Dato);
end;
procedureTForm1.Button2Click(Sender:TObject);
var
Nombre:string;
PulsoOk:boolean;
begin
PulsoOk:=InputQuery('Identificate!','Pontunombre,porfavor...',Nombre);
ifPulsoOk=truethenShowMessage('Envantadodeconocerte,'+Nombre)elseShowMessage('Hasdepulsar
Ok...');
end;
procedureTForm1.Button3Click(Sender:TObject);
begin
if(Application.MessageBox('Erestonto?','Tontera',MB_YESNO)=IDYES)thenshowmessage('Losaba')
elseshowmessage('Respuestaincorrecta')
end;
procedureTForm1.Button4Click(Sender:TObject);
begin
Application.MessageBox('EsteesunmensajeconbotnAceptar','Informacin',MB_OK);
end;
procedureTForm1.Button5Click(Sender:TObject);
var
Nombre:string;
PulsoOk:boolean;
pregunta:pchar;
begin
PulsoOk:=false;
whilePulsoOk=falsedo
begin
PulsoOk:=InputQuery('Identificate!','Pontunombre,porfavor...',Nombre);
ifPulsoOK=falsethenShowMessage('HasdepulsarOk...');
end;
Pregunta:=Pchar('Hoye'+Nombre+',erestonto?');
whileApplication.MessageBox(Pregunta,'Tontera',MB_YESNO)=IDNOdo
begin
MessageDlg('Respuestaincorrecta',mtError,[mbOk],0);
end;
MessageDlg('Respuestacorrecta',mtInformation,[mbOk],0);
end;
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg23
Ejercicio 5. Prcticas con controles de lista y eleccin.
1.- Crear el formulario Helados.frm con
los nombres y controles que se indican en
la figura.
Control:Combobox
Name:Producto Control:ListBox
Name:Sabor
Compo: Panel
Name: Panel1
Compo: Label
Name: Label1
Compo: Image1
Name: Image1
Compo: Bevel
Name: Bevel1
Style:bsLowered
Name: ImageForm
Caption: Visor Componente: Button Componente: CheckBox
Name: Salir Name: StretchCheck
Caption: Salir Checked: False
Caption: Ajustar
Paso2.Escribirloscdigosdeloseventos
Alhacerclicenunaunidaddedisco(Drivecombobox)secambianlosdirectorios(DirectoryListbox)porquelehemos
dichoqueDirlist:DirectoryListBox1,lomismoocurrealcambiardedirectorio,secambialalistadearchivos
(Componente:FileListBox)yenlalistadearchivossloaparecernlosarchivosdeltipoqueseponganenlamscara
(Mask:*.bmp;*.ico;*.wmf).
Lapartemsdifcildecdigoestalhacerclicenunarchivodelalista:
procedureTForm1.FileListBox1Click(Sender:TObject);
var
FileExt:string[4]; {creamoslavariableFileExtqueserdetresletrasmselpunto}
begin
FileExt:=UpperCase(ExtractFileExt(FileListBox1.Filename)); {detectalaextensindelarchivoenmaysc}
if(FileExt='.BMP')or(FileExt='.JPG')or(FileExt='.GIF)or(FileExt='.WMF)then {SiesBMPoJPGoGIF}
begin {empezar}
Image1.Picture.LoadFromFile(FileListBox1.Filename); {Cargaelarchivoenlaimagen}
Label1.Caption:=ExtractFilename(FileListBox1.Filename); {Cambiaeltextodelaetiqueta}
end; {terminar}
end;
CdigoalpulsarelbotndeSalir:(SalirClick): close;
Cdigoalpulsarenajustarimagen(StretchCheck): Image1.Stretch:=StretchCheck.Checked;
Paso3.Ejecutarycomprobar.
PulsaenelbotnRunoenelmen:Run,compruebayyaest.
GuardaelproyectoentucarpetaconelnombreVisor.
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg25
Mejorasalvisordeimgenes
2.UsararchivosINI.
ParagrabaryleerdatosdeconfiguracindelprogramautilizalosTinifiles:
AadirINIFILESalaseccinUSESdelaunidad.
GrabacindelarchivoINI:
procedure onclose
var
datosini:TIniFile;
begin
datosini:=TIniFile.Create('DATOS.INI');//>creaelarchivodatos.ini
datosini.WriteInteger('Formato','Posicionizquierda',form1.left);
datosini.WriteString('Formato','nombre',form1.caption);//guardadatodeltipotextostring
DATOSINI.FREE;>cierraelarchivodatos.ini
end;
LecturadelarchivoINI:
Procedureoncreate
var
datosini:TIniFile;
begin
datosini:=TIniFile.Create('DATOS.INI');form1.left:=datosini.readinteger('Formato','Posicionizquierda',100);
Ejemplo. Como grabar y leer todos los caption del formulario segn el idioma escogido:
Buscaremos todos los componentes de nuestro formulario usando la clase: TCOMPONENT que me
devuelve el nombre del componente segn el nmero de rden de creacin en el formulario. Por lo tanto:
Components[3] es una variable array o matriz (conjunto de variables ordenadas) que me devuelve el
nombre del componente nmero 3
Component is TLABEL: Evalua si el componete es de la clase o tipo Tlabel
{Alcargarelformularioleeelarchivodeidioma.lngquelehadichoenelarchivodatosiniyque
anteslohaguardadoelusuarioalcambiarlaconfiguracindeidiomaenelarchivoDatos.ini}
var
Ini:TIniFile;
component:tcomponent;
i:integer;
dire:string;
begin
Dire:=Application.GetNamePath;
Ini:=TIniFile.Create(dire+'\langs\'+Configidioma+'.lng');//direeslarutapordefecto
//>Rutaparaios:TIniFile.Create(GetHomePath+PathDelim+'Documents'+PathDelim+'ex.ini');
fori:=0toComponentCount1do//>Agrupaporcomponenteseccion[CAPTIONS]
begin
Component:=Components[i];
if(ComponentisTLABEL)and((ComponentasTLABEL).Caption<>'')then(componentas
TLABEL).Caption:=Ini.ReadString('CAPTIONS',(componentasTLABEL).name,(componentas
TLABEL).Caption)
end;
end;
Ejercicio 6 . Reproductor multimedia
Componente:Opendialog
Paleta:Dialogs
Name:Abrirdialogo
Filter:AVI|*.avi|WAV|*.wav|MIDI|*.mid
Componente: Mainmenu
Paleta: Standard
Componente: Mediaplayer Name: MainMenu1
Name: Player Carpeta: System
Display: VideoPanel
AuotoOpen: False
Componente: Panel
Name: Videopanel Formulario
Name:Form1
Caption:Reproductormultimedia
Evento: Abrir1click
Ejerciciopropuesto1:AadealproyectoVisordeimgenes,delejercicioanterior,laposibilidaddeverarchivosde
vdeoymsicaademsdeimgenes;aadiendoelcomponentemediaplayer.
Ejerciciopropuesto2:SitienesinstaladaslaslibrerasgratuitasJVCL.Puedescrearuncapturadordevdeofcilmente
conelcomponente:JvAVICapture1(Paleta:JVimages,animators).
Ejercicico 7 Dibujar: Controles de los botones del mouse y variable Flag
Creamos una variable de estado lgica y
Name:Form1 pblica(Tipo Flag o permiso) llamada Pinta:
Eventos: public
Onmousedown:FormMouseDown var
Onmouseup:FormMouseUp ColorDialog1
Form1: TForm1;
OnmouseMove:FormMouseMove Pinta: Boolean;
procedureTForm1.FormMouseDown
begin
Pinta := True; // Permiso para pintar
Canvas.MoveTo(X, Y); //Fija el origen
Panel1 end;
Button1 Button2
procedureTForm1.FormMouseUp
begin
Pinta := False; //Quita permiso para pintar
end;
procedureTForm1.FormMouseMove(Sender:TObject;Shift:TShiftState;X,Y:Integer);
begin
If Pinta=True then Canvas.LineTo(X, Y); // Si la variable Pinta es True entonces linea desde el CP al puntoXY
end;
procedureTForm1.Button1Click
begin
If Colordialog1.execute then Form1.Canvas.Pen.Color := colordialog1.color; //Abre ventana color y asigna
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg27
EjercicioArrastrarysoltar.Propiedadesdelosformulariosydelmouse.
1. Crear un proyecto nuevo llamado: CARAS.DPR. Aadir al formulario los ingredientes que se muestran:
var
Form1: TForm1;
Live : TBitmap;
implementation
{$R *.DFM}
{$R extrares.res} // <- aqu se incluye el recurso
Variantes y mejoras:
Esteprotectordepantallapuedeconvertirseenunjuegodehabilidad(mezcladoconelanterior)sialpulsardobleclic
sobreelobjeto(quepuedeserunaimagen)cuentalosgolpesyasuvezseaceleraelobjeto.
Animacin. (Juego Ping)
var b:=1;
Form1:TForm1; end;
p1x,p1y,p2x,p2y,p3x,p3y:real;//posic.delos
recuadros if((trunc(p1y)<trunc(p2y)rectangle1.Height))
b:byte; and((trunc(p1y)>trunc(p2y)rectangle1.Height
modowin:boolean; 5))and(p1x>p2xrectangle1.Width/1.3)and(p1x<
mx,my:integer;//posic.delmouse p2x+(rectangle2.Widthrectangle1.Width)+
rectangle1.Width/1.3)then
procedureTForm1.ButtonPausaClick(Sender:TObject); begin
begin ifb=0then//sihaycolisinconsegundapala
Timer1.Enabled:=False; bajando....puntua
Timer2.Enabled:=False; begin
Timer3.Enabled:=False; label4.Text:=inttostr(strtoint(label4.text)+1);
Timer4.Enabled:=False; end;
buttonSalir.Visible:=True; b:=1;
buttonIniciar.Visible:=True; end;
end;
ifp1y>form1.Heightthen//tocafondopierde
procedureTForm1.ButtonIniciarClick(Sender:TObject); begin
begin b:=1;//poneenmodosubir
Timer1.Enabled:=True; p1y:=form1.Height63;
Timer2.Enabled:=True; p1x:=form1.Width/2;
Timer3.Enabled:=True; ifstrtoint(label4.Text)>strtoint(label2.Text)
Timer4.Enabled:=True; then
buttonSalir.Visible:=False; label2.Text:=label4.Text;//fijalamxima
buttonIniciar.Visible:=False; puntuacinyponepuntosacero.
{$IFDEFMSWINDOWS} label4.Text:='0';
modowin:=true;//sieswindows end;
{$ELSE}
modowin:=false;//sinoeswindows ifb=1then//siestaenmodosubir
{$ENDIF} begin
p1y:=p1y5;//restaposicinvertical
end; ifmodowin=falsethen//siestajugandoenandroid
controlaconelsensor
procedureTForm1.FormCreate(Sender:TObject); begin
begin if(rectangle1.Position.X+20*
Timer1.Enabled:=False; motionsensor1.Sensor.AccelerationY<form1.Width)and
Timer2.Enabled:=False; (rectangle1.Position.X+20*
Timer3.Enabled:=False; motionsensor1.Sensor.AccelerationY>0)then
Timer4.Enabled:=False; p1x:=rectangle1.Position.X+20*
p1x:=form1.Width/2;//situaalcentroinferior motionsensor1.Sensor.AccelerationY;
p1y:=form1.Height20; end
end; else//siestajugandoenwindows
begin
procedureTForm1.FormMouseMove if(mxp1x)>Rectangle1.Widththenp1x:=
begin rectangle1.Position.X+5//mousealaderecha
mx:=round(x); elseif(mxp1x)<5thenp1x:=
my:=round(y); rectangle1.Position.X5;////mousealaizda
end; end;
end;
procedureTForm1.Timer1Timer(Sender:TObject);
begin ifb=0then//siestaenmodobajar
rectangle1.Position.X:=p1x;//muevelosobjetos begin
rectangle1.Position.Y:=p1Y; p1y:=p1y+5;//sumaposicinvertical
rectangle2.Position.X:=p2X; ifmodowin=falsethen
rectangle2.Position.Y:=P2Y; begin
rectangle3.Position.X:=p3X; if(rectangle1.Position.X+20*
rectangle3.Position.Y:=P3Y; motionsensor1.Sensor.AccelerationY<form1.Width)and
Application.ProcessMessages;//procesaperoesperaa (rectangle1.Position.X+20*
queseacabelatareaanterior motionsensor1.Sensor.AccelerationY>0)then
end; p1x:=rectangle1.Position.X+20*
motionsensor1.Sensor.AccelerationY;
procedureTForm1.Timer2Timer(Sender:TObject); end
var else//siestajugandoenwindows
a:integer; begin
begin if(mxp1x)>Rectangle1.Widththenp1x:=
ifp1y<0then rectangle1.Position.X+5//mousealaderecha
begin elseif(mxp1x)<5thenp1x:=
b:=0;//modobajar rectangle1.Position.X5;////mousealaizda
p1y:=p1y+15; end;
end; end;
if((trunc(p1y)<trunc(p3y)rectangle1.Height)) end;
and((trunc(p1y)>trunc(p3y)rectangle1.Height
5))and(p1x>p3xrectangle1.Width/1.3)and(p1x< procedureTForm1.Timer3Timer(Sender:TObject);//mueve
p3x+(rectangle3.Widthrectangle1.Width)+ lapala1aleatoriamente
rectangle1.Width/1.3)then begin
begin p2y:=form1.Height/1.3;
ifb=0then//sihaycolisinconprimerapala p2x:=rectangle2.Position.X10;
bajando....puntua ifrectangle2.Position.X<150then
begin begin
label4.Text:=inttostr(strtoint(label4.text)+1); p2x:=form1.Width;
end; timer3.Interval:=Random(150)+10;
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg31
end;
end;
procedureTForm1.Timer4Timer(Sender:TObject);//mueve
lapala2aleatoriamente
begin
p3y:=form1.Height/1.3;
p3x:=rectangle3.Position.X+10;
ifrectangle3.Position.X>form1.Width+150then
begin
p3x:=150;
timer4.Interval:=Random(150)+10;
end;
end;
Delphi.Ejercicio5.Movimientosycontadores.Juego
Comp:Panel
Name:Panel1
Color:Azul
Onclick:flecha1Click Comp:Label
Name:Label1
Caption: Enciende la luz
Comp:Image
Name:Flecha1
Picture:Arrow1r.bmp
Onclick:flecha1Click
Comp:Image
Comp:Timer Name:Bombilla
Name:Timer1 Picture:
Interval:10 Images\buttons\bulboff.bmp
OnTimer:Timer1Timer
BitBtn1
Comp:Image
Name:Bombilla1
PictureImages\buttons\bulboff.bmp
Comp:Timer
Name:Timer2 Comp:Image
Interval:10 Name:Bombilla2
OnTimer: Picture:\Images\buttons\
Comp:Label Timer2Timer
Name:Label2
Caption:0 Comp:Panel3 Comp:Panel2
taRightJustify Align:alLeft Align:alBottom
Bevelouter:bvLowered
Caption:Aciertos
Preparacin: Alignment:taLeftJustify
var
MainForm: TMainForm;
subir:integer; // => Variable pblica para controlar el sentido subir ser numrica entera
Acciones:
El timer1 se encarga de desplazar la flecha hacia la derecha y comprueba si su posicin est cerca de
la bombilla:
procedure TMainForm.Timer1Timer(Sender: Tobject); {solo funciona si el timer1 est activado}
begin
if (flecha1.left=460{bombilla.left})and (flecha1.top<bombilla.top+10) and (flecha1.top>bombilla.top-10)
then
begin
bombilla.picture:=bombilla2.picture; {si flecha toca bombilla cambia picture a bombilla2}
puntos.caption:=inttostr(strtoint(puntos.caption)+1); {suma un punto y convierte en cadena}
end;
if flecha1.left<500 then
flecha1.left:=flecha1.left+5 {avanza de izquierda a derecha 5 pixels a cada pulso del timer}
else
begin
timer1.enabled:=false; {descativa el temporizador timer1}
flecha1.left:=10; {si la flecha pasa de largo empieza de nuevo en posic. izquierda a 10}
end
end;
Ofimegaacadmies ManualEjerciciosProgramacinRadStudioDelphi Impago16 Pg33
El timer2 se encarga de desplazar arriba y abajo la bombilla, (segn si la variable subir est a 0 o 1):
procedureTMainForm.Timer2Timer(Sender:TObject);
begin
ifsubir=0then {sinoestactivadosubir}
begin
ifbombilla.top<200then {sinopasade200deprofundidadquesigabajando}
begin
bombilla.top:=bombilla.top+1;
bombilla.picture:=bombilla1.picture;{porsiestencendida,queseapage}
end
else {sipasade200defondo...}
subir:=1 {queseactivesubir}
end
else {siestactivadasubir..}
begin
ifbombilla.top>0then {ysiannoestarriba...}
bombilla.top:=bombilla.top1 {quesigasubiendo}
else {siyahallegadoarriba...}
subir:=0 {quesedescativesubir}
end
end;
Al empezar el programa, la variable subir debe de valer algo (cero por ejemplo)
procedureTMainForm.FormCreate(Sender:TObject);
begin
subir:=0; {empiezaconsubirdesactivado}
end;
Al hacer clic sobre la flecha se activa el timer (o tambin se puede hacer sobre un botn)
procedureTMainForm.flecha1Click(Sender:TObject);
begin
timer1.enabled:=true; {alhacerclicconelratnqueseactiveeltimer1}
end;
Variantes y mejoras:
Conexin a Internet.
1.- Crea un botn que nos conecte con la pgina web de soporte del programa:
Aade la siguiente lnea de cdigo:
Panel1
Name:Empezar
Name:Inicio
Name: Salir
Name:Parar Shape1
stCircle
Timer1
Pamel2.Bottom Interval=50
Panel3.Bottom
Shape2
Tscrollbar
Label1 Componente: vertical
Tbiagauge Name:Barrav
Name:Nivelh Max:10
Min:10
Tscrollbar
Horizontal
Name:Barrah
progressbar progressbar
Name:Nivelvynivelh Name:Energa
MaxMin:+1010 0100
Procedures:
Variantes:
El fondo de la ventana ser de color negro y se aadirn shapes de estrellas blancas
El objeto ser el dibujo de una nave en un picture box.
(En el programa esqueleto el objeto es un shape de forma circular.)
Se aadirn asteroides que resten puntos y/o desven la nave de su ruta.
Finalizar el juego al coincidir el objeto con las coordenadas de la base lunar.
Puedes sustituir las barras de direccin por botones Updown de la paleta Win32 o
sustituirlos por ArcDial y TrackBar el en Firemonkey
Varianteparaquenosesalgalanavedeloslmitesdelaventanaaincluirenelprocedimientodeltimer:
IfShape1.Left<0thenShape1.Left:=299;
IfShape1.Left>300thenShape1.Left:=1;>Idemparacontrolarribayabajoconlapropiedadtop
Notas:
Hemos creado un procedimiento independiente para comprobar si se sale del borde, por lo tanto hay que
declararlo en la lista de declaracin de procedures: procedure ComprobarBordes();
La accin para el evento ScrollHChange es la misma que para ScrollVChange
La accin para el evento DialHChange es la misma que para DialVChange
Ingredientes
1textomemo(memo1)
1cuadroabrir(opendialog1)
1cuadroguardar(savedialog1)
1menu(mainmenu1)
procedureTForm1.Nuevo1Click(Sender:TObject); procedureTForm1.Salir1Click(Sender:TObject);
begin begin
Memo1.Clear; Close;
OpenDialog1.Filename:=''; end;
Caption:='TextDemo[Untitled]';
end; procedureTForm1.FormCloseQuery(Sender:TObject;var
CanClose:Boolean);
procedureTForm1.Abrir1Click(Sender:TObject); var
begin MsgResult:Word;
withOpenDialog1do begin
ifExecutethen ifMemo1.Modifiedthen
begin MsgResult:=MessageDlg(Format('Archivo%s
Memo1.Lines.LoadFromFile(FileName); modificado.Guardar?',
Caption:='TextDemo'+ExtractFilename(FileName); [OpenDialog1.Filename]),mtWarning,mbYesNoCancel,
end; 0);
end; caseMsgResultof
mrYes:
procedureTForm1.Guardar1Click(Sender:TObject); begin
begin Guardarcomo1Click(Sender);
ifOpenDialog1.Filename<>''then CanClose:=True;
begin end;
Memo1.Lines.SaveToFile(OpenDialog1.Filename); mrNo:CanClose:=True;
end mrCancel:CanClose:=False;
elseGuardarcomo1Click(Sender); end;
end;
procedureTForm1.Guardarcomo1Click(Sender:TObject);
begin
withSaveDialog1do
ifExecutethen
begin
Memo1.Lines.SaveToFile(Filename);
Caption:='TextDemo'+ExtractFilename(FileName);
OpenDialog1.Filename:=Filename;
end;
end;
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg37
Enambosobjetos,cambiarlapropiedadfilter,parapoderespecificaretipode
documentoalabriroguardar,comoenlafiguraylaspropiedades:Filterindex:3
DefaultExt:*.rtf
Otrasacciones:
AccionesCortar,copiarypegar:Estasaccionesfuncionansincdigoescritoporqueestsasociadasaunacombinacin
deltecladoquesedesignaenlapropiedad:ShortCut:Ctrl+X,Ctrl+CyCtrl+V.
AccinNuevo:FileNew1FileNew1Execute:aadeelcdigo:RichEdit1.Lines.Clear();
AcccinSalir:FileExit1FileExit1Execute.Compruebaelcdigo:Close();Application.Terminate();
AcccinAcrecade(Crditos):HelpAbout1HelpAbout1Execute.Compruebaelcdigo:
AboutBox>ShowModal();
Problemasymejoras:
Nombredearchivoalguardar:
AlescogerGuardarlaaplicacinnonosdeberasolicitarelnombresiyasehaguardadoorecuperadoantes:
Creamosunavariablepblicaqueguardarelnombredelarchivo:nombrearchivo: String ;
CambiamoselcdigodelprocedimientoFileSave1Execute:
ifSender=FileSave1then
begin
ifnombrearchivo!=''thenRichEdit1.Lines.SaveToFile(nombrearchivo);
RichEdit1.Modified:=False;
end
else
ifSaveDialog.Execute()then
begin
RichEdit1.Lines.SaveToFile(SaveDialog.FileName);
Nombrearchivo:=SaveDialog.FileName;
end;
AadimoselcdigoalAbrir:nombrearchivo:=OpenDialog.FileName;
Preguntaralcerraronuevo:
Tantosicreamosunarchivonuevoosalimosdelprograma,laaplicacinnosdeberapeguntarsideseamosconservaro
guardareldocumentoeditado.ParaelloutilizamoslapropiedadModifieddelcomponenteRichedit.
FileNew1Execute
begin
if RichEdit1.Modified=True then
if MessageDlg("Guardar documento anterior?",
mtInformation, TMsgDlgButtons() << mbYes << mbNo << mbCancel, 0)= mrYes) then
FileSave1Execute(Sender);
end
RichEdit1.Lines.Clear();
RichEdit1.Modified:=False;
end
AlcerrarelformularioocurreanteseleventoFormCloseQuerydondeseconsultaantesdecerrarlavariableCanClose:
FormCloseQuery(Sender, CanClose)
{
if (RichEdit1.Modified=True) then
if (MessageDlg("Guardar documento?", mtInformation, TMsgDlgButtons() << mbYes << mbNo << mbCancel, 0)= mrYes)
then FileSave1Execute(Sender);
CanClose:=True;
end
Imprimir:
AadeunobjetoPrintDialog1delapaletaDialogs.
AadeunanuevaaccinalalistaActionList1paraimprimir,conlas
propiedadesdelaimagenalqueleaadiremoslasiguienteaccinenel
eventoOnExecute:
if PrintDialog1.Execute() then RichEdit1.Print(nombrearchivo);
AadeunelementoenlaseccinfiledelMainMenuyunnuevobotnenlaToolBar1demodoquesuaccinActionse
vinculea:Print.
ParagenerarlaaccinConfigurarImpresora,puedescrearunaStandardActiondeltipo:FilePrintSetup.Luegopuedes
aadirelelementoenelmenparaabrirelcuadrodedilogo:Configurarimpresora:
Ejecutayprueba(Run).Sitodoescorrecto,Guardatodo(FileSaveAll):Unit:Editor1Proyecto:Editor
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg39
Ejercicio de aplicacin Delphi. Procesador de textos. Ventanas madre e hija
Una ventana Madre (MDI) contendr varias ventanas hijas (Child). Esta es la ventana Madre:
Mainmenu1
GroupIndex:0
OpenFileDialog
Ventana:
Name:Madre (GroupIndex:9)
FormStyle:fsMDIForm Cascada:Cascade;
Mosaico:Tile;
Salir:(GroupIndex:9)
Organizariconos:
ArrangeIcons;
AquaparecelaventanaHija:
Archivo:(GroupIndex:0)Mismoquemadre
Editar:(GroupIndex:1)
Texto:(GroupIndex:1)
Aqu estn los procedures de la ventana Hija:
procedureTHija.SetFont procedureTHija.AlinearClick
begin begin
FontDialog1.Font:=Memo1.Font; Left1.Checked:=False;
ifFontDialog1.Executethen Right1.Checked:=False;
Memo1.Font:=FontDialog1.Font; Center1.Checked:=False;
SetEditRect; withSenderasTMenuItemdoChecked:=True;
end; withMemo1do
ifLeft1.Checkedthen
Alignment:=taLeftJustify procedureTHija.Abrir1Click
procedureTHija.Open(constAFilename: begin
string); elseifRight1.Checkedthen
Alignment:=taRightJustify madre.Abri1(Sender);
begin end;
Filename:=AFilename; elseifCenter1.Checkedthen
Alignment:=taCenter;
Memo1.Lines.LoadFromFile(FileName); procedureHija.Salir1Click;
Memo1.SelStart:=0; end;
begin
Caption:=ExtractFileName(FileName); madre.Salir1Click(Sender);
Position:=poScreenCenter; end;
Memo1.Modified:=False;
end;
procedureTHija.FormClose(alcerrarlaventanahija)
begin
procedureTHija.Imprimir1Click; Action:=caFree;(paraquepuedasercerradaporlamadre)
var end;
ifPrintDialog.Executethen
memo1.Print(FileName); procedureTHija.FormCloseQuery(accinantesdecerrar)
end; var
DialogValue:Integer;
procedureTHija.Impresora1Click(Sender:TObject); FName:string;
begin begin
PrinterSetupDialog1.Execute; ifMemo1.Modifiedthen
end; begin
Confirma.showmodal;>Muestraventanaconfirma
ProcedureGuardar FName:=Caption;
if(Filename='')orIsReadOnly(Filename)then Confirma.Label2.Caption:='Grabar'+Fname;
GuardarcomoClick(Sender) caseConfirma.Modalresultof
else mrOK:Save1Click(Self);
begin mrCancel:CanClose:=False;
Memo1.Lines.SaveToFile(Filename); end;
Memo1.Modified:=False; end;
procedureTHija.Guardarcomo1Click(Sender:TObject); end;
begin
SaveFileDialog.Filename:=Filename;
ifSaveFileDialog.Executethen
procedureTHija.Nuevo1Click
begin
begin
Filename:=SaveFileDialog.Filename;
Modifica.Caption:='Otrodocumentonuevo';
Caption:=ExtractFileName(Filename);
madre.Nuevo(Sender);
Modifica.Caption:='';{retiramensaje}
end;
Save1Click(Sender);
end;
procedureTHija.Cerrar1Click
end;
begin
procedureTHija.Save1Click(Sender:TObject);
Close;
begin
end;
ifPathName=DefaultFileNamethen
Guardarcomo1Click(Sender)
else procedureTHija.NegritaClick(Sender:TObject);
begin begin
Editor.Lines.SaveToFile(PathName); ifNegrita.DownthenMEMO1.Font.Style:=MEMO1.Font.Style
Editor.Modified:=False; +[fsBold]
end; elseMEMO1.Font.Style:=MEMO1.Font.Style[fsBold];
end; end;
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg41
ActionListyActionManager:ProcesadordetextosutilizandoelcomponenteActionList
Escoge:ArchivoNuevoproyectoVCL(oVCLFormsapplication)
Cambialapropiedad:Form1.caption=Editordetextos
Aadircomponentesalformulario:
AadiremosuncomponenteRichEditdelapaletawin32.
Unavezsobreelformulariocambiarlapropiedadalignaclient.
PulsadobleclicenelcomponeteStatusBardelapaletawin32yeste
seaadirabajodelformulariocomobarradeestado.
Paracrearunpanelenlabarradeestado:
EnlapropiedadSimpleText>escribir:Sinttulo.txt.
EnlapropiedadPanelsabrirelcuadrodePanels
ClicenelbotnNewparaaadirunpanelalabarradeestado
statusbar1.Cierraelcuadro.
Aadirmenybarradeherramientas:
Delapaletaestandarescogeelcomponente:Mainmen1
DelapaletaWin32escogeelcomponente:ToolBar
AgruparaccionesmedianteActionlist:
ParaagruparlasaccionesdelmenydelabarradeherramientasDelphiproporcionaunactionmanagerpara
centralizaramboscdigoseimgenes.
Enlapaletaadicional,hagadobleclicenelcomponente:ActionManageroenlapaletaestandar:actionlist.Paraaadirlo
alformulario.Comoesuncomponentenovisual,sepuedeponerencualquiersitio.
Paraverloscaptionsdecomponetesnovisualesescoga:ToolsEnvironmentOptions,clicenDesignerpage,y
seleccionar:Showcomponentcaptions,OK..
Menu Comando Herramientas? Descripcin
Archivo Nuevo S Createsanewfile.
Archivo Abrir S Opensanexistingfileforediting.
Archivo Guardar S Savesthecurrentfiletodisk.
Archivo Guardar No Savesafileusinganewname(alsoletsyousaveanew
como fileusingaspecifiedname).
Archivo Salir S Quitstheeditorprogram.
Edicin Cortar S Deletestextandstoresitintheclipboard.
Edicin Copiar S Copiestextandstoresitintheclipboard.
Edicin Pegar S Insertstextfromtheclipboard.
Ayuda Contenido No DisplaystheHelpcontentsscreenfromwhichyoucan
accessHelptopics.
Ayuda Indice No DisplaystheHelpindexscreen.
Ayuda Acerca.. No Displaysinformationabouttheapplicationinabox.
DobleclicenActionlistparaabrirlo
EnEditingForm1.ActionManager1pulsarelbotn:NewAction.Ensus
propiedadesescribir:
Caption=&New
Category=Archivo
Hint=Creaunarchivonuevo
ImageIndex=6(imagen6deImageList)
Name=FileNew
Pulsarelbotn:NewAction.Ensuspropiedadesescribir:
Caption=&Guardar Variante:ActionManager
Category=Archivo
Hint=Guardaelarchivo SimilaraActionlist,tenemoselcomponente:
ImageIndex=8(imagen8deImageList) ActionManagerenlapaletaAdicional.Vaen
Name=FileSave combinacinconActionmainmenyActiontoolbar.
Pulsarelbotn:NewAction.Ensuspropiedadesescribir: PermitelaaparienciaOfficeXPypermite
Caption=&Indice personalizarlasbarrasdeherramientasyelmen
Category=Ayuda entiemporeal,conelcomponete:CustomizeDlg.
Hint=Indiceayuda
Name=HelpIndex
Pulsarelbotn:NewAction.Ensuspropiedadesescribir:
Caption=&Acerca
Category=Ayuda
Hint=AcercadeName=HelpAbout
Aadiraccionesestandaralacionlist(open,saveas,exit,cut,copy,paste,help)
Pulsarelbotnderechodelmouseaescogerdelmen
contextual:aadirNewestndarAction:Aadirlasacciones:
TEditCut,TEditCopy,yTEditPaste.SecrearlacategoraEdit
EnlacategoraarchivooFileaade:TFileOpen,TFileSaveAs,
andTFileExit.
EnlacategoraHelpaadeTHelpContents.
Guardaelproyecto:FileSaveAll
Aadirimagenesalimagelist
Truco:Abreelarcivo(Archivoabrir):C:\Archivosdeprograma\Borland\DelphiX\Source\Vcl\ActnRes.pas.
Apareceunejemploconlasimgenesestndaryalistas.
TambinpuedesPulsarAddybuscarlasimgenesen:C:\Archivosdeprograma\Archivoscomunes\Borland
Shared\Images\Buttons
Edit|Cut 0
Edit|Copy 1
Edit|Paste 2
File|New 6
File|Open 7
File|Save 8
File|SaveAs 30
File|Exit 43
Help|Contents 40
Aadirunmen:
Delapaletaestandarescogeelcomponente:Mainmen1ypulsa
dobleclic,paraaadirloalformulario.
Pulsaluegodobleclicsobreelcomponentedelformulariomainmenu1
paraeditarlo.
Enlapropiedad:imagelistescoge:imagelist1
Puedesusarelbotnderechodelmousesobreelmenparaaadir
elementosalmendesdelaplantilla:Insertfromtemplate.Oaadir
loselementosmanualmenteusandoelbotnderechodelmouse
sobreelmenyescogerInsert.
Aadirunabarradeherramientas:
- DelapaletaWin32escogeelcomponente:ToolBarypulsadobleclic,paraaadirloalformulario.
- Enlapropiedad:imagelistescoge:imagelist1
- Pulsaelbotnderechodelmouseparaaadirbotones
alabarradeherramientas
- EnlapropiedaddecadabotndeAction:Buscala
actionlistdeseada.
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg43
Cdigos de ejemplo tpicos de eventos en Procesadores de texto y ventanas madre-hija:
Trabajarconventanas Abrirventanahija.
procedureTFrameForm.OpenChild(Sender:TObject);
var
Salir.Cerrarventana.
EditForm:TEditForm;
begin
begin
Close;
ifOpenFileDialog.Executethen
end;
begin
Preguntaparacerrar.
EditForm:=TEditForm.Create(Self);
procedureTForm1.FormClose(Sender:TObject;var
EditForm.Open(OpenFileDialog.Filename);
Action:TCloseAction);
EditForm.Show;
begin
end;
ifMessageDlg('Salirdelprograma?',
end;
mtConfirmation,
[mbYes,mbNo],0)=mrYesthen
Action:=caFree Trabajarcontextos
else
Action:=caNone; Abrirtextoenuncomponentememo.
end; procedureTForm1.FileOpenClick(Sender:TObject);
Eventoalcerrarhija(onclose) begin
procedureTHija.FormClose(Sender:TObject;var withOpenDialog1do
Action:TCloseAction); ifExecutethen
begin begin
Action:=caFree;//CloseActionPermitido Memo1.Lines.LoadFromFile(FileName);
end; Caption:='TextDemo'+
AbrirventanaAcercade...AboutClick ExtractFilename(FileName);
begin end;
AboutBox.ShowModal; end;
end; Guardartextomemo.
Ponernombredelarchivoaunaventana. procedureTForm1.Save1Click(Sender:TObject);
Ventana.Caption:=ExtractFileName(FileName); begin
Ventanamosaico. ifOpenDialog1.Filename<>''then
procedureTFrameForm.Tile1Click(Sender:TObject); begin
begin Memo1.Lines.SaveToFile(OpenDialog1.Filename);
Tile; end
end; elseSaveAs1Click(Sender);
Ventanacascada. end;
procedureTFrameForm.Cascade1Click(Sender: Guardarcomo...textomemo.
TObject); procedureTForm1.SaveAs1Click(Sender:TObject);
begin begin
Cascade; withSaveDialog1do
end; ifExecutethen
Ventanaorganizar. begin
procedureTFrameForm.ArrangeIcons1Click(Sender: Memo1.Lines.SaveToFile(Filename);
TObject); Caption:='TextDemo'+
begin ExtractFilename(FileName);
ArrangeIcons; OpenDialog1.Filename:=Filename;
end; end;
Nuevaventanahija.(desdelamadre) end;
procedureTPrincipal.Nuevo1Click(Sender:TObject); DilogoBuscartexto.
var procedureTForm1.Find(Sender:TObject);
Hija:THija; begin
begin withSenderasTFindDialogdo
Hija:=THija.Create(Application); ifnotSearchMemo(Memo1,FindText,Options)
Hija.Show; then
end; ShowMessage('Cannotfind"'+FindText+'".');
Nuevaventanahija.(desdelahija) end;
procedureTHijaNew1Click(Sender:TObject); DilogoReemplazartexto.
begin var
Ventana.Caption:='nuevo';{retiramensaje} Found:Boolean;
PrincipalForm.Nuevo1Click(Sender); begin
end; withReplaceDialog1do
begin ConfirmChange(Caption,FromFileName.Text,
ifAnsiCompareText(Memo1.SelText,FindText)=0 ToFileName.Text);
then end;
Memo1.SelText:=ReplaceText; end;
Found:=SearchMemo(Memo1,FindText,Options); Borrararchivos.
whileFoundand(frReplaceAllinOptions)do procedureTFMForm.Delete1Click(Sender:TObject);
begin begin
withFileListdo
ifMessageDlg('Delete'+FileName+'?',
mtConfirmation,
Trabajarconarchivos. [mbYes,mbNo],0)=idYesthen
ifDeleteFile(FileName)thenUpdate;
Detectardirectorio. end;
procedureTFMForm.DirectoryOutlineChange(Sender:
TObject); Llamadasaprocedimientos
begin
FileList.Directory:=DirectoryOutline.Directory; Enelmen:ArchivoMoveryCopiarllamanal
DirectoryPanel.Caption:= mismoeventoFilechange
DirectoryOutline.Directory;
end; procedureTFMForm.FileChange(Sender:TObject);
Detectarlistadearchivos. begin
procedureTFMForm.FileListChange(Sender:TObject); withChangeDlgdo
var begin
TheFileName:string; ifSender=Move1thenCaption:='Mover'
begin elseif(Sender=Copy1)or(Sender=copiara)or
withFileListdo (Sender=Copiara1)thenCaption:='Copiar'
begin elseifSender=Rename1thenCaption:=
ifItemIndex>=0then 'Renombrar'
begin elseExit;
TheFileName:=FileName; CurrentDir.Caption:=Statusbar.panels[2].text;
FilePanel.Caption:=Format('%s,%dbytes', FromFileName.Text:=FileList.FileName;
[TheFileName,GetFileSize(TheFileName)]); ToFileName.Text:='';
end if(ShowModal<>mrCancel)and(ToFileName.Text
elseFilePanel.Caption:=''; <>'')thenConfirmChange(Caption,
end; FromFileName.Text,ToFileName.Text);
end; {Llamaalprocedimientoconfirmchangepasandole
Ejecutararchivo. tresvariablesdetexto}
procedureTFMForm.Open1Click(Sender:TObject); end;
begin end;
withFileListdo
ExecuteFile(FileName,'',Directory,SW_SHOW); ProcedureTFMForm.ConfirmChange(constACaption,
end; FromFile,ToFile:string);
begin
Copiar,renombrar,moverarchivos. ifMessageDlg(Format('%s%sto%s?',[ACaption,
procedureTFMForm.FileChange(Sender:TObject); FromFile,ToFile]),
begin mtConfirmation,[mbYes,mbNo],0)=mrYesthen
withChangeFormdo begin
begin ifACaption='Mover'then
ifSender=Move1thenCaption:='Move' MoveFile(FromFile,ToFile)
elseifSender=Copy1thenCaption:='Copy' elseifACaption='Copiar'then
elseifSender=Rename1thenCaption:='Rename' CopyFile(FromFile,ToFile)
elseExit; elseifACaption='Renombrar'then
CurrentDir.Caption:=FileList.Directory; RenameFile(FromFile,ToFile);
FromFileName.Text:=FileList.FileName; FileList.Update;
ToFileName.Text:=''; end;
if(ShowModal<>idCancel)and(ToFileName.Text end;
<>'')then
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg45
Ejercicio de controles.
Dirlistbox
Name:Dir1
Filelistbox
Name:File1
Image
Name:Open
Label:Label1
Command1Salir
Name:Command1
Caption:&Salir PrivateSubForm_Load()
Drive1.Drive=App.Path
Dir1.Path=App.Path
EndSub
PrivateSubFile1_DblClick()
'en(C:\),Pathtieneunabarra(\)alfinal
'encualquierotronivel,nohaybarra(\)final.
IfRight(file1.Path,1)<>"\"Then PrivateSubDrive1_Change()
label1.Caption=file1.Path&"\"&file1.filename Dir1.Path=Drive1.Drive
Else Drivelistbox
EndSub
PrivateSubDir1_Change()
label1.Caption=file1.Path&file1.filename Name:Drive1
EndIf file1.Path=Dir1.Path
Form1.open.Picture=LoadPicture(label1.Caption) EndSub
EndSub
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg47
Bases de Datos con Delphi - Teora
Delphi y C++ Builder tienen mtodos de acceso a bases de datos que se basan en TDataSet. que, como su
nombre lo indica, es un "set de datos". El set de datos abstracto no especifica el origen de la base de datos .
Esto lo hace flexible e independiente.
Los componentes Table y Query son los componentes ms comnmente usados para acceso bsico a
bases de datos (pero no los nicos). Estos componentes representan una tabla y una consulta SQL,
respectivamente.
Conectores:
BDE: Libreras para acceder a tablas de dBase con el motor DataBaseEngine (obsoleto)
ODBC: Controlador creado por Microsoft para accesar a datos, integrado en Windows.
LiveBindings. (Versiones Xe). Acceso desde controles de FireMonkey y dispositivos mviles.
Driver o libreras de acceso a datos:
DbExpress: Sustituto del BDE que ha quedado obsoleto.
ADO: ActiveX Data Objects. Permite acceder a datos, sin necesidad de conocer la base de datos.
XML Client Dataset: Acceso a tablas de datos XML Necesita MIDAS.dll
FireDac. (Versiones Xe) Acceso directo a bases de datos
Componentes No Visuales de Acceso a Datos:
Conexin: Configura el driver y el modo de cacceso a la base de datos.
Database: Es la representacin de una base de datos o conjunto de tablas.
Table (Tabla): Representa una tabla entera. TTable contiene informacin acerca del tipo de tabla, del ndice,
as como filtros. TTable tiene entre sus mtodos, First, Next, Last, etc.
Query (Consulta): Se comporta como una tabla, pero al mismo tiempo es un comando de SQL.
Porqu SQL?: La respuesta es sencilla: COMPATIBILIDAD. La especificacin SQL-92 es soportada por
todos los lenguajes generales.
DataSource: Es el "origen de los datos". Un componente intermedio que permite tener varias
representaciones de los mismos datos
UpdateSQL: Permite editar un query SQL. Todos los queries tienen un Edit, Insert y Delete. TStoredProc:
Permite ejecutar un comando SQL sin esperar ninguna respuesta, como un procedimiento.
Componentes Visuales de Acceso a Datos
Los componentes de este tipo son llamados "Data-aware", y tienen el prefijo "DB". De este modo, un
componente de edicin "Edit" en su versin "Data Aware" es llamado "DBEdit". ComboBox se convierte en
"DBComboBox".
DBgrid es una tabla de datos y DBControlGrid equivale a formularios contnuos.
Ademas, existe un componente llamado "DBNavigator", que es una serie de botones "mapeados" a los
comandos Next, Prior, Last, Edit, Delete, etc., de cualquier DataSource.
Ejercicio 8. Bases de datos. Agenda de telfonos.
Tabla de datos DBF - Modo DBE: (obsoleto)
En Delphi escoge: Tools Database Desktop para crear el archivo que contendr los datos Data Base File
Escoge del men: File New Table: Dbase for Windows.
Crear la estructura de la derecha y guardar como Agenda.dbf
En el formulario principal de Delphi, aadir los componentes Table1 (Paleta BDE) y Datasource1( Paleta Data
Access)
En la Table1: La propiedad TableName es el nombre del archivo de datos: Agenda.dbf ; Name es el nombre de la
Tabla: Table1 y Databasename es la ruta donde se encuentra el archivo de datos
Crear la Tabla: Entra en Access y crea una base de datos con una tabla
llamada Acceso que contenga los campos de la imagen:
Complementos: Para realizar las pruebas y comparaciones puedes aadir al formulario un DBNavigator y un DBGRid
ambos conectados con el Datasource1
Accesoadatos.
DesdeAccesscreamoslabasededatosTestwincon3tablas:Acceso,
PreguntasyTemasylossiguientescampos:
Acceso:UsuarioClavePermiso
Temas:IDTema
Preguntas:Tema,Dificultatd,T1,R1,R2,R3$4,Sol,Comen,
Imagen
PginaSesin
Enelformulario,aadimoslosobjetos
dedatosdelaimagen.
Cadadatasourceenlazaconsu respectivaTFDtableyenellas,
cadaTablenameconlastablasdela basededatos.
Pestaadeacceso:
Aadimosdosgropubox
Destinadoainiciarsesindeusuarioocrear
nuevousuario.
Encadaunodeellosinsertamosdoscuadros
detexto(edits)ydosbotones(buttons)como
enlafigura.
Elsegundogroupbox,seestablecevisible=
false.
AlpulsarelbotnBNuevodelprimer
groupbox1semostrarelsegundoyocultar
elprimero:
procedureTForm1.BNuevoClick();
begin
GroupBox2.Visible:=True;
GroupBox1.Visible:=False;
end;
Opcional:PuedesaadiralformulariounDBGridyunDBNavigatorno
visulesyvinculadosalatabladeAccesoparacrearycomprobaralos
usuarios.
AadimosunnuevoGroupBox3quecontendrunLookupComboBox procedureTForm1.BAccesoClick(Sender:TObject);
llamadoFiltrotema,parala var
encontrado:Boolean;
seleccindeltemayun
opciones:TLocateOptions;
LabelUsuarioqueinformar begin
delnombredelusuario. opciones:=[LOCaseInsensitive];
encontrado:=TableAcceso.Locate('Usuario',
EUsuario.Text,opciones);
ifencontrado=falsethen
showmessage('Usuarioincorrectooinexistente')
else
begin
GroupBox1.Visible:=False;
AlpulsarelbotnparaaccederBacceso,compuebaconlafuncin GroupBox2.Visible:=False;
Locatesielusuarioexisteenlatabla.Encasoafirmativo,muestrael GroupBox3.Visible:=True;
GroupBox3paraescogereltema.Unavezescogidoeltema,alpulsarel LabelUsuario.caption:=
botndeIniciar,activaremoslasegundapginadelpagecontrol: TableAccesoUsuario.value;
end;
procedureTForm1.BInicioTemaClickPagecontrol.ActivePageIndex:=1;
Pginatrasera
Eslapginadeadministracindepreguntasyseaccedeaellaconprivilegiosdeadmninistrador.Enellapodemoscreary
modificarpreguntas.Aadimosloscontrolesconlosnombresquesemuestranenlaimagen:
Paracargarlaimagen:Aadirantesunelementodedilogo:OpenPictureDialog
o Alpulsarelelbotnpegar:DBIma1.PasteFromClipboard;
o AlpulsarenelbotnAbrir:ifOpenPictureDialog1.Execute()then
dbIma1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
ParaModificarTemas:AlpulsarelBotnModificarTemas:GroupboxTemas.visible:=true;
Pginafrontal
Enlapestaafrontal,aadirloscontrolesconlosnombresquesemuestranenlaimagen:
Creamoslasvariablespblicas:
aciertos,preguntas:integer;//>numricasenteras
media:single; //>decimalesdeprecisinsencilla
Aadimosloseventossiguientes:
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg53
Alpulsar(OnClick)enelbotnBsiguiente:
R1.font.color:=clblack; //<cambiocolores>
R2.font.color:=clblack; Ifletra='A'THENR1.font.color:=clred
R3.font.color:=clblack; elseifletra='B'THENR2.font.color:=clred
R4.font.color:=clblack; elseifletra='C'THENR3.font.color:=clred
labelcorrecto.visible:=false; elseifletra='D'THENR4.font.color:=clred;
labelincorrecto.visible:=false; end;
DBTextcomen.visible:=false; DBTextcomen.visible:=true;
Labelpregunta.caption:='Preguntanmero'+inttostr(preguntas+1) labelsiguiente.Caption:='Pulsasiguientepregunta';
+'de'+inttostr(TablePreguntas.RecordCount); labelsiguiente.visible:=true;
labelsiguiente.caption:='Hazclicsobreelcrculodelarespuesta labelelige.visible:=false;
correcta...'; Bsiguiente.enabled:=true;
labelelige.visible:=true; preguntas:=preguntas+1;
RadioRespuestas.itemindex:=1; labelpreguntas.caption:=inttostr(preguntas);
Bsiguiente.enabled:=false; media:=round(aciertos*10/preguntas);
//StatusBar1.Panels[0].Text:='Ndepregunta:' labelmedia.caption:=floattostr(media);
+inttostr(TablePreguntas.recno); progreso.progress:=preguntas;
RadioRespuestas.Enabled:=True; progreso2.progress:=aciertos;
RadioRespuestas.Hint:='Elige'; Ifletra='A'THENR1.color:=clwhite
TablePreguntas.Next; elseifletra='B'THENR2.color:=clwhite
StatusBar1.Panels[0].Text:='Ndepregunta:' elseifletra='C'THENR3.color:=clwhite
+inttostr(TablePreguntas.recno); elseifletra='D'THENR4.color:=clwhite;
imagenBien.picture.loadfromfile('DRAC.BMP'); if(preguntas=TablePreguntas.RecordCount)then//finde
StatusBar1.Panels[0].Text:='Ndepregunta:' preguntas
+inttostr(TablePreguntas.recno); begin
ifaciertos=preguntasthenLabelsiguiente.Caption:='Enhora
buena,hasobtenidolamximapuntuacin!!'+Labelmedia.caption
Alpulsar(OnClick)en RadioRespuestas:
else
var Labelsiguiente.Caption:='Findepreguntasdeltema.Hasobtenido
letra:string; un'+Labelmedia.caption;
begin MessageDlg(Labelsiguiente.Caption,mtInformation,[mbOk],0);
Binicio.Enabled:=true; Bsiguiente.enabled:=false;
ifBsiguiente.enabled=falsethen BInicio.Enabled:=true;
begin end;
caseRadioRespuestas.itemindexof Labeltotal.caption:=inttostr(TablePreguntas.RecordCount);
0:letra:='A'; end;
1:letra:='B';
2:letra:='C';
Alpulsar(OnClick)en elbotnBInicio:
3:letra:='D';
end; TablePreguntas.First;
RadioRespuestas.Enabled:=false; RadioRespuestas.Enabled:=true;
RadioRespuestas.Hint:=''; Bsiguiente.Enabled:=false;
ifletra=TablePreguntasSOL.valuethen progreso.progress:=0;
begin progreso2.progress:=0;
labelcorrecto.caption:='!Correcto!,esla progreso.MaxValue:=TablePreguntas.RecordCount;
'+TablePreguntasSOL.value; progreso2.MaxValue:=TablePreguntas.RecordCount;
labelcorrecto.visible:=true; aciertos:=0;
labelincorrecto.visible:=false; preguntas:=0;
aciertos:=aciertos+1; Labelmedia.Caption:='0';
labelaciertos.caption:=inttostr(aciertos); labelaciertos.Caption:='0';
imagenBien.picture.loadfromfile('DRACBIEN.BMP'); Labelpreguntas.Caption:='0';
//<cambiocolores> Labelsiguiente.visible:=true;
Ifletra='A'THENR1.font.color:=clblue Labelsiguiente.Caption:='Iniciodeltema'+filtro.text+'.Clicsobre
elseifletra='B'THENR2.font.color:=clblue elcrculodelarespuestacorrecta...';
elseifletra='C'THENR3.font.color:=clblue RadioRespuestas.itemindex:=1;
elseifletra='D'THENR4.font.color:=clblue; StatusBar1.Panels[0].Text:='Ndepregunta:'
end +inttostr(Table1.recno);
else R1.font.color:=clblack;
begin R2.font.color:=clblack;
labelincorrecto.caption:='Incorrecto,lasolucinnoerala'+ R3.font.color:=clblack;
letra+'sinola'+TablePreguntasSOL.value; R4.font.color:=clblack;
labelcorrecto.visible:=false; DBTextcomen.Visible:=false;
labelincorrecto.visible:=true; Labelincorrecto.Visible:=false;
imagenBien.picture.loadfromfile('DRACMAL.BMP'); Labelcorrecto.Visible:=false;
letra:=TablePreguntasSOL.value; imagenBien.picture.loadfromfile('DRAC.BMP');
Labelpregunta.caption:='Pregunta:';
Formulario: EnlapaletaDataControls,aadiralformulariounDbgrid,yensupropiedaddatasource:ponerdatasource1.
Aadir el grfico:
Delphi7:DelapaletaDatacontrols,aadiruncomponente:DBChart.
DelphiXE7:Delapaleta:TeeChartLit,aadirunTDBChart
Pulsardobleclicyenlasolapaseriesponercomoenlafigura.
EnlasolapaChart,Aadirlaserie1(Add)tipoBarcomoenfigura.
EnlapestaaDatasource:SeleccionarDatasetyelegirelDatasetdenuestratabladedatos.
procedureTForm1.calcula1Click(Sender:TObject); ifTable1.RecordCount<1thenshowmessage('Introduzca
var valoresenlatablaparacalcular')else
suma,xmax,xmin,media:single; begin
antes:single; media:=suma/Table1.RecordCount;
begin table1.refresh;
suma:=0; table1.Edit;
dessuma:=0; table1.First;
varsuma:=0; table1.DisableControls;//>ojo
table1.First; whilenottable1.eofdo
antes:=table1valor.value; begin
whilenottable1.eofdo table2.edit;
begin table2porciento.Value:=roundto((table2valor.value/sum
xmax:=max(table1valor.value,antes); a)*100,2);
suma:=suma+table2valor.value; table2.Next;
table1.Next; end;
antes:=table1valor.value;
end;
CODIGOFUENTEdelprogramaderecetas:
var
Receta:TReceta;//>nombredelaventanaoformulario
varfiltro:string;//>variabledetexto procedure
TReceta.TabSheet9Enter(Sender
procedureTReceta.PageControlChange(Sender:TObject); begin
contar('recetas');
begin
DM.table1.filtered:=true;
procedure
Edit1.text:=''; TReceta.PageControl1Enter(Sender
DM.Table1.CancelRange; begin
ifPageControl1.activepage=tabsheet1thenFiltro:='''Entrantes''';; contar('Recetas');
ifPageControl1.activepage=tabsheet2thenFiltro:='''Vegetales''';
ifPageControl1.activepage=tabsheet3thenFiltro:='''Carnes'''; procedure TReceta.contar(Sender:string);
ifPageControl1.activepage=tabsheet4thenFiltro:='''Pescados'''; begin
ifPageControl1.activepage=tabsheet5thenFiltro:='''Mariscos'''; Receta.StatusBar1.panels[1].text:=sender+ ':
ifPageControl1.activepage=tabsheet6thenFiltro:='''Varios'''; ' + inttostr(dm.Table1.RecordCount);
ifPageControl1.activepage=tabsheet7thenFiltro:='''Postres'''; end;
ifPageControl1.activepage=tabsheet8thenFiltro:='''Pastas''';
ifPageControl1.activepage=tabsheet9then
Begin
DM.table1.filtered:=False; procedure TReceta.Edit1Change(Sender
Filtro:='''Completo'''; Var
Campobusca: string;
end;
begin
DM.table1.filter:='Tipo='+Filtro;
Campobusca := 'TITULO';
Panellistado.caption:='Listado'+filtro;
DM.table1.SetRangeStart;
contar('Recetas'); DM.Table1.FieldByName(Campobusca).AsString:=Edit1.Tex
end; t;
DM.Table1.ApplyRange;
procedurecontar(Sender:TObject);
begin
Receta.StatusBar1.panels[1].text:=inttostr(dm.Table1.RecordCount);
end;
procedureTReceta.SpeedButton1Click(Sender:TObject);
begin
ifMessageDlg('Nuevareceta?',mtConfirmation,[mbYes,mbNo],0)=id_Yesthen
begin
DM.table1.insert;
ifPageControl1.activepage=tabsheet1thenDM.Table1TIPO.value:='Entrantes';
ifPageControl1.activepage=tabsheet2thenDM.Table1tipo.value:='Vegetales';
ifPageControl1.activepage=tabsheet3thenDM.Table1tipo.value:='Carnes';
ifPageControl1.activepage=tabsheet4thenDM.Table1tipo.value:='Pescados';
ifPageControl1.activepage=tabsheet5thenDM.Table1tipo.value:='Mariscos';
ifPageControl1.activepage=tabsheet6thenDM.Table1tipo.value:='Varios';
ifPageControl1.activepage=tabsheet7thenDM.Table1tipo.value:='Postres';
ifPageControl1.activepage=tabsheet8thenDM.Table1tipo.value:='Pastas';
DM.Table1TITULO.value:='';
end;
end;
procedureTReceta.SpeedButton2Click(Sender:TObject);
begin
ifMessageDlg('Borrarreceta?',mtConfirmation,[mbYes,mbNo],0)=id_YesthenDM.table1.delete;
end;
Impresin:
Imprimirelformulario(ventana):Aadircomponente:PrintdialogdelapaletaDialogsyenelbotnimprimirescribirel
cdigo:ifPrintDialog1.executethenprint;
Imprimirinformededatos:UtilizareldiseadordeinformesRavereportoQreportexplicadosenelsiguientetema.
Guardaelproyectoconelnombre:Recetas(tambinlaventana/unidadrecetas1ylaventana/datamoduledm)
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg57
INFORMES de impresin de datos (reports)
a) Crear un informe con RaveReports
Truco: Cambiar el formulario de vista previa a espaol: Busca en la carpeta: Rave5\Lib los formularios:
RPFormPreview.FRM y RPFormSetup.FRM y brelos desde Delphi.
Opcional: Puedes aadir tambin un componente: RVSystem al formulario de recetas y que enlazar
con la propiedad Engine del objeto RaveReport. Este componente te permitir especificar los
parmetros de impresin y vista previa deseados.
Truco: Para cambiar la ventana a espaol, abre el formulario: QRPrev.DFM en la carpeta: DELPHI\LIB
LENGUAJE SQL EN DELPHI
Manipulacin de Datos mediante lenguaje SQL: SELECT, INSERT, UPDATE, DELETE
SELECT: Extrae datos de una o ms tablas indicando los campos (o columnas) separados por comas.
El asterisco (*) sustituye a todos los campos
UPDATE: Modifica datos de la tabla. Ej: UPDATE GOODS SET CITY = 'SANTA CRUZ' WHERE GOODS.CITY = 'SCOTTS
VALLEY'
DELETE: Borra datos de la tabla. Ej: DELETE FROM GOODS WHERE PART_NO = 'AA0093'
Substitucin de variables:
En Delphi, cuando se aade una palabra precedida por un signo de dos puntos (:), la palabra es
automticamente convertida en un parmetro, el cual es agregado a la propiedad: Params
SELECT * FROM "CLIENTS.DBF" CLIENTES WHERE Last_Name LIKE :Apellido
LIKE: devuelve todos los registros que se parezcan a la cadena. La lnea que asigna el parmetro aade un
signo de porcentaje (%) al final:
qryClientes.ParamByName('Apellido').AsString := dlgConsulta.edtApellido.Text+'%';
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg59
Ejercicio de consulta de datos con SQL
Crea una aplicacin nueva en Delphi. File New Aplication.
De la pestaa Data Access y DBE, inserta los componentes: Query y DataSource que representan las
partes "no visuales" del acceso a base de datos.
Ahora, vaya al TQuery y cambie la propiedad "Databasename" a Dbdemos, que es un alias local que apunta
al directorio de Demos de Delphi.
Selecciona el Datasource. En la propiedad Dataset, selecciona: Query1
Selecciona el Query1, haz doble-click en su propiedad: SQL Escribe lo siguiente:
SELECT * from animals where upper(NAME) like :nombre order by NAME
Obseva que :nombre es un parmetro. En la propiedad Params pulsa doble clic y pon su Datatype a string
A continuacin, vaya a la propiedad "RequestLive" de su Query y pngala en "True". Esto es importante
porque SQL siempre devuelve resultados "Read-Only", o "muertos" (dead) a menos que especifiquemos que
nuestro query debe ser "vivo" (live)
Haz doble-click en el query1. A continuacin vers una ventana vaca. Haz click con el boton derecho del
mouse y selecciona: "Add Fields". Nos aparece la lista de las "columnas" (campos) disponibles. As que
simplemente presiona {Enter} para aceptar el aadir todos los campos.
Arrastra" desde la lista de campos del query1, hasta el formulario. Cuando "sueltes" cada campo, Delphi
crear un componente TLabel y un DbEdit, listos para recibir los datos adecuados. Conecta todos los
DBedits con la propiedad Datasource al Datasource1. A asignar su datafield al campo correspondiente.
Para ver los datos vamos a abrir el query1 (active = true).
Groupbox
Edit1
Dbedit
5. Seleccionar todos
los campos de
tablefacturas y
soltar sobre el
form principal
llamado:
Facturacin
6. Crear un DBgrid
con Align al
bottom y asignarle
la datasource de
articulos.
Luego aadir
todos los
campos al
dBGrid de
artculos.
7. Para
relacionar
facturas con
artculos
debemos
volver al DM y
elegir en
mastersource
de artculos el
Datasource
de facturas.
Luego, en el
MasterFields, relacionar los campos NUM_Fact de cada tabla. Activar ambas tablas (active=true) para ver el
funcionamiento.
8. Aadir en el form principal un DBNavigator para las facturas.
9. Crear el campos calculados:
Asignar a un campo existente un calculado: Para el importe: En la table_articulos poner en el evento:
onCalcfileds: Table_articulosimporte.Value:=Table_articuloscant.Value*Table_articulosprecio.Value;
Luego poner en el campo Importe su propiedad: FieldKind: fkCalculated
Crear un campo
calculado nuevo:
llamado PVP (como
referencia):
En la table_articulos
anadir un New
field del tipo: Flota y
calculado.
Aadir al evento: On
CalcFileds: Table_articulosPVP.Value:=Table_articulosprecio.Value*(1+Table_facturasiva.Value/100);
Clculo automtico: Por ltimo, para calcular automtico, aadir al evento del la table_articulos: AfterPost:
Table_articulosAfterPost: Form1. Calcular1Click(nil); // llama al procedure sin sender
Mejoras:
Aadir el componente DBCombobox al % de IVA con los items: 0,7,12,16. En el campo IVA del DataModule
cambiar su DefaultExpression = 16.
Para autoincrementar el nmero de factura: Como no existe del tipo Autonumerico en Dbase, no vale con cambiar
el Autogeneratevalue a AutoInc sino escribir el cdigo:
Var pblica en el Data module: Numero:single:
Table_facturasBeforeInsert: Table_facturas.last;
Numero:=Table_facturasNUM_FACT.value;
Table_facturasAfterInsert: Table_facturasNUM_FACT.value:=numero+1;
procedureTForm1.primeroClick(Sender:TObject);
begin
withtable1do
begin
ifsender=primerothenfirst
elseifsender=anteriorthenprior
elseifsender=siguientethennext
elseifsender=ultimothenlast
elseifsender=nuevathen
begin
if(Application.MessageBox('Crearnuevoregistro?','Agregarregistro',MB_YESNO)=IDYES)then
begin
table1.append;//>Inserta
table1.Post;//>Guarda
end;
end
elseifsender=borrarthen
begin
if(Application.MessageBox('Confirmaquedeseaeliminaresteregistro?','Confirmareliminacinderegistro',
MB_YESNO)=IDYES)thendelete;
end;
Table1.Refresh;
StatusBar1.panels[1].text:='Totalregistros:'+inttostr(Table1.RecordCount);
end; Table_facturasFECHA_FACT.value:=date;
NivelAvanzado.ControldeBasededatos.Relacionardostablas(facturacin)
Cmo crear una consulta (Query) SQL para relacionar dos tablas por un campo en comn: VaselenguajeSQL
Pasos previos para el ejercicio: enestemanual
CrearundirectorioC:\FACTU(osimilar)
UtilizarlaherramientaDataBaseDesktopparacrearpreviamentelastablasdebasesdedatos:FACTURA.DBFy
ARTI.DBFcuyocamposmnimossean:
ARTI."REFER",
FACTURA."NUM_FACT", ARTI."DESCRIPCIO",
FACTURA."FECHA_FAC", ARTI."CANT",
FACTURA."COD_CLIENT",
ARTI."DESC",
FACTURA."IVA", ARTI."PRECIO",
ARTI."NUM_FACT",
EstaaccinesautomticaconFileNewDataBaseForm.
EsconvenienteusarundatamoduleparalasDatasourcesylasquerys.
Relacionamoslasfacturasconsusartculosporelcamponum_factcomnalosdos.
Recordarque: Query1NUM_FACT: TFloatField; Name:Table1
Query1 Query2
Ejercicio. Facturacin DataBaseName:c:\factu
TableName:FACTURA.DBF
Table2
DataBaseName:c:\factu
TableName:ARTI.DBF
DataSource2
DataSource1 DataSet:Query2
DataSet:Table1
Campos
Calculados
Nota:Enestaaplicacinesposibleaadirymodificardatosenfactura,peronoenartculos.Paraello OnFormcreate:
esnecesariocrearunbotnparaaadirartculo,queutilizalatable2. Query1.Open;
LasconsultasSQLnopermitenmodificacionesenlatablarelacionadasinotenemosRequestLivea
Query2.Open;
true.Poresotrabajaremosdirectamentesobrelastablasenpginasiguiente.
Botncalcular
Procedureparaaadirunanuevafactura:
AntesDeestosprocedurescrearla
Variablenumero:DOUBLE(deltipoflotante)
1saberculeslaltimafactura
procedureTFormfactu.Table1BeforeInsert
begin
table1.last;
numero:=table1num_fact.value;
Cmoborrarlaltimafactura end;
procedureTFormfactu.EliminarClick
2sumar1alnmerodelaltimafacturay
begin
ponrseloalanueva,tambinprepararlafecha
table1.last;
delafacturaconeldadehoy:
numero:=table1num_fact.value;
ifMessageDlg('Eliminarlafactura'+floattostr(numero)+
procedureTFormfactu.Table1AfterInsert
'?',mtInformation,[mbYes,mbNo],0)=mrYes
begin
thentable1.delete;
table1num_fact.value:=numero+1;
end;
table1fecha_fac.value:=date;
table1iva.value:=16;
estado.caption:='Aadidalafacturanum.'+
procedureTFormfactu.Table1AfterDelete; floattostr(numero);
begin end;
ShowMessage('Eliminadalafacturanum.'+
floattostr(numero));
end;
Ejercicio Facturacin. Cmo crear un campo calculado para el IMPORTE:
Supongamos que tenemos una tabla cuya Table Name sea Articulos.dbf y que posee entre otro el campo CANT (cantidad) y
el campo PRECIO:
Pulsa doble clic encima de la tabla para activar el Fields Editor.
Pulsa el botn derecho encima y elige aadir campos (coge todos). De esta manera se declaran en la unidad PAS todos
los campos y sus tipos.
A continuacin elige New Field. Nuevo campo cuyo nombre ser IMPORT, del tipo FLOAT y CALCULATED.
Termina con OK.
Pulsa doble clic en el evento ONCALCFIELDS de la tabla. Debemos introducir una frmula para el campo.
Presta atencin al nombre que tiene los campos en el apartado TYPE de la unidad PAS y escribe el valor:
Table2IMPORT.VALUE:=Table2CANT.VALUE*Table2PRECIO.VALUE;
Para probar su funcionamiento, puedes crear 3 componentes DBEDIT para la cantidad, precio e importe. Recuerda
poner en la propiedad Paswordchart #0 para obligar a que sea un dato numrico.
Tambin es posible crear campos calculados uniendo campos de texto. Ejemplo:
CustomersCityStateZip.Value := CustomersCity.Value + ', ' + CustomersState.Value + ' ' + CustomersZip.Value;
Campo calculado importe (En la tabla 2 On calcfields)
procedure TFormfactu.Table2CalcFields(DataSet: TDataSet);
begin
table2importe.value:=table2cant.value*table2precio.value;
table2pvp.value:= table2importe.value*(1+table1iva.value/100);
end;
Cmocalcularlabaseimponible:Labaseimponiblenoesuncampocalculado,pueseselresultadodelasumadevarios
camposdevariosregistrosmientrasuncampocalculadoseobtienedeoperarconcamposdeunmismoregistro.
Mtodo2:BaseimponibleconunbucleWhilequesumeconsecutivamenteyunoaunocadaregistroyloalmacene
enunavariablenumrica.
Comoestemtodoesmslento(peromsflexible)esaconsejablecrearunbotnllamado"Calcular"cuyo
procedimientoalhacerclicseaelsiguiente.
LavisualizacindelabaseimponibledebeserenuncomponenteLabelnoEditpuesesmsfcilyademsnodebe
sermodificable.
procedureTFormfactu.CalcularClick(Sender:TObject);
var
baseimpo:Real;{crealavariablenumricarealdondesealmacenarelresultadodelasuma}
impiva:Real;
begin
baseimpo:=0.0;
impiva:=0.0;
table2.disablecontrols;
table2.first; {sitaelpunteroderegistrosalprincipiodelatabla}
whilenottable2.eofdo {mientrasnollegealEndOfFile...(finaldelatabla)hazelbucle}
begin
baseimpo:=baseimpo+table2importe.AsFloat; {sumalacantidadanteriormsladeestecampo}
table2.next; {saltaalsiguientecampo}
end; {repiteelbucle}
table2.enablecontrols;
impiva:=baseimpo*table1iva.value;
labelbaseimpo.Caption:=Floattostr(baseimpo);
end;
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg65
FichaListadodefacturas.Crearunfiltroentredosfechas.
ChekBox:Filtrar
procedureTFormfactu.FiltrarClick(Sender:TObject);
Crearuncomponentetablayun begin
datasource: iffiltrar.checked=truethen
Aadir2componentesdeltipo begin
DateTimePickers:
Propiedadesdelatabla: table1.active:=false;
Names:InicioyFin
Name:Consulfactu consulfactu.active:=true;
Tablename:Factura.dbf consulfactu.IndexFieldNames:='Fecha_fac';
withconsulfactudo
PropiedadesdelDatasource: begin
Dataset: Consulfactu SetRangeStart;{inicioindice}
FieldByName('Fecha_fac').AsString:=
datetostr(inicio.date);
SetRangeEnd;{finalindice}
FieldByName('Fecha_fac').AsString:=datetostr(fin.date);
ApplyRange;{estableceelrangoalDataset}
end;
Impresindelafactura: end
1. CrearunanuevaventanaQuikReport1 else
begin
2. Aadirlosapartados:QrBand,QrSubdetaillyGroupFooterBand1
{nohayqueponerfiltrar.checked:=false;}
3. Aadirloscomponentes:QRLabelparaetiquetasottulosyQRDbtextparaloscampos
consulfactu.CancelRange;
4. Aplicarunfiltroparaquesloseimprimaunafactura
consulfactu.active:=false;
QrBand.Tipo:Qtdetaill
table1 active:=true;
AlpulsarelbotnImprimir:
procedure
TFormfactu.SpeedButton2Click(Sender:TObject);
var
textofiltro:string;
begin
QrSubdetaill
textofiltro:='num_fact='+floattostr(table1num_fa
ct.value);
table1.filter:=textofiltro;
table1.filtered:=true;
quickreport1.preview;
table1.filtered:=false;
end;
GroupFooterBand1
Porltimo:CrearelprogramadeInstalacin:
ParaelloutilizarelprogramaanexoInstallShieldyseguirlospasosparacreareldiscodeinstalacindelprograma.
RecuerdaquetambindebesaadiralosarchivosdeinstalacinelcontroldeBasededatosDBE
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg67
Cdigofuentebasedeejemploparaprogramadefacturacin:
unitfactu1;
interface
usesWindows,SysUtils,Classes,Graphics,Forms,Controls,StdCtrls,Buttons,ComCtrls,ExtCtrls,Menus,DBTables,DB,
DBGrids,Mask,DBCtrls,dialogs,math,Grids;
var end;
Formfactu:TFormfactu; table2.last;
numero:double; table2.delete;
baseimpo:Real; end;
table1.enablecontrols;
usesempresa1,CLIENTES,Imprime1,Acerca; table2.enablecontrols;
end;
procedureTFormfactu.FormCreate(Sender:TObject);
begin procedureTFormfactu.nuevoClick(Sender:TObject);
table1.open; begin
table2.open; table2.insert;
table3.open; end;
table4.open;
table1.last; procedureTFormfactu.borraartClick(Sender:TObject);
begin
procedureTFormfactu.Table1AfterInsert table2.delete;
begin end;
table1num_fact.value:=numero+1;
table1fecha_fac.value:=date; procedureTFormfactu.Table2CalcFields
table1iva.value:=16; begin
estado.caption:='Aadidalafacturanum.'+ table2importe.value:=table2cant.value*table2precio.v
floattostr(numero); alue;
end; table2pvp.value:=
table2importe.value*(1+table1iva.value/100);
procedureTFormfactu.Table1BeforeInsert end;
begin
table1.last; procedureTFormfactu.calcula1Click(Sender:TObject);
numero:=table1num_fact.value; var
end; impiva:Real;
totfact:Real;
procedureTFormfactu.Table1AfterDelete toteuros:Real;
begin begin
estado.caption:='Eliminadalafacturanum.'+ baseimpo:=0.0;
floattostr(numero); impiva:=0.0;
ShowMessage('Eliminadalafacturanum.'+ totfact:=0.0;
floattostr(numero)); toteuros:=0.0;
end; table2.disablecontrols;
table2.open;
procedureTFormfactu.EliminarClick(Sender table2.first;
begin whilenottable2.eofdo
table1.last; begin
numero:=table1num_fact.value; baseimpo:=baseimpo+table2importe.AsFloat;
table2.disablecontrols; table2.next;
table1.disablecontrols; end;
ifMessageDlg('Eliminarlafacturan'+ {TFormfactu.Table1CalcFields;}
floattostr(numero)+'?',mtInformation,[mbYes, {table1base_impon.value:=baseimpo;}
mbNo],0)=mrYes table2.enablecontrols;
then impiva:=baseimpo*table1iva.value/100;
begin labelbaseimpo.caption:=Floattostr(baseimpo);
table1.delete; labelimpiva.caption:=Floattostr(impiva);
table2.first; totfact:=baseimpo+impiva;
whilenottable2.eofdo {iftotfact>0thentoteuros:=totfact/table1euro.value;}
begin labeltotal.caption:=Floattostr(totfact);
table2.delete; labeleuros.caption:=Floattostr(toteuros);
table2.next; end;
Filtros y bsquedas en tablas
Bsquedas blandas desde un edit o Dbcombo.
{elEditsellamabuscaylavariableCampobusca:String;}
procedureTFichero.buscaChange(Sender:TObject);
begin
Campobusca:='Apellidos';
table1.SetRangeStart;
Table1.FieldByName(Campobusca).AsString:=busca.Text;
Table1.ApplyRange;
end;
Bsquedas duras
Table1.Open; // abrir la tabla
Table1.SetKey; // Ponemos el DataSet en situacin dsSetKey
Table1.FieldByName('Autor').AsString := 'Borges';// Damos valor al campo
Table1.GotoNearest; // Nos posicionamos en ese valor o el ms cercano
showmessage(table1.FieldbyName('Autor').AsString);
Table1.close;
procedureTForm1.Button1Click(Sender:TObject);
var
temp:integer;
opcion:TLocateOptions;
begin
Table1.Locate('NOMBRE',Edit1.Text,[]);
end;
LosparmetrosdelmtodoLocate(),son;
Locate("Columnadebsqueda","Datoabuscar",[loCaseInsensitive,loPartialKey]);
cuandoopcin=loCaseInsensitiveignoradiferenciaentremaysculasyminsculas
cuandoopcin=loPartialKeyresultadoparcial,ejemplosisebusca"ju"seposesionaenelprimerrenglndonde
esecampoempiececon"ju",ejemploJuan,juvenal,etc.
Contar el nmero de registros:
Se puede utilizar este ejemplo en el ejercicio anterior para calcular el nmero de facturas totales.
numero.caption:=IntToStr(table1.recordcount)+' fichas';
BasedatostipoclienteservidorDelphi:InterbaseFirebirdMysql
EnlugardeusartablaslocalestipoBDomdb,utilizaremosunabasededatosdeltiposervidorcomo
Interbase(osuequivalentegratuitaFirebird):
1. InstalarInterbaseoFirebirdenelPC:https://downloads.embarcadero.com/free/interbase
2. CrearlabasededatosconIBconsoleoconIBExpert
Herramientas visuales de Interbase: IBConsole:
El primer paso para utilizar IBConsole es registrar el servidor Interbase y conectar a servidores locales y
remotos.
Pararegistrarunservidor:seleccionardelmenServer|Register...oCreateloquemostrarlaventana
paraconectarseaunservidorlocaloremoto.
Indicarsielservidoreslocaloremoto.Pordefectoeslocal.Enelcasoquesearemoto,indicarelnombredel
servidoryelprotocoloderedautilizar.SiesTCP/IPsepuedeindicarladireccinIPenlugardelnombre.
Sisequiereregistrarelservidor...
oIndicarunnombredealias.Enelcasodeservidorlocal,elnombreesautomtico.
oIndicarunadescripcinparaelservidor.
oIndicarquelainformacindealiasdebeseralmacenada.
Sisequiereconectaralservidor...
oIndicarelnombredeusuario(SYSDBA)
oIndicarlaclave(masterkey)
LaprimeravezqueentrasaInterbase,elsistematiene
predefinidounusuario
llamadoSYSDBAquetienetodoslosderechosdeaccesoen
Interbase.El
passworddeesteusuarioesinicialmentemasterkey
Paracrearunabasededatos:
Indicarunnombredearchivo.GDB.Seleccionardelmen
Database|CreateDatabaseEscribeelnombreAGENDA
(puedesponerleextensinGDBoIB).Escogeellugardonde
guardar.PulsaOK.
Paraconectarconlabasededatos:
Pulsaelbotnderechosobrelatablayescoge:Connect.
Tepediruserycontra.Rellenarcomoenlafigura:
Paracreardeunatabla
VamosacrearunatabladesdeInteractiveSQL:
EscogedelmendeIBConsole:ToolsInteractiveSQL.
CopiaestecdigoenInteractiveSQLyescogedelmen:
QueryExecute
createtabletelefonos
(nombrevarchar(24)notnullprimarykey,
direccionvarchar(24)notnull,
telefonovarchar(24)notnull)
Sintaxiscreatetable:Enprimerlugarindicamoselnombredelatablayluego,entreparntesisy
separadosporcomas,loscamposquelacomponen.Paracadacampoindicamossunombre,tipode
datoeimposiciones.Todosloscampostienenlasmismasimposicionessalvoelcamponombreque,
ademsdelaimposicinnotnull,tienelaimposicinprimarykey.
Seleccionarloscampos:
EscogedelmendeInteractiveSQL:QueryWizardaadetodosloscamposyescribeunalias.Se
generarunaconsultacomoesta:
selectA."NOMBRE",A."DIRECCION",A."TELEFONO"from"TELEFONOS"A
Escogedelmen:QueryExecute.Semostrarlatabla.
Insertardatosenlatabla:
Insertintotelefonos(nombre,direccion,telefono)
values('Ofimega','CalleBarcelona','977350471')
Recuerdaqueelcamponombrenosepuededuplicarporserprimarykey.
Modificardatos:
Cambiamoseltelefonoconelsiguientecdigo:
Updatetelefonossettelefono=977351777
IBExpert
Esunaherramientagratuitaquesedescargadesdelapginadefirebirdyesuninterfazgraficopara
manipularbasesdedatosytablasdeinternaseyfirebird.
1. Descargarversinpersonaldesde:http://ibexpert.net/ibe/index.php?n=Main.DownloadFree
2. Registrarteparaqueteenvenelpasswordynombredeusuario.
Introducirlosalejecutarelprograma.
3. Crearlabasededatos:
Escogedelmen:DatabaseCreatedatabase
Introduceelnombredeusuario,password,versindelabasededatosy
lugardondeseguarda.Verfigura
4. Conectarlabasededatos.Pulsasobreelnombredelabasededatosdela
listayescoge:Conect.
5. Crearlatabla:PulsaelbotnderchodelmousesobreelelementoTablesy
escoge:Newtable
Escribeelnombredeloscampos,sutipoytamaoenlapestaa:Fields:
6. EscribeelnombredelatablaTELEFONOSenellugarindicadoporlaflechadelaimagen.
7. Rellenardatos:SeleccionalapestaaDatayescribealgunasfilas.
ConexinInterbaseconDelphi:
Enunaaplicacinnueva,aadimosalformulariounDatasource,unDBGridyun
DBNavigatorLuegorelacionamoselDBnavigatoryelDBgribconelDatasource.
DelapaletadecomponentesInternase,aadirunIBDatabaseyunIBtransaction.
ElcomponenteIBdatabasesellamarIBdatabase1yenelcomponenteIBtransactioncambialapropiedad
DefaultdatabaseporIBDatabase1.
EnelcomponenteIBDatabase1cambialapropiedadDatabasepor:
C:\...\AGENDA.GDBAGENDA.IB.SilabaseesdeFirebird:AGENDA.FDB
CambialapropiedadConected=true.TesolicitarenUsernameyelPassword.
Ponereldelaimagenderecha:
Metodo1.ModoDBE:
AadiruncomponenteIBTableycambiarlaspropiedadescomoenlaimagen
derecha.
Metodo2.Sintabla:
AadiruncomponenteIBdatasetqueproveeuneditorSQL.CambiasupropiedadDatabasepornuestraDatabase1ysu
propiedadSelectSQLpor:Select*fromtelefonos.
EsaconsejablecrearundatamodulellamadaDMconexionconloscomponentes:IBDatabase,IBtransactiony
IBdataset.Compila(F9)yguardaelproyectoconelnombre:Agenda.
AgregueunZTableymodifiquelassiguientespropiedades:
Connection:ZConnection1
TableName:myagenda
ParaconectardirectoaunPCservidorremoto:
EsnecesariodetectarlaIPdelservidor(medianteunawebcomohttp://www.hcidata.info)elnombredelabasede
datosysupasswordparaagregarloalcontroladorODBC
MedianteaccesoFireDAc
ParaDelphiXE7ysuperioresdiponesaccesodirectouniversalDAC:
DesdelapaletaFireDACinsertarloscomponentesdelafigura
EnFDconectionpulsadobleclicyespecificaeldriver:MySql
ElaccesoalasbasesdedatosMySQLoSQLiteylascreacindelastablases
posiblehacerlomuyfcilmentedesdelapestaaDataExplorer.
Crearunanuevaconexinyconelbotnderechoencimaseleccionar:Newtable.
Aadirloscamposdetexto:Nombreytelfonodeancho50caracteresyguardarlatablaconelnombreAgenda.
Arrastrarlatablacreadasobreelformulario.Aparecernloscomponentes:
AgendatableymSqlConection
Activalascasillas:
Conectedyactive.
AadeunoscomponentesDBGrid,DBNavigatoryDatasourcealformulario
Mtodo2:UsarZeos
1. DescargarlalibreragratuitaZeosDBOVersion714.
2. InstalarelpakageparaXE7
3. Aadirloscomponentesdelaimagenalformulario:
4. EnZconectionasignarladatabaseyectivarconected.
5. EnZtable:AsignaralaTablename:agendayactivar.
6. EnDatasource:Ponereldataset:Ztable1
7. EnelDBGridyelDBNavigaorasignarelDatasource1
8. Probar(Run)
Mtodo3:UsarFireDAC
ParaDelphiXE7ysuperioresdiponesaccesodirectouniversalDAC:
DesdelapaletaFireDACinsertarloscomponentesdelafigura
EnFDconectionpulsadobleclicyespecificaeldriver:MySql
Mtodo 2:
Con esto nos aparecer el dispositivo en el target de Android SDK. Pulsar doble
clic sobre l.
En el modo de emulacin se puede arrancar antes el emulador del SDK para que tarde menos. Accediendo a
las Android tools o SDK manager y en el manager AVD virtual devide arrancar (Start) el AVD deseado.
Para probar la emulacin para IOS crearemos una aplicacin bsica para FireMonkey;
Escoge: New > FireMonkey Desctopt Application o File > New > Other > Delphi Projects > FireMonkey HD
Application.
Aade, de la paleta Estandar, estos tres elementos al formulario:
- Tedit Edit1
- TButton que diga Hola.
- TLabel que diga: Introduzca
su nombre
Probar la aplicacin:
Pulsa el botn Run o elige del men: Run run para comprobar su funcionamiento.
Nota: Si tu FM RAD Studio corre bajo x86 (Win32) podrs compilar en 64 bits
pero no podrs ejecutarlo.
3 Selecciona Add
para abrir la ventana de conexin con un equipo
mac por red.
Crea un nuevo proyecto llamado Ruffini (File > New > Multidevice)
Aade los componentes de la imagen adjunta:
1 spinbox
5 lables
2 StrinGrid
Llama a las Stringrids con el nombre: coef
y tabla
Llama al coef divisor a
Aade el evento en el botn:
procedureTForm1.FormCreate(Sender);
varco:integer;
begin
forco:=0toround(grado.Value)do
coef.Cells[co,0]:='0';
end;
procedureTForm1.Button1Click(Sender:TObject); procedureTForm1.GradoChange(Sender:TObject);
var begin
d:real; ifgrado.Value<coef.ColumnCount1then
fi,co,I:integer;//fila,columna
begin begin //quitacolumnas
d:=strtofloat(a.Text)*1;//cambiamoselsigno coef.Columns[tabla.ColumnCount1].DisposeOf;
tabla.cells[0,1]:=floattostr(d); tabla.Columns[tabla.ColumnCount1].DisposeOf;
forco:=1toround(grado.Value)do//ponemoslos end
coeficientes
elseifgrado.Value>coef.ColumnCount1then
ifcoef.Cells[co1,0]=''thentabla.cells[co,0]:='0'
begin //aadecolumnas
elsetabla.cells[co,0]:=coef.Cells[co1,0];
coef.AddObject(TStringColumn.Create(Self));
//bajamoselprimercoef;
tabla.AddObject(TStringColumn.Create(Self));
co:=1; //>celda[col,fil]
coef.Cells[tabla.ColumnCount1,0]:='0';
fi:=2;
coef.Columns[tabla.ColumnCount1].Width:=50
tabla.cells[co,fi]:=tabla.cells[co,0]; tabla.Columns[tabla.ColumnCount1].Width:=50
forco:=1toround(grado.Value)do
begin end;
//multiplicamosyponemosarribaizquierda
tabla.Cells[co+1,fi1]:= tabla.RealignContent;
floattostr(d*strtofloat(tabla.cells[co,fi])); end;
//sumamosyponemosabajo:
iftabla.cells[co+1,fi2]=''then
tabla.cells[co+1,fi2]:='0';
tabla.Cells[co+1,fi]:=floattostr(strtofloat(tabla.cells
[co+1,fi2])+strtofloat(tabla.cells[co+1,fi1]));
end;
end;
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg81
Sensores mobile. Antorcha android (versin apaptada Samples\FlashLight)
Descarga de internet imagen de bombilla o similar y de un botn encendido y apagado:
Crea un nuevo proyecto llamado Linterna (File > New > Multidevice
application)
Aade los components de la imagen derecha:
Alinea el LayoutContenedor al cliente y el LayoutBotones al centro.
Aade el cdigo:
procedureTForm1.FormCreate(Sender:TObject);
begin
apagado.Enabled:=Camera.HasFlash;
Camera.Active:=True;
end;
procedureTForm1.ApagadoClick(Sender:TObject);
begin
apagado.Visible:=False;
encendido.Visible:=True;
Camera.TorchMode:=TTorchMode.ModeOn;
end;
procedureTForm1.EncendidoClick(Sender:TObject);
begin
apagado.Visible:=True;
encendido.Visible:=False;
Camera.TorchMode:=TTorchMode.ModeOff;
end;
Compila en dispositivo: En el Project Manager, selecciona la plataforma Android y conecta un mvil Android al
Puerto USB.
Ejecutar y comprobar: Escoje Run > Run Without Debugging
Guarda el Proyecto: Linterna y la unidad: Linterna1.
Aade el cdigo:
procedureTForm1.ActivadorSwitch(Sender:TObject);
begin
LocationSensor1.Active:=Activador.IsChecked;//>activaellocationsensor
end;
procedureTForm1.LocationSensor1LocationChanged(Sender:TObject;
constOldLocation,NewLocation:TLocationCoord2D);
begin
Lat.Value:=NewLocation.Latitude;//>devuelveposicinlatituddelGPS
Long.Value:=NewLocation.Longitude;//>devuelveposicinlongituddelGPS
Button1Click(Sender);//>situaenelmapa
end;
procedureTForm1.Button1Click(Sender:TObject);
begin
formatsettings.DecimalSeparator:='.';//>formatodecimalpuntoamericano
WebBrowser1.Navigate('https://maps.google.com/maps?q='+floattostr(Lat.Value)+','+
floattostr(Long.Value));
end;
Compilar en el dispositivo: Conecta un mvil Android al Puerto USB y en el Project Manager, selecciona la
plataforma Android.
Ejecutar y comprobar: Escoje Run > Run Without Debugging
Guarda el Proyecto: Localizador y la unidad: Localizador1.
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg83
Sensores mobile. Orientacin sensor (versin apaptada Samples)
Propiedades:
OrientationSensor1SensorChoosing( end;
Sender:TObject;constSensors:TSensorArray;
varChoseSensorIndex:Integer); Timer1Timer(Sender:TObject);
var begin
I:Integer; lbTiltX.Text:=Format('TiltX:%f',
Found:Integer; [OrientationSensor1.Sensor.TiltX]);
begin lbTiltY.Text:=Format('TiltY:%f',
Found:=1; [OrientationSensor1.Sensor.TiltY]);
forI:=0toHigh(Sensors)do lbTiltZ.Text:=Format('TiltZ:%f',
begin [OrientationSensor1.Sensor.TiltZ]);
ifbotonInclinacion.IsPressedand lbHeadingX.Text:=Format('HeadingX:%f',
(TCustomOrientationSensor.TProperty.TiltXin [OrientationSensor1.Sensor.HeadingX]);
TCustomOrientationSensor(Sensors[I]).AvailablePr lbHeadingY.Text:=Format('HeadingY:%f',
operties)then [OrientationSensor1.Sensor.HeadingY]);
begin lbHeadingZ.Text:=Format('HeadingZ:%f',
Found:=I; [OrientationSensor1.Sensor.HeadingZ]);
Break; end;
end
elseifbotonOrigen.IsPressedand FormActivate(Sender:TObject);
(TCustomOrientationSensor.TProperty.HeadingXin begin
TCustomOrientationSensor(Sensors[I]).AvailablePr {$ifdefIOS}
operties)then {$ifndefCPUARM}
begin lbOrientationSensor.Text:='Sinsensor';
Found:=I; swOrientationSensorActive.Enabled:=False;
Break; {$endif}
end; {$endif}
end; end;
ifFound<0then botonOrigenClick(Sender:TObject);
begin begin
Found:=0; OrientationSensor1.Active:=False;
botonInclinacion.IsPressed:=True; botonInclinacion.IsPressed:=False;
botonOrigen.IsPressed:=False; botonOrigen.IsPressed:=True;
ShowMessage('Brjulanodisponible'); OrientationSensor1.Active:=
end; swActivar.IsChecked;
end;
ChoseSensorIndex:=Found; swActivarSwitch(
end; Sender:TObject);
begin
botonInclinacionClick(Sender:TObject); {activateordeactivatetheorientation
begin sensor}
OrientationSensor1.Active:=False; OrientationSensor1.Active:=
botonOrigen.IsPressed:=False; swActivar.IsChecked;
botonInclinacion.IsPressed:=True; Timer1.Enabled:=swActivar.IsChecked;
OrientationSensor1.Active:= end;
swActivar.IsChecked;
Transmisin Bluetooth. Teora
Los dispositivos BlueTooth pueden actuar como Masters o como Slaves (Amos o esclavos). La diferencia es que un
BlueTooth Slave solo puede conectarse a un master y a nadie ms, en cambio un master BlueTooth, puede
conectarse a varios Slaves o permitir que ellos se conecten y recibir y solicitar informacin de todos ellos, arbitrando
las transferencias de informacin ( Hasta un mximo de 7 Slaves).
As pues un nodo BlueTooth puede ser Master o Slave y dispone de una direccin nica, as como de un nombre
para identificarse y muy habitualmente tambin incluye un PIN de conexin o nmero de identificacin que debe
teclearse para ganar acceso al mismo.
Como el BlueTooth lo desarroll Nokia para conectar telfonos mviles, a otros dispositivos como auriculares,
micrfonos o conexiones al audio del coche, existe un procedimiento definido que se llama Pairing (o
emparejamiento) que vincula a dos dispositivos Bluetooth.
Cuando vinculas dos dispositivos BT, se inicia un proceso en el que ellos se identifican por nombre y direccin
interna y se solicitan la clave PIN para autorizar la conexin.
Si el emparejamiento se realiza con xito, ambos nodos suelen guardar la identificacin del otro y cuando se
encuentran cerca se vuelven a vincular sin necesidad de intervencin manual. Por eso el CD de tu coche reconoce el
mvil de tu bolsillo en cuanto te subes y puedes reproducir la msica que tienes en tu Smartphone.
Aunque para que tu BlueTooth pueda enviar o recibir msica, debe aceptar otra norma posterior llamada Advanced
Audio Distribution Profile (A2DP) y que en caso de ser algn sistema antiguo te impedir la reproduccin.
Naturalmente, a lo largo de los aos la norma ha ido variando y existen varias versiones de la misma, con
compatibilidad siempre con las versiones anteriores que se diferencian en la distancia que pueden alcanzar (entre 50
y 100 metros, tericamente y sin obstculos) adems de la velocidad de transferencia.
LOS COMANDOS AT
La transmission serie RS232 solo utilizaba dos hilos de comunicaciones, no haba ms remedio que incorporar una
orden de atencin que significara que a continuacin venia una orden de programacin del modem, que no deba ser
transmitida al otro extremo. Es decir que las ordenes eran del tipo AT+Orden, donde AT era el comando
especificado de atencin y al conjunto de ellas se llam comandos AT. Lisa commandos para HC-06.
COMMAND FUNCTION
AT Test UART Connection
AT+RESET Reset Device
AT+VERSION Query firmware version
AT+ORGL Restore settings to Factory Defaults
AT+ADDR Query Device Bluetooth Address
AT+NAME Query/Set Device Name
AT+RNAME Query Remote Bluetooth Devices
AT+ROLE Query/Set Device Role
AT+CLASS Query/Set Class of Device CoD
AT+IAC Query/Set Inquire Access Code
AT+INQM Query/Set Inquire Access Mode
AT+PSWDAT+PIN Query/Set Pairing Passkey
AT+UART Query/Set UART parameter
AT+CMODE Query/Set Connection Mode
AT+BIND Query/Set Binding Bluetooth Address
AT+POLAR Query/Set LED Output Polarity
AT+PIO Set/Reset a User I/O pin
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg85
Sensores mobile. Bluetooth (versin apaptada de Samples)
Aadir la librera a uses: System.Bluetooth
Y los objetos en la declaracin public:
FBluetoothManager: TBluetoothManager;
FDiscoverDevices: TBluetoothDeviceList;
FPairedDevices: TBluetoothDeviceList;
FAdapter: TBluetoothAdapter;
procedureTForm1.BConectarClick(Sender:TObject); procedureTForm1.BuscarClick(Sender:TObject);
begin begin
ifFBluetoothManager.ConnectionState= AniIndicator1.Visible:=True;
TBluetoothConnectionState.Connectedthen Buscar.Text:='Buscando...';
begin Buscar.Enabled:=False;
ifComboDevices.ItemIndex>1then ComboDevices.Clear;
FAdapter.Pair(FDiscoverDevices[ComboDevices.Item ifFBluetoothManager.ConnectionState=
Index]) TBluetoothConnectionState.Connectedthen
ElseShowMessage('Dispositivonoseleccionado'); begin
end; Label1.Text:='DispositivoBluetooth
end; detectado
"'+FBluetoothManager.CurrentAdapter.AdapterNam
procedureTForm1.BDesconectarClick(Sender: e+'"';
TObject); FBluetoothManager.StartDiscovery(10000);
begin FBluetoothManager.OnDiscoveryEnd:=
ifFBluetoothManager.ConnectionState= ListaDispositivos;
TBluetoothConnectionState.Connectedthen end;
begin end;
ifComboParejas.ItemIndex>1then
FAdapter.UnPair(FPairedDevices[ComboParejas.Item procedureTForm1.ListaDispositivos(const
Index]) Sender:TObject;constADevices:
elseShowMessage('Dispositivoemparejadono TBluetoothDeviceList);
seleccionado'); var
end; I:Integer;
end; begin
Buscar.Text:='Terminado';
procedureTForm1.BEmparejadosClick(Sender: Buscar.Enabled:=True;
TObject); AniIndicator1.Visible:=False;
var FDiscoverDevices:=ADevices;
I:Integer; ComboDevices.Clear;
begin ifComboDevices.Count=1then
ifFBluetoothManager.ConnectionState= ComboDevices.Items.Add('Nohaydispositivos')
TBluetoothConnectionState.Connectedthen else
begin forI:=0toADevices.Count1do
ComboParejas.Clear; ComboDevices.Items.Add(ADevices[I].DeviceName
FPairedDevices:= +'>'+ADevices[I].Address);
FBluetoothManager.GetPairedDevices; ComboDevices.ItemIndex:=0;
ifFPairedDevices.Count>0then end;
forI:=0toFPairedDevices.Count1do
ComboParejas.Items.Add(FPairedDevices[I].DeviceN procedureTForm1.FormShow(Sender:TObject);
ame) begin
else try
ComboParejas.Items.Add('Nohaydispositivos FBluetoothManager:=TBluetoothManager.Current;
emparejados'); FAdapter:=FBluetoothManager.CurrentAdapter;
end; except
end; ShowMessage('Bluetoothnodetectado');
end;
end;
FireMonkey: Manipular objetos3D (versin apaptada de docwiki.embarcadero.com)
4. Escoge: New > Multi-Device / FireMonkey Application > FireMonkey 3D Application
o File > New > Other > Delphi Projects > FireMonkey 3D Application (segn la versin)
5. Aade los siguientes componentes 3D de la Tool Palette al
formulario:
1 TLight de la paleta Scenes
2 TCubes de la paleta Shapes.
procedureTForm4.Form1DCreate(Sender:TObject);//> llamadoeneleventoOncreatedelForm
begin
//inicializatamao:
SpinAncho.Value:=Cube1.Width; //poneelspinanchoalanchodelcubo
SpinAlto.Value:=Cube1.Height; //poneelspinaltoalaltodelcubo
//inicializaposicin
SpinX.Value:=Cube1.Position.X;
SpinY.Value:=Cube1.Position.Y;
SpinZ.Value:=Cube1.Position.Z;
//inicializarotacin
TrackX.Value:=Cube1.RotationAngle.X;
TrackY.Value:=Cube1.RotationAngle.Y;
TrackZ.Value:=Cube1.RotationAngle.Z;
end;
procedureTForm1.SpinAnchoChange(Sender:TObject);
begin
ifsender=SpinAnchothenCube1.Width:=SpinAncho.Value//siesllamadodesdeelspinancho
elseCube1.Height:=SpinAlto.Value; //sinoesqueesllamadodesdeelspinalto
end;
procedureTForm1.SpinXChange(Sender:TObject);
begin
Cube1.Position.X:=SpinX.Value; //posicinxdelcubolaquetengaelSpinX
Cube1.Position.Y:=SpinY.Value; //posicinydelcubolaquetengaelSpinY
Cube1.Position.Z:=SpinZ.Value; //posicinzdelcubolaquetengaelSpinZ
end;
procedureTForm1.TracKXChange(Sender:TObject);
begin
Cube1.RotationAngle.X:=TrackX.Value; //rotacinxdelcubolaquetengaelTrackX
Cube1.RotationAngle.Y:=TrackY.Value; //rotacinydelcubolaquetengaelTrackY
Cube1.RotationAngle.Z:=TrackZ.Value; //rotacinzdelcubolaquetengaelTrackZ
end;
Firemonkey: Introduccin a juego Flappy
Crea un nuevo proyecto llamado Flappy (File > New > Multidevice application)
Creacin de la pantalla de Introduccin:
Asigna el tamao a la ventana: 360 width x 480 Height aprox.
Aadiremos: 3 Imgenes, 1 label, 1 botn y 1 Stylebook.
En el Stylebook, cargaremos el estilo Air de la carpeta Samples (Apply and close).
Al Formulario Form1 le asignaremos ese
Stylebook1
var procedureTGame.Timer1Timer
Game:TGame; const
Desplazatubos:integer; VelocidadTubos=2;//velocidad
factor:single; depasodelostubos
EnemyList:TStringList; var
Score:Integer;//puntuacion R:TLayout;
PajaroFlag:boolean;//variablespermisoparamover I:Integer;
pajaro POffset,WOffset:Integer;
JuegoAcabado:boolean; R1,R2:TRect;//rectangulos
paracolisin
usesuIntro; begin
Game.BeginUpdate;
procedureTGame.FormCreate ifTimer1.Enabled=truethen
begin begin
EnemyList:=TStringList.Create; JuegoAcabado:=False;
factor:=1.5;//factordeescala //sitocasueloseacabael
GameOverLayout.Position.Y:=Game.Height; juego...
end; if(Pajaro.Position.Y+
Pajaro.Height)>Suelo.Position.Y
procedureTGame.FormDestroy(Sender:TObject); then
begin begin
EnemyList.Free; JuegoAcabado:=True;
end; end;
procedureTGame.FormHide(Sender:TObject); ifDesplazatubos=0then
begin begin
Timer1.Enabled:=False; if(Random<0.5)then
Intro.Show; begin
end; WOffset:=round((200*Factor));
end
procedureTGame.FormMouseDown else
Shift:TShiftState;X,Y:Single); begin
begin WOffset:=round((250*Factor));
ifTimer1.enabled=Truethen end;
begin if(Random<0.5)then
ifpajaro.Position.Y<75then begin
begin POffset:=round((125*Factor));
pajaro.Position.Y:=0; end
end else
else begin
begin POffset:=round((25*Factor));
pajaro.Position.Y:=pajaro.Position.Y75; end;
//sube75pixeles
end; R:=TLayout(Tubo.Clone(Self));//clonaelobjetotubo
pajaro.RotationAngle:=0;//miraalfrente EnemyList.AddObject('',R);//aadeelobjetoRala
end; lista
end; R.Parent:=Game;
R.Visible:=True;//muestraelobjetotubo
procedureTGame.ReadyLayoutClick R.Position.X:=Game.Width+R.Width;//loponeala
begin derecha
ReadyLayout.Visible:=False; R.Position.Y:=(0WOffset)+POffset;//posiciona
puntuacion.Visible:=True; arriba+alturaaleatoria
Timer1.Enabled:=True;
end; R:=TLayout(Tubo.Clone(Self));//clonaotroobjeto
tubo
EnemyList.AddObject('',R);//aadeelobjetoRala
lista
R.Parent:=Game;
R.Visible:=True;
R.Position.X:=Game.Width+R.Width;
R.Position.Y:=(Game.HeightR.Height+WOffset)+POffset;
//posicionaabajo+alturaaleatoria
R.RotationAngle:=180;//logira180grados
end;
ifDesplazatubos>(VelocidadTubos*30)then ifJuegoAcabado=TruethenGameOver;
begin end;
Desplazatubos:=0; Suelo.BringToFront;
end puntuacion.BringToFront;
else ifJuegoAcabado=truethen
begin GameOverLayout.BringToFront;
Inc(Desplazatubos);//aumentaeldesplazamiento Game.EndUpdate;
end; end;
//RectanguloR1estadefinidoporelareadelpajaro
R1:= procedureTGame.Puntua(I:Integer);
Rect(Trunc(Pajaro.Position.X),Trunc(Pajaro.Position.Y), begin
Trunc(Pajaro.Position.X+Pajaro.Width),Trunc(Pajaro.Posi Score:=I;
tion.Y+Pajaro.Height)); puntuacion.Text:=IntToStr(Score);
end;
forI:=EnemyList.Count1downto0do
begin procedureTGame.BtnSalirClick(Sender:TObject);
ifAssigned(EnemyList.Objects[I])then begin
begin Game.Close;
R:=TLayout(EnemyList.Objects[I]); Intro.Show;
R.Position.X:=R.Position.X5; end;
//RectanguloR2estadefinidoporelareadeltubo
R2:= procedureTGame.BtnVolverClick(Sender:TObject);
Rect(Trunc(R.Position.X),Trunc(R.Position.Y),Trunc(R. begin
Position.X+R.Width),Trunc(R.Position.Y+R.Height)); game.iniciar;
//sihayinterseccinentrelasdosareas... end;
ifChequeaColision(R1,R2)=Truethen
begin functionTGame.ChequeaColision(R1,R2:TRect;OffSetY
JuegoAcabado:=True; :LongInt=4;OffSetX:LongInt=4):Boolean;
end begin
else //RectanguloR1estadefinidoporelareadelpajaro
begin //RectanguloR2estadefinidoporelareadeltubo
if(((R.Position.X+(R.Width/2))<Pajaro.Position.X) //Detectarsihayintereseccinentrelasdosareas..
AND(R.Tag=1)AND(R.TagFloat=0))then //Automtico:>Result:=IntersectRect(R1,R2);
begin //Manual:>
R.TagFloat:=1; {Result:=(NOT((R1.Bottom(OffSetY*2)<R2.Top+
Puntua(Score+1); OffSetY)or(R1.Top+OffSetY>R2.Bottom(OffSetY*
end; 2))
end; or(R1.Right(OffSetX*2)<R2.Left+OffSetX)
or(R1.Left+OffSetX>R2.Right(OffSetX*2))));}
if(R.Position.X<((R.Width*1)10))then end;
begin
R.DisposeOf; procedureTGame.GameOver;
EnemyList.Delete(I); begin
end; JuegoAcabado:=True;
end; Timer1.enabled:=false;
end; GameOverLayout.BringToFront;
GameOverLayout.Visible:=True;
ifPajaro.RotationAngle<90then Puntuacion.Visible:=False;
Pajaro.RotationAngle:=Pajaro.RotationAngle+5; end;
Pajaro.Position.Y:= procedureTgame.Iniciar;
Pajaro.Position.Y+(Max(Pajaro.RotationAngle,1)/5); var
//(recuerdaponerlibreriamathparausarMax) I:Integer;
ifPajaroFlag=Falsethen R:TLayout;
begin begin
Pajaro.Bitmap.Assign(PajaroB.Bitmap); JuegoAcabado:=False;
PajaroFlag:=True; GameOverLayout.Visible:=False;
end pajaro.Position.X:=96;
else pajaro.Position.Y:=248;
begin pajaro.RotationAngle:=0;
Pajaro.Bitmap.Assign(PajaroA.Bitmap); ReadyLayout.Visible:=True;
PajaroFlag:=False; puntua(0);
end; end;
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg91
Usaremos dbExpress para Conectarse a la Base de Datos. Para las plataformas mviles, dbExpress soporta
InterBase ToGo as como SQLite. Esos productos de bases de datos pueden ejecutarse sobre dispositivos
iOS y Android.
Vamos a crear un archivo de base de datos SQLite usando el FireMonkey Mobile Form Designer
ACrearlabasedeDatosylatablaenelDataExplorer
1. Vaya al Data Explorer, click-derecho en el nodo SQLite y
seleccione Add New Connection:
HacerVisibleelBotnDelete
Seleccione ListBox1 y defina el siguiente manejador
de evento para el evento OnItemClick: ButtonDelete.Visible:=ListBox1.Selected<>nil;
AgregarunaEntradaalaLista
1. Suelte un componente TSQLQuery al formulario.
2. Establecer las siguientes propiedades en el Object Inspector Name a SQLQueryInsert y conecta con
SQLConnection
3. Poner la propiedad SQL como se muestra: INSERT INTO ITEM (Elemento) VALUES (:Elemento)
4. Seleccione el botn Expand (...) sobre la propiedad Params.
Seleccione el parmetro Elemento y poner DataType a ftString.
Probar: Para realizar las pruebas de aadir y eliminar elementos a la lista puedes realizarlas bajo la plataforma
Win32
El registro TPath est declarado en la unidad System.IOUtils, solo necesita agregar System.IOUtils en la
uses clause de su unidad.
procedureTForm1.ShoppingListAfterConnect(Sender:TObject);
begin
ShoppingList.ExecuteDirect('CREATETABLEIFNOTEXISTSItem(ShopItemTEXTNOTNULL)');
end;
Ahora su aplicacin est lista para ejecutarse sobre el simulador o su dispositivo mvil conectado. Para
ejecutar su aplicacin Desarrollo de Apps Mviles con Delphi (iOS y Android) .1. En el Project Manager,
seleccione su plataforma objetivo.
2. Escoja alguno de los siguientes comandos: Run > Run o Run > Run Without Debugging
Procedimientos y funciones bsicas - Delphi (alfabtico)
Abs Returns the absolute value of the argument. FindNext Returns the next entry that matches the name
AnsiCompareStr Performs a case sensitive compare of two and attributes.
strings. FloatToDecimal Converts a floating-point value to a decimal
AnsiCompareText Performs a non-case sensitive compare of representation.
two strings. FloatToStrF Converts the floating-point value to its string
AnsiLowerCase Converts characters to lowercase. representation.
AnsiUpperCase Converts characters to uppercase. FloatToStr Converts the floating-point value to its string
Append Opens an existing file for appending. representation.
AppendStr Adds a given string to an existing string FloatToText Converts the given floating-point value to its
ArcTan Returns the arc tangent of the argument. decimal representation.
AssignCrt Associates a text file with a CRT window. FloatToTextFmt Converts the given floating-point value to its
Assigned Tests to determine if a procedural, pointer, or decimal representation.
Delphi object variable is nil. FmtLoadStr Loads a string from a program's resource string
AssignFile Assigns the name of an external file to a file table
variable. FmtStr Formats a series of arguments and the results
BlockRead Reads one or more records into a variable. are returned in the parameter Result.
BlockWrite Writes one or more records from a variable. Format Formats a series of arguments and returns the
Break Terminates a for, while, or repeat statement. result as a Pascal string.
ChangeFileExt Changes a file's extension. FormatBuf Formats a series of arguments
ChDir Changes the current directory. FormatDateTime Formats a date and time using the specified
Chr Returns a character with a specified ordinal format.
number. FormatFloat Formats the floating-point value using the
CloseFile Closes an open file. format string given by Format.
ClrEol Clears all characters from the cursor position Frac Returns the fractional part of the argument.
to the end of the line without moving the Free Destroys an object instance.
cursor. FreeMem Disposes a dynamic variable of a given size.
ClrScr Clears the screen and returns the cursor to GetDir Returns the current directory of specified drive.
the upper left corner. GetMem Creates a dynamic variable of the specified size
Concat Concatenates a sequence of strings. and puts the address of the block in a pointer
Continue Continues a for, while, or repeat statement. variable.
Copy Returns a substring of a string. GotoXY Moves the cursor to the given coordinates
Cos Returns the cosine of the argument (x is an within the virtual screen.
angle, in radians). Halt Stops program execution and returns to the
Date Returns the current date. operating system.
DateTimeToFileDate Converts the Delphi date format to Hi Returns the high-order byte of the argument.
the DOS date format. High Returns the highest value in the range of the
DateTimeToStr Converts a value from time format to a string. argument.
DateTimeToString Converts a value from time format to a string. Inc Increments a variable.
DateToStr Converts a value from date format to a string. Include Includes an element in a set.
DayOfWeek Returns the current day of the week InitWinCrt Creates the CRT window if it has not already
Dec Decrements a variable. been created.
DecodeDate Decodes the specified date Insert Inserts a substring into a string.
DecodeTime Decodes the specifies time. Int Returns the Integer part of the argument.
Delete Deletes a substring from a string. IntToHex Converts an integer to a hexidecimal
DeleteFile Deletes the given file. IntToStr Converts an integer to a string
DiskFree Returns the amount of free disk space. IOResult Returns the status of the last I/O operation
DiskSize Returns the size of the specified disk. performed.
EncodeDate Returns values specified in date format. IsValidIdent Returns true if the given string is a valid
EncodeTime Returns values specified in time format. identifier.
Eof Returns the end-of-file status. KeyPressed Determines if a key has been pressed on the
Eoln Returns the end-of-line status of a text file. keyboard.
Erase Erases an external file. Length Returns the dynamic length of a string.
Exit Exits immediately from the current block. Ln Returns the natural logarithm of the argument.
Exp Returns the exponential of the argument. Lo Returns the low-order Byte of the argument.
ExpandFileName Expands the given file name. LoadStr Loads the string resource from the application's
ExtractFileExt Returns the file extension. executable file.
ExtractFileName Returns the file name. Low Returns the lowest value in the range of the
ExtractFilePath Returns the complete file path. argument.
FileAge Returns the age of the file. LowerCase Lowercases the given string
FileClose Closes a file. MaxAvail Returns the size of the largest contiguous free
FileDateToDateTime Converts a DOS date format to the block in the heap.
Delphi date format. MemAvail Returns the amount of all free memory in the
FileExists Returns True if file exists. heap.
FileGetAttr Returns file attributes MkDir Creates a subdirectory.
FileGetDate Returns the DOS date-and-time stamp of the Move Copies bytes from source to dest.
file. New Creates a new dynamic variable and sets a
FileOpen Opens a specific file. pointer variable to point to it.
FilePos Returns the current file position of a file. NewStr Allocates a new string on the heap.
FileRead Reads from a specific file. Now Returns the current date and time.
FileSearch Searches through the directories for a specific Odd Tests if the argument is an odd number.
file. Ofs Returns the offset of a specified object.
FileSeek Changes the current position of the file. Ord Returns the ordinal number of an ordinal-type
FileSetAttr Sets file attributes value.
FileSetDate Sets the DOS date-and-time stamp of the file. ParamCount Returns the number of parameters passed to
FileSize Returns the current size of a file. the program on the command line.
FillChar Fills a specified number (count) of contiguous ParamStr Returns a specified command-line parameter.
bytes with a specified value. Pi Returns the value of Pi.
FindClose Terminates a FindFirst/FindNext sequence. Pos Searches for a substring in a string.
FindFirst Searches a directory for a specified file name Pred Returns the predecessor of the argument.
and set of attributes. Ptr Converts a segment base and an offset
address to a pointer-type value.
Ofimega ManualEjerciciosProgramacinDELPHI Revago16 Pg97
Random Returns a random number. StrLIComp Compares two strings, up to a maximum
Randomize Initializes the built-in random number length, without case sensitivity.
generator with a random value. StrLower Converts a string to lower case.
Read For typed files, reads a file component into a StrMove Copies characters from one string to another.
variable. For text files, reads one or more StrNew Allocates a string on a heap.
values . StrPas Converts a null-terminated string to a Pascal-
ReadBuf Inputs a line from the CRT window. style string.
ReadKey Reads a character from the keyboard. StrPCopy Copies a Pascal-style string to a null-
Readln Executes the Read procedure, then skips to terminated string.
the next line of the file. StrPos Returns a pointer to the first occurrence of a
ReAllocMem Deallocates a block from the heap. string in another string.
Rename Renames an external file. StrScan Returns a pointer to the first occurrence of a
RenameFile Renames a file. character in a string.
Reset Opens an existing file. StrRScan Returns a pointer to the last occurrence of a
Rewrite Creates and opens a new file. character in a string.
RmDir Removes an empty subdirectory. StrToDate Coverts a string to a date format.
Round Rounds a real-type value to an Integer-type StrToDateTime Converts a string to a date/time format.
value. StrToFloat Converts the given string to a floating-point
RunError Stops program execution. value.
ScrollTo Scrolls the CRT window to show a screen StrToInt Converts a string to an integer
location. StrToIntDef Converts a string to an integer or the default
Seek Moves the current position of a file to a StrToTime Converts a string to a time format.
specified component. StrUpper Converts a string to upper case.
SeekEof Returns the end-of-file status of a file. Succ Returns the successor of the argument.
SeekEoln Returns the end-of-line status of a file. Swap Swaps the high- and low-order bytes of the
Seg Returns the segment of a specified object. argument.
SetTextBuf Assigns an I/O buffer to a text file. TextToFloat Converts the null-terminated string to a
Sin Returns the sine of the argument. floating-point value.
SizeOf Returns the number of bytes occupied by the Time Returns the current time.
argument. TimeToStr Converts a time format to a string.
SPtr Returns the current value of the SP register. TrackCursor Scrolls the CRT window if necessary to
Sqr Returns the square of the argument. ensure that the cursor is visible.
Sqrt Returns the square root of the argument. Trunc Truncates a real-type value to an Integer-type
SSeg Returns the current value of the SS register. value.
Str Converts a numeric value to a string. Truncate Truncates the file at the current file position.
StrCat Appends a copy of one string to the end of TypeOf Returns a pointer to an object type's virtual
another and returns the concatenated string. method table.
StrComp Compares two strings. UpCase Converts a character to uppercase.
StrCopy Copies one string to another. UpperCase Uppercases the given string.
StrDispose Disposes a string on a heap. Val Converts a string value to its numeric
StrECopy Copies one string to another and returns a representation.
pointer to the end of the resulting string. WhereX Returns the X coordinate of the current cursor
StrEnd Returns a pointer to the end of a string. location.
StrFmt Formats a series of arguments. WhereY Returns the Y coordinate of the current cursor
StrLCat Appends characters from one string to the location.
end of another and returns the concatenated Write For typed files, writes a variable into a file
string. component. For text files, writes one or more
StrIComp Compares two strings without case sensitivity. values to the file
StrLComp Compares two strings, up to a maximum WriteBuf Writes a block of characters to the CRT
length. window.
StrLCopy Copies characters from one string to another. WriteChar Writes a single character to the CRT window.
StrLen Returns the number of characters in Str. Writeln
StrLFmt Formats a series of arguments and the result
contains a pointer to the destination buffer.