power builder
-
Upload
carlos-ronald-manrique-arias -
Category
Documents
-
view
992 -
download
16
Transcript of power builder
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Exportar e Importar Datawindow
Implemente la siguiente Base de datos Universidad
Desarrollar la Siguiente aplicación.
Objeto Datawindow: Dw_Alumnos Tabla : Alumno Tipo: Grid Control Datawindow: Dw_data Command Button: Cb_Registrar Cb_Importar Cb_Exportar Cb_Guardar Cb_Eliminar
Script En el Evento open de la Aplicación: // Profile Venta SQLCA.DBMS = "ODBC" SQLCA.AutoCommit = False SQLCA.DBParm = "Connectstring='DSN=UNiversidad" Connect using SQLCA; If Sqlca.Sqlcode=0 then open(W_Exportar) else Messagebox ("Error de Conexión",Sqlca.SqlErrText) Halt end if
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 2 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Script Open de la Ventana
Dw_data.DataObject="Dw_Alumno"
Dw_data.SetTransObject(Sqlca)
Dw_data.Retrieve()
Script Clicked Para Botón Cb_Exportar
string ls_nombre,ls_archivo TRY if getfilesavename("Guardar Archivo",ls_archivo,ls_nombre,"xls","Archivo de excel(*.xls),*.xls")= 1 then dw_data.saveas(ls_archivo,excel! ,True) MessageBox ("Mensaje","los datos exportados con exito") else MessageBox ("error","los datos no fueron exportados con exito") dw_data.saveas() end if //dw_data.saveas("reporteenexcel.xls",excel! ,false) //MessageBox ("error","datos exportados con exito") CATCH (runtimeerror msg) MessageBox ("error",msg.text) END TRY // Script Clicked Para Botón Cb_Importar
string ls_nombre,ls_archivo TRY GetFileOpenName("Importar archivo",ls_archivo, ls_nombre,"CSV","Archivos (*.CSV),*.CSV") dw_data.ImportFile(ls_archivo) CATCH (runtimeerror msg) MessageBox ("error",msg.text) END TRY //dw_1.ImportFile("reporteenexcel1111.csv")
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1
PRACTICA ESTRUCTURAS REPETITIVAS
Objeto SingleLineEdit:
Name:Sle_numero
Control StaticText:
Name:St_numero
Control CommandButton:
Name:Cb_primeroCb_suma
Ventana Bucles
BUCLE FOR
Script Clicked Para Botón Primeros Nº
integer i,numerostring mnumero=integer(sle_numero.text)if isnumber(sle_numero.text) thenfor i=1 to numerom +=string(i)+ " "nextst_numero.text=string(m)Messagebox("Mostrar",string(m))else
Messagebox("Error","ingrese un Valor Numerico")sle_numero.text=""sle_numero.setfocus()
end if
Script Clicked Para Botón Suma Nº
integer i,numerointeger mif isnumber(sle_numero.text) thennumero=integer(sle_numero.text)for i=1 to numero
m+=inextst_numero.text=string(m)Messagebox("Mostrar",string(M))
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 2
elseMessagebox("Error","ingrese un Valor Numerico")sle_numero.text=""sle_numero.setfocus()
end if
BUCLE WHILE
Script Clicked Para Botón Primeros Nº
integer i,numero,nstring mnumero=integer(sle_numero.text)if isnumber(sle_numero.text) theni=1do while i<=numero
m +=string(i)+ " "n +=i
i+=1loopst_numero.text=string(m)Messagebox("Mostrar",string(m))else
Messagebox("Error","ingrese un Valor Numerico")sle_numero.text=""sle_numero.setfocus()
end ifScript Clicked Para Botón Suma Nºinteger i,numero,nnumero=integer(sle_numero.text)
if isnumber(sle_numero.text) theni=1do while i<=numero
n +=ii+=1
loopst_numero.text=string(n)Messagebox("Mostrar",string(n))else
Messagebox("Error","ingrese un Valor Numerico")sle_numero.text=""sle_numero.setfocus()
end if
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 3
BUCLE UNTIL
Script Clicked Para Botón Primeros Nº
integer i,numero,nstring mnumero=integer(sle_numero.text)if isnumber(sle_numero.text) theni=1do until i > numero
m +=string(i)+ " "n +=i
i+=1loopst_numero.text=string(m)Messagebox("Mostrar",string(m))else
Messagebox("Error","ingrese un Valor Numerico")sle_numero.text=""sle_numero.setfocus()
end if
Script Clicked Para Botón Suma Nº
integer i,numero,nnumero=integer(sle_numero.text)
if isnumber(sle_numero.text) theni=1do until i>numero
n +=ii+=1
loopst_numero.text=string(n)Messagebox("Mostrar",string(n))else
Messagebox("Error","ingrese un Valor Numerico")sle_numero.text=""sle_numero.setfocus()
end if
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 4
PRÁCTICA ESTRUCTURAS DE CONTROL - REPETITIVAS
Objeto SingleLineEdit:
Name:Sle_n
Control ListBox:
Name:Lb_numeros
Control CommandButton:
Name:Cb_LlenarCb_Primo
Ventana Numeros
Script Clicked Para Botón Llenar
integer i,nn=integer(sle_n.text)lb_numeros.reset()if rb_par.checked=true then
for i=2 to n step 2lb_numeros.additem(string(i))
nextelseif rb_impar.checked=true then
for i=1 to n step 2lb_numeros.additem(string(i))
nextend if
Script Clicked Para Botón Nº primo
integer i,n,cn=integer(sle_n.text)lb_numeros.reset()c=0for i=1 to n
if mod(n,1)=0 thenc=c+1lb_numeros.additem(string(i) + ' ' + " " + string(mod(n,i)))
end ifnext
if c<=2 thenst_primo.text=" Es Primo"
elsest_primo.text="No Es Primo"
end if
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1
PRACTICA ESTRUCTURAS CONTROL MULTIPLE
Objeto SingleLineEdit:
Name:Sle_mes
Control StaticText:
Name:St_esta
Control CommandButton:
Name:Cb_visualizar
Ventana EstacionesScript Clicked Para Botón Visualizar
integer messtring msgmes=integer(sle_mes.text)choose case mes
case 1 to 3msg="Verano"case 4 to 6msg="Otoño"case 7 to 9msg="Invierno"case 10 to 12msg="Primavera"case else
messagebox("Error","El mes No existe")st_esta.text=""sle_mes.text=""
end choosest_esta.text=string(msg)
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 2
Ventana Venta de Combustible
Objeto SingleLineEdit:
Name:Sle_total
Control StaticText:
Name:St_cantidadSle_precio
Control ListBox:
Name:Lb_combustible
Script Open Para la Ventana
lb_combustible.additem("Gasolina 97")lb_combustible.additem("Gasolina 95")lb_combustible.additem("Gasolina 90")lb_combustible.additem("Gasolina 84")lb_combustible.additem("Dissel 1")lb_combustible.additem("Dissel 2")
Script Selectionchanged Para Listbox combustible
choose case lb_combustible.selectedindex()case 1
sle_precio.text="15.00"sle_cantidad.text=""sle_cantidad.setfocus()
case 2sle_precio.text="12.00"
sle_cantidad.text=""sle_cantidad.setfocus()
case 3sle_precio.text="10.00"
sle_cantidad.text=""sle_cantidad.setfocus()
case 4sle_precio.text="9.50"
sle_cantidad.text=""sle_cantidad.setfocus()
case 5sle_precio.text="10.20"
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 3
sle_cantidad.text=""sle_cantidad.setfocus()
case 6sle_precio.text="11.00"
sle_cantidad.text=""sle_cantidad.setfocus()
end choose
Script Modified Para SingleLineEdit Cantidad
decimal precio, cantidad,totalprecio=dec(sle_precio.text)cantidad=dec(sle_cantidad.text)total=precio * cantidadst_total.text="S/. " + string(total,"###,###.00")
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
ESTRUCTURAS DE CONTROL
Objeto Datawindow:
Dw_producto
Tabla : Products
Tipo: Freeform
Control Datawindow:
Dw_data
Script Open de la aplicación
Open (W_Contraseña)
Ventana Contraseña
Declaración de variables deInstancia
Script Clicked Para Botón Aceptar
String claveClave = sle_clave.Textt+= 1If clave = "UAP" Then
Open (w_estructura)Close (w_contraseña)
ElseIf t< 3 ThenMessagebox ("Error","La contraseña es incorrecta"+ Char(13) + "N° intentos "
+string( t))sle_clave.Text = ""sle_clave.setFocus()End IfIf t = 3 Then Messagebox("Error","Se acabaron Tus Intentos")close(w_contraseña)End If
End If
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Ventas Northwind
Diseñe la siguiente interfase
para realizar ventas con la
base de datos Northwind.
Al cargar no deberá Mostrar
Nada en los Datawindow.
Al pulsar el Botón nuevo
Cargaran los Datawindow
Respectivos para Registrar
una Nueva venta. Donde
tendrá que agregar el cliente,
la fecha de venta, Luego se
activara el botón agregar.
Luego en el detalle agregar la cantidad y el producto, el precio deberá
mostrar automáticamente
En el detalle se agregar los productos seleccionados.
Luego al registrar la venta tendrá que almacenarse la boleta, la tabla
respectiva y el detalle en la tabla respectiva.
Ala vez se deberá descontar del stock los productos vendidos.
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Formularios Maestro Detalle
Objetos Datawindow:
Name: Dw_categoria
Tabla: Categories
Control Datawindow: Dw_1
Name: Dw_producto
Tabla : Products
Control Datawindow: Dw_2
Script Open de la Ventana
// Cargar Categorias
dw_1.settransobject(sqlca)
dw_1.retrieve()
// Cargar Productos
dw_2.settransobject(sqlca)
dw_2.retrieve()
//llamar el evento Clicked de dw_1
dw_1.triggerevent(clicked!)
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 2 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Declaración de variables de Instancia
Script Clicked del Dw_1
try
fila=dw_1.getitemNumber(GetClickedRow(),1)
dw_2.setfilter("categoryid="+string(fila))
dw_2.filter()
dw_2.setsort("productid asc")
dw_2.sort()
catch (runtimeerror ex)
fila=1
dw_2.setfilter("categoryid="+ string(fila))
dw_2.filter()
end try
Script Clicked Para Botón Nuevo
long n
n=dw_2.rowcount() +1
dw_2.insertrow(n)
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 3 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
dw_2.scrolltorow(n)
dw_2.setfocus()
Script Clicked Para Botón Guardar
Dw_2.modify(“categoryid.visible=0”)
dw_2.setcolumn(5)
dw_2.settext(string(fila))
dw_2.accepttext()
if dw_2.update()<>-1 then
commit;
messagebox("Msg","Datos Guardados Con exito")
else
rollback;
messagebox("Msg","Datos no se Guardaron")
end if
Dw_2.modify(“categoryid.visible=1”)
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1 INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Utilización del Datawindow
Controles DataWindows (dw_1), como
se observa :
Objeto DataWindow Control (Caja
de Herramientas)
El Objeto DataWindow Control se
selecciona del listado de objetos que se
pueden insertar en una ventana,
simplemente haga un clic sobre el
siguiente icono. Luego haga un
clic en la posición de la ventana, donde
desea poner el DataWindow Control.
Pasos 1.- Adjuntar la BD
NORTHWIND en el motor de Base
de dato SQL server, para este caso se hace uso del SQL server.
Pasos 2.- Conecte la base de datos
con Power Builder y configure los
parámetros de inicialización.
Paso 3.- Diseñar el
DataWindow - (File-New-
DataWindow)
- Se elige el estilo de
Presentación: (Elegir el Tipo Free)
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 2 INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Modos de trabajo: (Seleccione
QUICK Select)
El modo de trabajo define como
se trabajara con el Origen de
Datos. Existen 5 tipos de
modos de trabajo.
Al seleccionar Quick SELECT mostrara la siguiente pantalla:
Paso 3.- Seleccione la Tabla
Products
Luego Seleccione los campos de la
Tabla como se muestra a continuación:
Luego pulse ok hasta finalizar el asistente.
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 3 INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Edite las etiquetas como se muestra en la imagen.
Proceda a grabar el objeto DataWindow (almacene en la biblioteca creada y asignarle un comentario, (dw_productos)
Paso 4.- Se agregar un
Control Datawindow En la ventana.
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 4 INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Paso 5.- Haga clic en la
propiedad Dataobject de
Control Datawindow Para
enlazarlo con el objeto datawindow (dw_producto).
Paso 6.- Codificar en la ventana, evento open(), lo siguiente:
//enlazar el control con el objeto transaction
Dw_1.settransobject(sqlca)
//recuperar los registros
Dw_1.retrieve()
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 5 INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Controles Avanzados en Datawindow
Para agregar Controles en un Datawindows (Controles avanzados)
Paso 1.- Deberá entrar a editar el Datawindows.
En la Vista de Diseño Deberá seleccionar el Campo que desea modificar el tipo de control a Usar en el dataWindows.
Paso 2.-Luego Seleccionemos el campo Stock en el Datawindow
En la ventana de propiedades busque la ficha EDIT.
Paso 3.- En la Ficha Edit Busque la Propiedad StyleType y despliegue la Lista y
seleccione Editmask, Luego en Mask determine la cantidad de caracteres que se ingresaran en el campo, active la Propiedad Spin control.
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 6 INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Paso 4.-Luego Seleccionemos el campo Estado en el Datawindow
Paso 5.- En la Ficha Edit Busque la Propiedad
StyleType y despliegue la Lista y seleccione
RadioButtons, Luego active la propiedad 3 D Look,
Columns Across le asigna dos 2, luego en la propiedad Code Table asigna los siguientes valores.
Paso 6.- Para Poder Mostrar la categoría
de los productos y enlazarlo a al
datawindos Producto habrá que crear un
datawindows tipo grid para la tabla
Categories. Proceda a agregar un data
Windows.
Paso 7.- Se elige el estilo de Presentación:
(Elegir el Tipo Grid).
Paso 8.- Seleccione la Tabla Categories
Paso 9.- Luego Seleccione los campos de
la Tabla como se muestra a continuación:
Paso 10.- Luego pulse ok hasta finalizar el
asistente.
Paso 11.- Proceda a grabar el objeto
DataWindow (almacene en la biblioteca
creada y asignarle un comentario,
(dw_categoria)
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 7 INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Luego el datawindows quedara como muestra la imagen.
Para Mejorar la presentación del
datawindows (dw_categoria), se tendrá
que eliminar las etiquetas de la cabecera
y corres un poco el espacio de la cabecera
hasta que quede como la figura, también
el espacio de código de la categoría.
Paso 2.-Luego Seleccionemos el campo Categoria en el
Datawindow(dw_producto)
Paso 3.- En la Ficha Edit Busque la Propiedad
StyleType y despliegue la Lista y seleccione
DropdownDW, en la la propiedad Datawindow
pulse el botón y seleccione el datawindows(dw_categoria).
Luego defina el Display Column (lo que mostrar al
desplegar) en este caso es el Nombre de categoría,
luego el Data Column (loque almacenara al seleccionar) en este caso es el código de categoría.
Para finalizar active la propiedad always Show Arrow(para mostrar siempre la flecha).
para que muestre la
forma siguiente.
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 8 INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Al concluir se mostrara como la imagen.
Agregue los botones respectivos en el pie de página guarde la aplicación y esta lista para
manipularla.
INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Lic. Vladimir Cotaquispe Gutiérrez. 1
Controles de Lista
Objeto Listbox:
Name: Lb_producto
Lb_venta Control DropdownListbox:
Name: Ddlb_producto Control CommandButton:
Name: Cb_agregar Cb_borrar Cb_borrartodo Cb_pasar Cb_regresar Cb_pasartodo Cb_regresartodo
Ventana Sistema de Almacen Script Open de la Ventana
ddlb_producto.additem("Fideos")
ddlb_producto.additem("Arroz")
ddlb_producto.additem("Aceite")
ddlb_producto.additem("Harina")
ddlb_producto.additem("Azucar")
ddlb_producto.additem("Carne")
Script Clicked Para Botón agregar
lb_producto.additem(ddlb_producto.text)
st_n.text=string(lb_producto.totalitems())
Script Clicked Para Botón Pasar
if lb_producto.selectedindex()<0 then
INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Lic. Vladimir Cotaquispe Gutiérrez. 2
Messagebox("Error","Seleccione un Registro")
else
lb_venta.additem(lb_producto.selecteditem())
lb_producto.deleteitem(lb_producto.SELECTEDINDEX())
end if
Script Clicked Para Botón Pasartodo
integer i
for i=1 to lb_producto.totalitems()
lb_producto.selectitem(i)
lb_venta.additem(lb_producto.selecteditem())
next
lb_producto.reset()
Script Clicked Para Botón Borrar
if lb_producto.selectedindex()>0 then
lb_producto.deleteitem(lb_producto.selectedindex())
elseif lb_venta.selectedindex()>0 then
lb_venta.deleteitem(lb_venta.selectedindex())
elseif lb_producto.selectedindex()<0 or lb_venta.selectedindex()<0 then
Messagebox("Error","Seleccione un Registro")
end if
Script Clicked Para Botón Borrartodo
if lb_producto.selectedindex()=-1 and lb_venta.selectedindex()=-1 then
Messagebox("Error","seleccione La lista a eliminar")
Else
INSTITUTO SUPERIOR TECNOLOGICO JHALEBET
Lic. Vladimir Cotaquispe Gutiérrez. 3
if lb_producto.selectedindex()>=1 then
lb_producto.reset()
end if
if lb_venta.selectedindex()>=1 then
lb_venta.Reset()
end if
end if
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Llamados A Las Api’s De Windows Desde Power Builder
Power Builder al igual que otros lenguajes de programación, provee la capacidad de extender las posibilidades del lenguaje tomando funcionalidades que pertenecen al sistema operativo o controles de terceras partes. Este proceso es lo que se llama API (Application Programming Interface). Algunas personas incluyen DLLs que han realizado en C o C++, para usarlos en Power Builder. Pero los mas comunes llamados son los que se hacen a las API del sistema operativo, para que el programador acceda directamente a funciones que desde power builder tocaría desarrollarlas, y el sistema operativo ya las tiene implementadas.
Declaración de funciones externas en PowerBuilder para llamadas a API's de
32bit
Para declarar funciones externas en Power Builder se debe indicar el nombre de la
función, así como los parámetros que recibe y los tipos de datos equivalentes de cada
parámetro en Power Builder; además de la librería DLL que contiene a la función a
declarar.
FUNCTION <Tipo_Dato_Devuelto_Función> <Nombre_Función> (<Tipo_Acceso_Parámetro> <Tipo_Dato_Parámetro> <Parámetro>[,...]) LIBRARY <Librería DLL>
Declaración de funciones externas en PowerBuilders para llamadas a API's de 32bit
Función Devuelve Parámetros que recibe
Librería Ver también
_access Long Ref string filename, int
mode msvcrt.dll
_lclose long Long hfile Kernel32.dll
_lopen long Ref string lsfile, long
fnmode Kernel32.dll
Arc Boolean
ulong hwnd, long r1,
long r2, long r3, long r4,
long a1, long a2, long
a3, long a4
Gdi32.dll
Beep Boolean long freq,long dur Kernel32.dll
BitBlt Long
ulong hDC, long num,
long num, long num,
long num, ulong hDC,
long num, long num,
Gdi32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 2 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
ulong lParam
BringWindowToTop Boolean ulong w_handle User32.dll
Chord Boolean
Chord(ulong hwnd,long
x1,long y1,long x2,long
y2,long r1, long r2, long
r3, long r4
Gdi32.dll
ChooseColorA boolean REF str_ChooseColor
lpcc comdlg32.dll
ChooseFontA boolean REF str_choosefont c comdlg32.dll
CloseHandle Boolean Ulong h Kernel32.dll
CloseHandle Boolean ulong w_handle Kernel32.dll
CloseWindow Boolean ulong w_handle User32.dll
CopyFileA Boolean Ref string cfrom, ref
string cto, boolean flag kernel32.dll
CopyMemory Pb pointer, pb pointer kernel32.dll RtlMoveMem
ory
CreateCompatibleDC Ulong Ulong hDC Gdi32.dll
CreateDirectoryA Boolean Ref string ls_newdir,
ulong lnull kernel32.dll
CreateMutexA Ulong Ulong security,boolean
bowner, string lsname Kernel32.dll
DeleteFileA Boolean Ref string filename kernel32.dll
DeleteObject boolean ulong hgdiobj Gdi32.dll
DestroyWindow Boolean ulong w_handle User32.dll
DllRegisterServer Long c:\windows\
ocxname.ocx
Ellipse Boolean ulong hwnd,long x1,long
y1,long x2,long y2 Gdi32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 3 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
ExitWindowsEx boolean uint dwReserved, uint
uReserved User32.dll
ExpandEnvironmentSt
ringsA Long
REF String lpszSrc, REF
string lpszDest, long
cchDest
kernel32.dll
FatalExit int exitcode Kernel32.dll
FileTimeToLocalFileTi
me boolean
Filetimetolocalfiletime(r
ef str_filedatetime
lpfiletime,ref
str_filedatetime
lplocalfiletime)
Kernel32.dll
FileTimeToSystemTim
e boolean
Str_filedatetime lpt, ref
str_systemtime sts Kernel32.dll
FindClose boolean Long handle kernel32.dll
FindFirstFileA Long Ref string filename, ref
str_filedata filedata kernel32.dll
FindNextFileA Boolean Long handle, ref
str_filedata filedata kernel32.dll
FindWindowA Ulong Ref string c, ref string t User32.dll
FreeLibrary Ulong h kernel32.dll
FreeLibrary ulong libhandle Kernel32.dll
FtpRenameFile boolean
ulong hConnect, ref
string lpszExisting, ref
string lpszNew
wininet.dll
GetBkColor Ulong ulong hwnd Gdi32.dll
GetCapture Ulong User32.dll
GetClassNameA Long ulong hwnd, ref string
cname, int buf User32.dll
GetComputerNameA Boolean GetComputerNameA(ref
string cname,ref long
User32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 4 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
nbuf
GetCurrentDirectoryA ulong Ulong bufferlen, ref
string currentdir Kernel32.dll
GetCurrentThread Ulong Kernel32.dll
GetCursor Ulong User32.dll
GetCursorPos Boolean ref mousepos
mousepos2 User32.dll
GetDC Ulong Ulong hwnd User32.dll
GetDiskFreeSpaceA boolean
Ref string as_dir, ref
long
al_sectorspercluster, ref
long al_bytespersector,
ref long al_freeclusters,
ref long al_totalclusters
Kernel32.dll
GetDiskFreeSpaceExA boolean
Ref string as_dir, ref
str_ularge_long
ast_userfreebytes, ref
str_ularge_long
ast_totalbytes, ref
str_ularge_long
ast_totalfreebytes
Kernel32.dll
GetFileTime boolean
Long hfile, ref
str_filedatetime
lpcreate, ref
str_filedatetime
lpaccess, ref
str_filedatetime lpwrite
Kernel32.dll
GetFileVersionInfoA Boolean
Ref string lpfilename,
ref ulong lpdwhandle,
ulong dwlen, ref string
lpdata
Version.dll
GetFileVersionInfoSiz
eA Ulong
Ref string lpfilename,
ref ulong lpdwhandle Version.dll
GetKeyboardState Boolean ref integer kbarray[256] User32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 5 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
GetKeyState Integer Long al_vk User32.dll
GetLastError Long Kernel32.dll
GetMenu ulong Ulong w User32.dll
GetMenuStringA long Ulong h, ulong i, ref
string s, long m, ulong f User32.dll
GetMinMaxInfo Ref str_minmaxinfo d,
long s, long l kernel32.dll
RtlMoveMem
ory
GetModuleHandleA long string modname Kernel32dll
GetModuleFileNameA long
ulong hModule, ref
string lpFilename, long
nSize
Kernel32.dll
GetObjectBitmap Ulong
ulong hgdiobj, int
cbBuffer, ref s_bitmap
bm
Gdi32.dll GetObjectA
GetParent Ulong ulong hwnd User32.dll
GetPixel Ulong ulong hwnd, long xpos,
long ypos Gdi32.dll
GetShortPathNameA integer
string lpszLongPath,
REF string
lpszShortPath, integer
cchBuffer
Kernel32.dll
GetSubMenu Ulong Ulong w, long p User32.dll
GetSystemMenu boolean ulong mhandle, boolean
flag User32.dll
GetSystemMetrics Integer Integer indexnum User32.dll
GetSystemTime ref systemtime
systimeptr Kernel32.dll
GetTempPathA long long nBufferLength, ref
string lpBuffer Kernel32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 6 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
GetTextExtentPoint32
A boolean
( Ulong h, string s, long
l, ref str_point st Gdi32.dll
GetThreadPriority Integer ulong hthread Kernel32.dll
GetUserDefaultLangID Integer Kernel32.dll
GetUserNameA boolean ref string uname, ref
ulong slength Advapi32.dll
GetVolumeInformatio
nA boolean
Ref string
lprootpathname,ref
string
lpvolumenamebuffer,lon
g nvolumenamesize,ref
uint
lpvolumeserialnumber[2
], ref long
lpmaximumcomponentle
ngth, ref long
lpfilesystemflags,ref
string
lpfilesystemnamebuffer,
long
nfilesystemnamesize
kernel32.dll
GetWindow ulong ulong hwnd, uint fuRel user32.dll
GetWindowsDirectory
A Ulong
ref string wdir, ulong
buf Kernel32.dll
GlobalAlloc ulong ulong uFlags, long
dwBytes kernel32.dll
GlobalFree ulong ulong hMem kernel32.dll
GlobalLock ulong ulong hMem kernel32.dll
GlobalMemoryStatus Ref str_memorystatus
lpbuffer kernel32.dll
GlobalUnlock ulong ulong hMem kernel32.dll
LineTo boolean ulong hwnd,long wx,
long wy Gdi32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 7 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
LoadImageA Ulong
ulong hints, ref string
lpszName, UINT uType,
int cxDesired,int
cyDesired,UINT fuLoad
User32.dll
LoadLibraryA ulong String modname kernel32.dll
MciSendStringA long string cmd, REF string
rtn, long size, long wnd Winmm.dll
MessageBoxA long
ulong hwnd, ref string
text, ref string title,
ulong style
User32.dll
Mouse_Event
ulong dwflag,ulong
dx,ulong dy,ulong
cbutton,ulong dwextra
User32.dll
MoveFileA Boolean Ref string fromfile, ref
string tofile kernel32.dll
MoveToEx Boolean
ulong hwnd,long wx,
long wy,ref prepos
prepos2
Gdi32.dll
MoveWindow boolean
ulong whand,int wx,int
wy,int ww,int
wh,boolean wflag
User32.dll
Pie boolean
ulong hwnd,long x1,long
y1,long x2,long y2,long
x3,long y3,long x4,long
y4
Gdi32.dll
Polygon Boolean hdc, ref struct poly
poly2, int cnt Gdi32.dll
PostMessageA Boolean
ulong hwndle,UINT
wmsg,ulong
wParam,ulong lParam
User32.dll
RasDialA Ulong
ref
str_RasDialExtensions
lstrExt, string
phonebook, ref
str_Rasdialparms rdp,
long notifier, ulong
Rasapi32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 8 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
hwnd, ref ulong hConn
RasDialDlgA Boolean string p, string e, string
n, ref str_rasdialdlg s Rasapi32.dll
RasEnumConnections
A long
ref str_RasConn
lprasconn[], ref long
lpcb, ref long i
Rasapi32.dll
RasEnumEntriesA long
RasEnumEntriesA(string
r, string p, ref
str_rasentryname e[],
ref long lsize, ref long
lentries
Rasapi32.dll
RasGetConnectStatus
A Ulong
ulong hConn, ref
str_Rasstatus rs Rasapi32.dll
RasGetEntryDialPara
msA Long
ref string
lpszPhonebook, ref
str_RasDialParms rdp,
ref boolean lbfPassword
Rasapi32.dll
RasGetErrorStringA Long uint l, ref string s, long c Rasapi32.dll
RasHangUpA Ulong ulong hConn Rasapi32.dll
Rectangle boolean ulong hwnd,long x1,long
y1,long x2,long y2 Gdi32.dll
RegisterWindowMessa
geA Ulong String lpsz User32.dll
ReleaseCapture Boolean User32.dll
RemoveMenu boolean Ulong h, ulong p, ulong f User32.dll DeleteMenu
SendMessageA Long
ulong hwndle,UINT
wmsg,ulong
wParam,ulong lParam
User32.dll
SelectObject ulong ulong hDC, ulong
hGDIObj Gdi32.dll
SetCapture Ulong Ulong a User32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 9 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
SetComputerNameA Boolean ref string cname Kernel32.dll
SetCurrentDirectoryA Boolean Ref string cdir kernel32.dll
SetCursorPos Boolean int cx, int cy User32.dll
SetFocus long objhandle User32.dll
SetKeyboardState boolean ref integer kbarray[256] User32.dll
SetMinMaxInfo Long d, str_minmaxinfo
s, long l kernel32.dll
RtlMoveMem
ory
SetPixel Ulong ulong hwnd, long xpos,
long ypos, ulong pcol Gdi32.dkk
SetThreadPriority Boolean ulong hthread, int
npriority Kernel32.dll
SHBrowseForFolder Long Ref str_browseinfo lpbi Shell32.dll
SHGetPathFromIDList Boolean Ulong pidl, ref string
pszbuffer Shell32.dll
ShowWindow ulong hWind, int
nCmdShow user32.dll
Sleep Long m kernel32.dll
sndPlaySoundA boolean String wavfile, uint flag Winmm.dll
SwapMouseButton Boolean boolean var User32.dll
VerQueryValueA Boolean
Ref string lpblock, string
lpsubblock, ref long
lpbuffer, ref uint pulen
Version.dll
waveOutGetNumDevs Ulong Winmm.dll
WinExec uint ref string filename, uint
wstyle Kernel32.dll
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 10 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Ejemplo: En el script de una ventana la cual va utilizar la función de un DLL
existente. Elegimos Declare y seguidamente elegimos Local External Functions.
Luego
FUNCTION integer SQLAllocEnv(ref long henv) LIBRARY "odbc32.dll"
Usando API
Aquí se ha puesto una serie de llamadas a API's de 32 bits. en general se ha puesto sin
explicación, puesto creo que no las necesitan. Estos ejemplos se obtuvieron de la página
web: http://lonestar.texas.net/~chakes y se ha traducido al castellano.
Ejemplo: Llamadas a API's del entorno de Windows
//Nombre de Equipos
function long GetComputerNameA(ref string equipo, ref ulong
areatrabajo)library "kernel32.dll" alias for "GetComputerNameA;Ansi"
long ll_valor
string ls_equipo , ls_usuario
ulong lul_at1=20
//nombre equipo
ls_equipo=space(lul_at1)
ll_valor=GetComputerNameA(ls_equipo,lul_at1)
st_1.text=ls_equipo
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 11 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
function long GetUserNameA(ref string usuario, ref ulong areatrabajo)library
"advapi32.dll" alias for "GetUserNameA;Ansi"
// usuario
ulong lul_at2=20
ls_usuario=space(lul_at2)
ll_valor=GetUserNameA(ls_usuario,lul_at2)
st_2.text=ls_usuario
//buscador de fichero
FUNCTION long SearchTreeForFile(String RootPath ,String InputPathName,ref
String OutputPathBuffer) LIBRARY "imagehlp.dll" alias for
"SearchTreeForFile;Ansi"
CONSTANT long MAX_PATH = 260
string tempStr,ls_buscar,ls_unidad
long Ret
ls_buscar=sle_buscar.text
ls_unidad=sle_unidad.text
tempStr = space(MAX_PATH)
//'retorna 1 si lo encuentra, 0 si falla en la busqueda
Ret = SearchTreeForFile(ls_unidad,ls_buscar,tempStr)
if ret=1 then
st_ruta.text = tempStr //muestra el path
else
messagebox("Error...","El fichero no encontrado.")
end if
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 1 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Conectarse a SQL Server desde PowerBuilder 10 PowerBuilder desde la versión 10 ya no tiene la opción de configuración de drivers nativos (MSS Microsoft SQL Server) en el DBProfile. Ahora para conectarse "Nativamente" debe utilizar ADO.NET, JDBC, o OLE DB. O si lo prefiere por el tradicional ODBC con sus limitantes de rendimiento conocidas. A continuación le mostramos la manera de conectarse: "Nativamente" por OLE DB a SQL Server.
Abra el Database Profiles: Allí seleccione OLE Microsoft OLE DB y haga click en Nuevo: Luego seleccione en la pestaña conexión: Profile Name --> nombre de la conexiòn Provider --> SQLOLEDB DataSource --> Nombre del Servidor de Base de datos (nombre o IP) User ID --> Nombre del usuario de la base de datos Password --> Clave del Usuario de la base de datos Extended --> Aqui se define la base de datos asi :
Database=NOMBRE_DE_LA_BASE_DE_DATOS
Si deseas utilizar la seguridad integrada de Windows. En la Pestaña Security: Persist Security Info: (activar la casilla) Integrated: SSPI (digitar en la caja de texto)
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 2 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Nos pasamos a la ficha PREVIEW, Probamos la conexión y si es satisfactoria.
Copiamos la línea de conexión.
Normalmente el objeto transacción (transaction) se configura y se conecta cuando se inicia la aplicación, es decir en el open de la aplicación. Para hacer esto abra el objeto aplicación (file/open/aplication) en el evento open donde está el código de abrir la ventana inicial, borrelo y remplace por este código:
Para conectarse desde el PowerScript use la siguiente sintaxis:
// Profile Coneccion
SQLCA.DBMS = "OLE DB"
SQLCA.LogId = "sa"
SQLCA.AutoCommit = False
SQLCA.DBParm = "PROVIDER='SQLOLEDB',DATASOURCE='.',PROVIDERSTRING='Database=Northwind'"
Connect using SQLCA; If Sqlca.Sqlcode=0 then open(W_Buscar) else Messagebox ("Error de Conexión",Sqlca.SqlErrText) Halt end if
Tradicional ODBC con sus limitantes de rendimiento Por ODBC.
Pasos 1.- La BD NORTHWIND se encuentra de forma predeterminada en el motor de Base de dato SQL server, para este caso se hace uso del SQL server.
Pasos 2.- Acceder al panel de control \ Herramientas administrativas \ ODBC \ DSN USUARIO.
Click en el Botón Agregar.
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 3 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Seleccionamos el origen de Datos SQL Server
Activamos las Opciones:
Con la autentificación de Windows NT, mediante el ID de autentificación de Red.
Luego establecer la Base de datos Northwind.
Luego en adelante pulsar siguiente, probar la conexión de Base de datos y luego aceptar.
Pasos 3.- Desde el Entorno del PowerBuilder 10
Ventana DATABASE. Luego obtenemos las siguientes vistas
Power Builder
Lic. Vladimir Cotaquispe Gutiérrez. 4 E.P. DE INGENIERIA DE SISTEMA E INFORMATICA
Agregamos una nueva conexión NEW PROFILE.
Nos pasamos a la ficha PREVIEW, Probamos la conexión y si es satisfactoria.
Copiamos la línea de conexión.
Normalmente el objeto transacción (transaction) se configura y se conecta cuando se inicia la aplicación, es decir en el open de la aplicación. Para hacer esto abra el objeto aplicación (file/open/aplication) en el evento open donde está el código de abrir la ventana inicial, borrelo y remplace por este código:
Para conectarse desde el PowerScript use la siguiente sintaxis:
// Profile Venta
SQLCA.DBMS = "ODBC" SQLCA.AutoCommit = False SQLCA.DBParm = "Connectstring='DSN=venta" Connect using SQLCA; If Sqlca.Sqlcode=0 then open(W_Buscar) else Messagebox ("Error de Conexión",Sqlca.SqlErrText) Halt end if