Académique Documents
Professionnel Documents
Culture Documents
Tutorial Bsico
CONTENIDO
1. 2. 3. 4. 5. 6. 7. Introduccin Software necesario Mi primera aplicacin Controles GUI Personalizados. Bases de Datos Nativas de Palm OS Sitios tiles Bibliografa
2006
EVC Jr.
INTRODUCCIN
Handheld Basic es un lenguaje orientado al desarrollo de aplicaciones administrativas. El mismo posee una sintaxis casi idntica a MS Visual Basic, como as tambin muchos controles GUI necesarios para el desarrollo de cualquier aplicacin. Este tutorial es solo una gua bsica que recopila algunos materiales de la pgina oficial de Handheld Basic, por lo que toda la parte instructiva del tutorial est en ingls. El objetivo del mismo es dar a conocer algunas cuestiones de este nuevo lenguaje y animar a los programadores a utilizarlo y crear nuevas aplicaciones para los PDAs y Handhelds basadas en Palm OS. Por ser un lenguaje nuevo la comunidad de desarrolladores es muy reducida y la documentacin existente es casi nula, la mayora de la informacin y ejemplos disponible se limita a la pgina de HB++. Es por ello que la intencin de esta recopilacin es invitar a los programadores a probar este Entorno de Desarrollo y ayudarnos mutuamente en el maravilloso desafo de crear nuevas aplicaciones.
2006
EVC Jr.
SOFTWARE NECESARIO
Para comenzar a programar con HB++ necesitars descargarte el Palm OS Simulator de la pgina oficial del sistema operativo: www.palmsource.com Para descargarlo tens que registrarte como desarrollador. Posteriormente en la seccin reservada para desarrolladores, debers descargar la versin que simula al Palm OS 5.4 tambin llamado Palm OS Garnet. Luego descargarte de la pgina oficial de HB++: www.handheld-basic.com, la ltima versin de Handheld Basic. Con este software ya estamos en condiciones de comenzar a crear nuestras primeras aplicaciones.
2006
EVC Jr.
MI PRIMERA APLICACIN
Your first application will be made of a text field and a button. Clicking on the button will cause the message "hello world" to appear in the text field. An HB++ application is made up of one or more forms as well as a class describing how the application will handle different launch codes. Don't worry about these: the "Minimal Project" wizard will do everything for you.
Activate the frmMain default form which was automatically created for you:
Then, create a text field click using the appropriate tool in the toolbox:
2006
EVC Jr.
Create a button... It is now possible to modify the properties of the button and the text field. Select the button, then in the property window, change the "Text" property to: "Hello". Now select the form, and define the "Caption" property as: "My First Application".
The design of your form is now complete. It should look like this:
Writing code Now, it is time to write the code handling the user events. Right clicking on a control displays the list of events it can raise. By right clicking on the button, you will see:
2006
EVC Jr.
appears in the code edit window. Enter the following code between the Sub and End Sub declarations: Field1.Text = "hello, world" That's all! Compiling and debugging Click the Compile button or press F5 to compile your project. The output window displays error messages and warnings.
In case your source code has no error, a .prc file is generated... You can install it on your handheld, or use the HB++ integrated debugger. In case you want to use the HB++ integrated debugger, click on the icon to launch the application either in the Palm OS Emulator or on a device connected through a serial cable. At any time you can interrupt the execution by clicking on the button. Then, you enter in the debug mode in which it is possible to view the call stack or error messages generated by your application, add or remove a breakpoint by pressing the F9 key, inspect variables or resume the execution, possibly line by line.
2006
EVC Jr.
Choose Minimal Project, just as shown. The following dialog box appears:
2006
EVC Jr.
You can leave all default values. Click the Next button. Do the same for step 2, just click the Next button. Finally to step 3 click the Finish button without changing anything. Now, we have a minimal project with a form. We have to add a UserControl. To do it, find the window called Project right click on UserControls and choose Add User Control into the contextual menu as shown below:
UserControl1 is now added to your project. You can rename the user control by changing the property name UserControl1 for the following name: Enhanced_Label as shown below:
You can also change the frmMain caption property to Enhanced Label Demo. At this point, the only thing we can expect from our enhanced custom control label is to display itself as a blank rectangle on a form.
2006 EVC Jr.
To continue, double-click on the Enhanced_Label project item you have just added. This item is available in the project window:
Just add the following code for our control enhanced label: Private Sub UserControl_Paint() 'Draw the label border Rectangle 0, 0, Width-1, Height-1, hbRectBorderSolid+hbRectFillSolid End Sub Our new enhanced label control is now created! To test it, draw an occurrence of the enhanced label control onto your main form: Open the main form and click on the tool box to choose the enhanced label control:
Once the Enhanced Label is selected, draw it on the form and launch the emulator. You can keep the default name which is Enhanced_Label1. You'll not see anything, except a blank rectangle:
2006
EVC Jr.
10
Our control is a little bit basic, isn't it? So what we are going to do now is to add the ability to set and display a text string into the control Go back to the Enhanced Label project item (simply double click on it inside the Project Window, User Controls, Enhanced_Label). At the top of the user control code, we declare a private variable called m_strCaption: Private m_strCaption As String m is for Member, str is for String. This convention is useful to know the type and scope of a variable simply from its name. This variable will contain our string shown into the label control. We also add two properties procedures into the code: Public Property Let Caption (ByRef Value as string) End Property Public Property Get Caption () as string End Property The Let Caption procedure property sets the content of our label's caption. The Get Caption procedure property allows us to get the current caption of the label. Now we are going to implement these properties. Add this code into each procedure property: Public Property Let Caption (ByRef Value as string) m_strCaption = Value Repaint End Property Public Property Get Caption () As String Caption = m_strCaption End Property
2006 EVC Jr.
11
Also, we add this code into the two events control Load and Paint: Private Sub UserControl_Load() m_strCaption = "Enhanced Label" End Sub Private Sub UserControl_Paint() 'Draw the label border Rectangle 0, 0, Width-1, Height-1, hbRectBorderSolid+hbRectFillSolid 'Show text in label centered horizontaly and vertically Textout Width/2, Height/2, m_strCaption, hbTextAlignCenter+hbTextAlignVCenter End Sub This is very important here to understand the role of the Load and the Paint events. Load is an event raised when the control is loaded in memory while the Paint event occurs when the control is painted on screen. We define the default value of the caption in the Load event. The default caption will be set to the word Enhanced Label, and will be showed on screen from the Paint event, using the TextOut function. One parameter of the TextOut function is the m_strCaption variable which contains our string. Note that we raise automatically the Paint event by the reserved keyword Repaint called right after a change of the property in the Let Caption procedure. Now we are going to show you how to modify the control's properties programmatically into our project. Add a button to your application in the main form and set its name property to Change_Caption and its Text property to Change Caption. Edit the code for the click event in the editor, and write in this code: Enhanced_Label1.Caption = "Hello" Now when you tap on the Change Caption button, the caption of the label changes to "Hello". In the emulator, you will get this result:
2006
EVC Jr.
12
How does it works exactly ? Actually, when you write this instruction: Label_Enhanced1.Caption = "Hello!" You change the Enhanced_Label Caption property. In the control code you actually make a call to Property Let Caption: Public Property Let Caption (ByRef Value as string) m_strCaption = Value Repaint End Property The private variable m_strCaption is set to the Property Let parameter called Value. Value is passed to set the new caption for our control and is equal to "Hello!" in this case. Note that the member is updated directly, you should always first affect the new value to a private variable declared and visible only from the control code (m_strCaption, for instance). This allows you to perform checks on the new value before changingthe actual property value. Once m_strCaption is set, we raise immediately the Repaint event from our control. This event refreshes the control by repainting it on the screen. Since the user control is repainted, the event UserControl_Paint() is raised, so the control caption will be redrawn with the new value of m_strCaption Private Sub UserControl_Paint() 'Show text in label centered horizontaly and vertically Textout Width/2, Height/2, m_strCaption, hbTextAlignCenter+hbTextAlignVCenter End Sub
2006
EVC Jr.
13
Additionnaly, suppose that you want to accept only 4 characters and no more for your caption, we could add into our Let Property a check before changing the value: Public Property Let Caption (ByRef Value as string) If len(Value) > 4 then MsgBox "Please enter 4 characters only and no more" Exit Sub Else m_strCaption = Value End if End Property And, finally, you can get the actual caption property of the control simply by adding this statement into your Change_Caption Button event: MsgBox Enhanced_ Label1.Caption Actually, you call the Get Caption property of our Enhanced_Label: Public Property Get Caption () As String Caption = m_strCaption End Property >Get Caption simply returns the current caption property of the control which is stored in the m_strCaption private variable. That's all! Once you have assimilated the principle, it's pretty simple to continue our project. Now let's learn how to change the BackColor property of the Enhanced Label
14
Backcolor = m_lngBackcolor 'Draw the label border Rectangle 0, 0, Width-1, Height-1, hbRectBorderSolid+hbRectFillSolid 'Show text in label centered horizontaly and verticaly Textout Width/2, Height/2, m_strCaption, hbTextAlignCenter+hbTextAlignVCenter End Sub This statement will paint the control with the color stored into the m_lngBackcolor variable (The white color, for instance) when your control appears on your form. Since the UserControl_Paint event is raised when you draw your control, the m_lngBackcolor member is initialized with the default background color. But we also want to change programmatically the background color. So let's add two properties, just like we did before to set and get the caption control. However, we now want to set and get the background color of the control, so add those two properties: Public Property Let BackColorLabel (Byval lngValue As Long) m_lngBackcolor = lngValue Repaint End Property Public Property Get BackColorLabel() As Long BackColorLabel = m_lngBackcolor End Property The Drawing color is defined when you call the BackColorLabel property. For example, draw a new button to your form and set its name to "Change_BackColor". Now open the code of its Click event and enter exactly the following statement to set the background color of the label to blue: Enhanced_Label1.BackColorLabel = hbColorBlue (Note that you can use any color constant to set the background color of the label easily) Now, when you start the program and click on the button, the following code is executed: Enhanced_Label1.BackColorLabel = hbColorBlue Actually, you call the Let BackColorLabel property, inside the control code and pass the hbColorBlue value to this property. The blue color is, at first, assigned to our member variable m_lngBackcolor: Public Property Let BackColorLabel (Byval lngValue As Long) m_lngBackcolor = lngValue Repaint End Property Now, m_lngBackcolor has the value hbColorBlue, the blue color. Then, since the Repaint statement is called, the Paint event is raised, allowing us to immediately apply this change to our control by this statement: Backcolor = m_lngBackcolor"
2006 EVC Jr.
15
the control is repainted on the form with its new blue background color. Note that the BackColor reserved word is a property inherited from the display class. Here is the result:
Click on the Change BackColor button, the background color of the label will become blue:
To get the new background color of the control, you can use this statement whenever you want: MsgBox Enhanced_Label1.BackColorLabel
2006
EVC Jr.
16
2006
EVC Jr.
17
Tap on the Change Text Color button, you will get this result:
Now let's see how to add a new feature allowing us to modify the font used in our Enhanced_Label control
18
Public Property Let FontLabel (Byval eFont As HbFont) m_lngFontLabel = eFont Repaint End Property Public Property Get FontLabel () as HbFont FontLabel = m_lngFontLabel End Property Then, add this statement into the Private Sub UserControl_Paint() event handler: Private Sub UserControl_Paint() 'Change the background color Backcolor = m_lngBackcolor 'Change the text color TextColor = m_lngTextcolor 'Change the font used for the label DrawFont = m_lngFontLabel 'Draw the label border Rectangle 0, 0, Width-1, Height-1, hbRectBorderSolid+hbRectFillSolid 'Show text in label centered horizontaly and vertically Textout Width/2, Height/2, m_strCaption, hbTextAlignCenter+hbTextAlignVCenter End Sub Note that the DrawFont reserved word is a property inherited from the Display class. Now, add this line to the Private Sub UserControl_Load() event handler: Private Sub UserControl_Load() m_strCaption = "Label" m_lngBackcolor = hbColorWhite m_lngTextcolor = hbColorBlack m_lngFontLabel = hbFontStandard End Sub Now you can change the font used in our Enhanced Label custom control by setting the FontLabel property using a font constant. Here is an example, you can copy it and paste it into the Click event handler of a button called Change_Font, to set the font of the label to a large font: Enhanced_Label1. FontLabel = hbFontLarge
2006
EVC Jr.
19
Tap on the Change_Font button, the font is modified and is now larger.
20
Constant
hbColorBlack hbColorBlue hbColorCyan hbColorDarkGray hbColorGray hbColorGreen hbColorLightGray hbColorMagenta hbColorOrange hbColorPink hbColorRed hbColorYellow hbColorWhite
Value
&H00000000 &H000000FF &H0000FFFF &H00404040 &H00808080 &H0000FF00 &H00C0C0C0 &H00FF00FF &H00FFC080 &H00FFB0B0 &H00FF0000 &H00FFFF00 &H00FFFFFF 0 0 0 64 128 0 192 255 255 255 255 255 255
Red
0 0 255 64 128 255 192 0 192 176 0 255 255
Green
0 255 255 64 128 0 192 255 128 176 0 0 255
Blue
hbFontBold = 1
hbFontLarge = 2
hbFontLargeBold = 7
hbFontSymbol = 3
hbFontSymbol7 = 5
hbFontSymbol11 = 4
2006
EVC Jr.
21
9 - The complete source code for the Enhanced Label custom control
'============================================================ 'User control declaration section '============================================================ Private m_strCaption As String Private m_lngBackcolor As Long Private m_lngTextcolor As Long Private m_lngFontLabel As HbFont '============================================================ 'Load event handler '============================================================ Private Sub UserControl_Load() m_strCaption = "Enhanced Label" m_lngBackcolor = hbColorWhite m_lngTextcolor = hbColorBlack m_lngFontLabel = hbFontStandard End Sub '============================================================ 'Paint event handler '============================================================ Private Sub UserControl_Paint() 'Change the background color Backcolor = m_lngBackcolor 'Change the text color TextColor = m_lngTextcolor 'Change the font used for the label DrawFont = m_lngFontLabel 'Draw the label border Rectangle 0, 0, Width-1, Height-1, hbRectBorderSolid+hbRectFillSolid 'Show text in label center horizontaly and verticaly Textout Width/2, Height/2, m_strCaption, hbTextAlignCenter+hbTextAlignVCenter End Sub '============================================================ 'Caption property '============================================================ Public Property Let Caption(ByRef Value as string) m_strCaption = Value Repaint
2006 EVC Jr.
22
End Property Public Property Get Caption() as String Caption = m_strCaption End Property '============================================================ 'BackColorLabel property '============================================================ Public Property Let BackColorLabel(Byval lngValue As Long) m_lngBackcolor = lngValue Repaint End Property Public Property Get BackColorLabel() as long BackColorLabel = m_lngBackcolor End Property '============================================================ 'TextColorLabel property '============================================================ Public Property Let TextColorLabel(Byval lngValue As Long) m_lngTextcolor = lngValue Repaint End Property Public Property Get TextColorLabel() as long TextColorLabel = m_lngTextcolor End Property '============================================================ 'FontLabel property '============================================================ Public Property Let FontLabel(ByVal eFont As HbFont) m_lngFontLabel = eFont Repaint End Property Public Property Get FontLabel()as HbFont FontLabel = m_lngFontLabel End Property
2006
EVC Jr.
23
24
End Sub How to manage expansion cards? The StreamFile class allows the manipulation of files stored on external media such as a Secure Digital or MultiMedia cards for example. Dim v as New VFSVolume Dim s as New StreamFile v.FindFirstVolume s.Open v.Reference, "/tmp.txt", hbModeWrite+hbModeCreateAlways Write s, "Hello World !" s.Close Use the StreamFile and the DatabaseInfo classes to copy databases from the handheld device memory to a memory card and vice versa. You can easily implement Backup and Restore functionality in a few lines: Public Function CopyDatabaseToVFS(ByVal iVolRef as Integer, ByRef db as DatabaseInfo) as Integer Dim sf as New StreamFile On Error Goto ERR sf.Open iVolRef, "/" & db.Name & ".prc", hbModeCreateAlways+hbModeReadWrite Write sf, db sf.Close CopyDatabaseToVFS=0 Exit Function ERR: CopyDatabaseToVFS=Err.Number End Function Public function RestoreDatabaseFromVFS(ByVal iVolRef as Integer, ByRef sName as String) as Integer Dim di as New DatabaseInfo Dim sf as New StreamFile On error goto ERR sf.Open iVolRef, sName, hbModeOpenExisting+hbModeReadOnly Read sf, di fd.Close Exit Function ERR: RestoreDatabaseFromVFS=Err.Number End Function How to use graphics? HB++ provides advanced graphics functions. You will find these functions in the Display class and all the classes deriving from it.
2006
EVC Jr.
25
Using double buffering for fluid graphics and animation without flickering is possible :
Private Sub Form_Paint() me.CopyArea 0,20,160,140,myOffscreenBitmap,0,0 End Sub Networking The StreamSocket class implements a standard TCP/IP client socket: Dim objSock as New StreamSocket Dim cmd as String cmd = "GET /MiniBrowser.html HTTP/1.1" & chr(10) & "host: www.handheld-basic.com\n\n" objSock.Connect "www.handheld-basic.com", 80 objSock.Timeout=5000 'send the http query Write objSock, cmd[Len(cmd)] ... You can also use telephony functions to send SMS from a mobile phone connected to your handheld. Notifications and Launch codes You can register various notifcations, in order to implement specific behaviour for your application using the Application class: For example, the following lines tells the system that your app have to be launched with a specific Launch code each time a HotSync operation ends or when the device is started up: RegisterNotify hbNotifySyncFinishEvent RegisterNotify hbNotifyEarlyWakeupEvent Then, each time the HotSync operation ends or when the device is started up, the following method will be called: Private Sub Application_Notify(ByVal eNotify As HbNotify) If eNotify = hbNotifySyncFinishEvent then ' Manage databases operations for example ....
2006 EVC Jr.
26
End if End Sub Using alarm and reminders is also very easy - Add an alarm to your application just with the following line of code: App.Alarm=Now()+3600.0/86400.0 'in one hour Custom launch codes can also be used to enable communications between your app and other applications.
2006
EVC Jr.
27
SITIOS TILES
Manual de HB++ Online: www.handheld-basic.com/documentation/index.html Descarga de HB++: www.handheld-basic.com/dl_try.php Tutoriales Interactivos: www.skinnyfrogsoftware.com/tutorial.htm Fuentes y ejemplos: www.handheld-basic.com/su_samples.php Foro y comunidad: www.handheld-basic.com/forum Palm Source: www.palmsource.com
2006
EVC Jr.
28
BIBLIOGRAFA
Todos los textos troncales de este tutorial han sido sacados de la pgina oficial de HB++. Todos los copyrights y marcas registradas son propiedad de sus respectivos dueos. Este material es solo con fines educativos e informativos.
2006
EVC Jr.
29