Visual Basic

Post on 20-Jan-2016

33 views 2 download

description

Visual Basic. About the Lecturer. Age 24 Professional experience: Two years as a Developer at Intel Corp . 1 year as Web Developer in a small firm. Head of Department in Basmach (computer science school - IDF) in the field of methodology. Now at Technical System Designer in IDF - PowerPoint PPT Presentation

Transcript of Visual Basic

SQA

of 86Slide 1

Visual Basic

SQA

of 86Slide 2

About the Lecturer

• Age 24

• Professional experience:• Two years as a Developer at Intel Corp.

• 1 year as Web Developer in a small firm.

• Head of Department in Basmach (computer science school - IDF) in the field of methodology.

• Now at Technical System Designer in IDF

• Specializing in Teaching:• OO Design Principles

• .NET

• C++

SQA

of 86Slide 3

4. מבוא...............................................014. יסודות.............................................131. פקדים א'.........................................242. תנאים.............................................349. לולאות............................................4 53. מערכים..........................................557. פונקציות.........................................673. פקדים............................................7

SQA

of 86Slide 4

Visual Basic

מבוא

SQA

of 86Slide 5

הכרות עם תכנות מונחה ארועים•

עבודה עם ממשקי משתמש גרפיים•

VBשפת •

מטרת הקורס

SQA

of 86Slide 6

Toolbox

Project Explorerwindow

Properties window

Form

ToolbarMenu bar

סביבת העבודה

SQA

of 86Slide 7

Visual Basic 6התחל את סביבת העבודה •• Start->Programs->Microsoft Visual Studio 6.0-

>Microsoft Visual Basic 6.0Hello.exeצור פרויקט חדש – •" שנמצא בארגז הכלים וגרור Buttonלחץ על פקד הכפתור "•

Formאותו ל-לחץ פעמיים על הכפתור כדי להעלות את עורך הקוד•רשום את הקוד:•

לחץ על כפתור ההפעלה•

תוכנית ראשונה

Private Sub Command1_Click()MsgBox ("Hello world")End Sub

SQA

of 86Slide 8

שפה מונחית ארועים•

קלה לשימוש•

RAD(Rapid Applictionמתאימה ל-•Development)

VBמהי

SQA

of 86Slide 9

•VB משתמשת במושג formכדי להתכוון לחלון

frm. נשמר בקובץ formהמידע על •

בהתאם form מציירת את הVBהמערכת של •למידע הזה

OOP כמו למחלקות בFormsניתן להתייחס ל-•

Forms

SQA

of 86Slide 10

כפתורים, תיבות טקסט, תויות, תיבות סימון.....•

= אלמנט של ממשק משתמשVBפקד של •

חלקם בלתי נראים (כמו טיימר)•

לפקדים יש מאפיינים (לדוגמא צבע רקע)•

שלושה סוגים:•סטנדרטים•

)MSלא סטנדרטים של גורם צד שלישי (כמו •

•ActiveXשנכתבים פנימית

Controls

SQA

of 86Slide 11

– לא שפה מונחית אובייקטים VB ב-OOיש מעט •טהורה

)Formיש אפשרות ליצור אובייקטים (לדוגמא •

תכונה = ערך מידע שמיוחס לאובייקט•

מתודה = משהו שהאובייקט יכול לעשות•

אובייקטים

SQA

of 86Slide 12

OOדוגמא ל

Dim f As Form2Set f = New Form2

f.Show

f.BackColor = RGB(255, 0, 0)

Form2 is a class

f is an object – an instance of class Form2

the Form2 class has a method called show

It has a property called BackColor

SQA

of 86Slide 13

Event-driven programming

GUIגישה סטנדרטית ל•

בניגוד לגישה הישנה (הדפסות על המסך) שבה •התוכנית קבעה מה צריך לקרות

) מה האפליקציה triggers המשתמש קובע (GUIב•תעשה (בעיקר)

): לחיצת מקש, הזזת Eventsדוגמאות לאירועים (• של טיימרtimeoutעכבר,

•Event Handler מתודה שתתבצע כאשר האירוע – קורה

SQA

of 86Slide 14

Visual Basic

יסודות

SQA

of 86Slide 15

Project

פרויקט = קוד בשביל אפליקציה•

•Form חלון – יתכנו מספר בפרויקט אחד =

•Module קוד = VB

•Classהגדרת מחלקות משל עצמנו =

exeהתוצר של הפרויקט הוא .•

SQA

of 86Slide 16

קבצי פרויקט

SQA

of 86Slide 17

VERSION 5.00Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2445 ClientLeft = 5145 ClientTop = 4110 ClientWidth = 5070 LinkTopic = "Form1" ScaleHeight = 2445 ScaleWidth = 5070 Begin VB.CommandButton Command1 Caption = "Command1" Height = 615 Left = 1200 TabIndex = 0 Top = 600 Width = 1815 EndEndAttribute VB_Name = "Form1"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalseOption Explicit

Private Sub Command1_Click()MsgBox ("Hello world")

End Sub

Inside a .frm file

SQA

of 86Slide 18

Visual Basic

משתנים

SQA

of 86Slide 19

Variables

לכל משתנה בתוכנית מוקצה טיפוס נתונים•

כדי להצהיר על הטיפוס של Dimהשתמשו ב•המשתנה

• Dim x as Integer

• Dim x,y as Integer NO!

•Case sensitive)בערך(

משפט השמה•

X = 4

SQA

of 86Slide 20

Variables

ניתן להשתמש במשתנה גם אם לא הגדרנו VBב•אותו (לא מומלץ) אלא אם נוסיף את הפקודה

Option Explicit

הגדרת קבועים•

Private const MyInt As Integer = 5

Stringכדי להחזיק מחרוזות השתמשו בטיפוס •

Dim flower As String

SQA

of 86Slide 21

טיפוסים

• Integer Long • Single Double • Currency• Byte unsigned 0 - 255• String• Boolean• Date• Object• Variant - do not use except explicit reason

SQA

of 86Slide 22

Variant

יכול להכיל כל סוג של מידעVariantהטיפוס •

ניתן לדעת מה טיפוס המידע בזמן ריצה ע"י •VarTypeDim x As Variant

x = 1MsgBox (VarType(x))

SQA

of 86Slide 23

VarTypeערכי 0 Empty (uninitialized)1 Null (no valid data)2 Integer3 Long integer4 Single-precision floating-point number5 Double-precision floating-point number6 Currency value7 Date value8 String9 Object10 Error value11 Boolean value12 Variant (used only with arrays of variants)13 A data access object14 Decimal value17 Byte value36 Variants that contain user-defined types8192 Array

SQA

of 86Slide 24

Operator operation Basic expression

^ Exponentiation A ^ B

* Multiplication A * B

/ Division A / B

+ Addition A + B

- Subtraction A - B

פעולות אריתמטיות

SQA

of 86Slide 25

שרשור

ניתן לשרשר שתי מחרוזות בעזרת אופרטור השרשור •&

Private Sub cmdConcatenation_Click()Dim strVar1 As StringDim strVar2 As StringDim result As StringstrVar1 = “Hello”strVar2 = “World”result = strVar1 & strVar2

End Sub

SQA

of 86Slide 26

HEXהערות, המשך שורה ו

הערות מתחילות עם גרש ', וממשיכות עד לסוף •השורה

'this line is a comment

ביטוי ארוך מאוד ניתן לפצל לשורות בעזרת •קו-תחתון _

כדי להמשיך לשורה הבאה

HFF0012&קבועים הקסה-דצימלים נכתבים בצורה: •

SQA

of 86Slide 27

Visual Basic

המרות

SQA

of 86Slide 28

Conversion function Converts an expression to

Cbool Boolean

Cbyte Byte

Ccur Currency

Cdate Date

CDbl Double

Cint Integer

CLng Long

CSng Single

CStr String

Cvar Variant

CVErr Error

DIM x as integerx = Cint("10")

המרות

SQA

of 86Slide 29

Form properties

SQA

of 86Slide 30

Controls and properties

SQA

of 86Slide 31

Visual Basic

1פקדים – חלק

SQA

of 86Slide 32

הפקדים השימושיים ביותר

• Text Boxes

• Labels

• Command Buttons

• Picture Boxes

SQA

of 86Slide 33

TextBox

לחצו פעמיים על תיבת הטקסט בארגז הכלים כדי •להוסיף לחלון

)F4הפעילו את חלון המאפיינים (ע"י לחיצה על •

הציבו ערכים במאפיינים של תיבת הטקסט•

SQA

of 86Slide 34

TextBox

Text box

SQA

of 86Slide 35

מאפיינים חשובים

• Name

• Caption

• Border style

• Visible

• Back Color

• Alignment

• Font

SQA

of 86Slide 36

.מחרוזתיהתוכן של תיבות טקסט הוא תמיד •

גם מספרים מאוחסנים בתיבות טקסט בתור •מחרוזת.

מכאן נובע שצריך להמיר את המחרוזת של תיבת •הטקסט לפני שמשתמשים בה כמספר

•Val (txtBox.Text) משנה את מחרוזת הקלט למספר

numVar = Val (txtBox.Text)

txtBox.Text = Str(numVar)

שימוש בתיבות טקסט לקלט ופלט

SQA

of 86Slide 37

Object Prefix Example

Command Button cmd cmdStart

Form frm frmPayroll

Label lbl lblName

Picture box pic picClouds

Text box txt txtAddress

חוקים בנתינת שמות

SQA

of 86Slide 38

Private Sub Command1_Click()Dim num1 As IntegerDim num2 As IntegerDim result As Integernum1 = val(Text1.Text)num2 = val(Text2.Text)result = num1 + num2Label1.Caption = str(result)End Sub

Example - calculator

SQA

of 86Slide 39

תרגיל

הוסיפו למחשבון תמיכה בחיסור, כפל, וחילוק•

התעלמו מספרים לא חוקיים וחלוקה באפס – •נתייחס לזה בהמשך

SQA

of 86Slide 40

במקום input boxעבור קלט בודד ניתן להשתמש ב•תיבת טקסט

•Input Box הוא תיבת דיאלוג מוגדרת מראש

• Input Box is a predefined dialog box.

תחביר:•

stringVar = InputBox (prompt, title)

קלט מתיבת קלט

SQA

of 86Slide 41

Private Sub cmdDisplay_Click()

Dim fileName As String

fileName = InputBox("Enter the name of the file containing the information.", "Name of File")

End Sub

After executing an inputbox would pop up

Input Boxדוגמא ל-

SQA

of 86Slide 42

Visual Basic

תנאים

SQA

of 86Slide 43

If c > 5 Then x = 1 y = 3End If

If c > 5 Then x = 1: y = 3

If c > 5 Then x = 1 y = 3Else z = 7End If

If c > 5 Then x = 1 y = 3ElseIf c = 4 Then z = 7Else x = 9End If

IFמשפט

SQA

of 86Slide 44

תרגיל – פיתרון משוואה ריבועית

עם:formצרו • a,b,c תיבות טקסט שיכילו את ערכי 3•

תויות שבהן התוצאות יוצגו2•

כפתור בשם "פתור" – הקוד שמשויך לכפתור יפתור את המשוואה•

sqr* פונקציה לשורש היא

a

acbbx

2

42

SQA

of 86Slide 45

Dim Number Number = 8 ' Initialize variable. Select Case Number ' Evaluate Number.

Case 1 To 5 ' Number between 1 and 5, inclusive. x=4Case 6, 20, 8 ' Number is 6 or 20 or 8. x=5Case 9 To 10 ' Number is 9 or 10. x=6Case is<0X=7Case Else ' Other values. x=8

End Select

select

SQA

of 86Slide 46

Visual Basic

טיפול בשגיאות

SQA

of 86Slide 47

•Exceptionבעיה שעולה בזמן ריצה =

I/O בד"כ קשורה ל-•

לדוגמא:קובץ שלא נמצא, בעית חיבור לשרת, •קלט שגוי של המשתמש

לא באג תיכנותי•

•VBקורא ל exception- בשם error

Error and exception handling

SQA

of 86Slide 48

Private Sub Command1_Click()Dim num1 As IntegerDim num2 As IntegerDim result As Integer

On Error GoTo myErrorHandlernum1 = Text1.Textnum2 = Text2.Textresult = num1 + num2Label1.Caption = resultExit Sub

myErrorHandler:If Err.Number = 13 Then MsgBox ("Please enter a valid number")Else MsgBox (Err.Description)End IfResume Next

End Sub

תרגיל

הוסיפו טיפול בשגיאות במחשבון שלכם

(11טפלו בבעית החלוקה באפס)

דוגמא לטיפול בשגיאות – מספרים לא חוקיים

SQA

of 86Slide 49

Visual Basic

לולאות

SQA

of 86Slide 50

Dim x as Integer, total As Integertotal = 0For x = 1 To 5 total = total + xNext

Dim x as Integer, total As Integertotal = 0For x = 1 To 5 Step 2 total = total + xNext

For next loops

SQA

of 86Slide 51

Do While name<>”סוף”name = InputBox)“הקלד את שמך או סוף כדי לצאת”(if name<>”סוף” Then Print name

Loop

Do while

Do name = InputBox)“הקלד את שמך או סוף כדי לצאת”(if name<>”סוף” Then Print name

Loop While name<>”סוף”

SQA

of 86Slide 52

Dim c As Integerc = 1Do While c < 5 c = c + 1Loop

Dim c As Integerc = 1Do Until c >4 c = c + 1Loop

Dim c As Integerc = 1Do c = c + 1Loop While c < 5

Dim c As Integer, x as integerc = 1x=2Do c = c + 1Loop Until c>4 And x<>3

לולאות נוספות

SQA

of 86Slide 53

Visual Basic

מערכים

SQA

of 86Slide 54

Dim x(100) As IntegerDim i As IntegerFor i = 0 To 100 x(i) = 99Next

Dim x(1 To 3, 1 To 3) As IntegerDim i as integer, j As IntegerFor i = 1 To 3 For j = 1 To 3 x(i, j) = 99 NextNext

מערכים בעלי גודל קבוע

SQA

of 86Slide 55

Dim x() As IntegerReDim x(5)

Dim i, j As IntegerFor i = 1 To 5 x(i) = 99Next

ReDim Preserve x(10)For i = 6 To 10 x(i) = 100Next

מערכים דינמיים

אומר למערכת

לשמור את הערכים שהיו

SQA

of 86Slide 56

• Debug.print x,y,z

• Immediate window – CTRL G

– תרגילכתבו תוכנית שתדפיס באמצעות לולאת

FOR את הסכום של כל המספרים . השתמשו בהדפסת 9 עד 1האי-זוגיים מ

Debug

Debugging – debug.print

SQA

of 86Slide 57

Visual Basic

סברוטינות ופונקציות

SQA

of 86Slide 58

Private Sub Command1_Click)(Dim x, y As Doublex = 1y = 2Debug.Print addUp)x, y(

End Sub

Private Function addUp)a as double, b As Double(addUp = a + bEnd Function

x and y copied to a and b

פונקציות

SQA

of 86Slide 59

Rnd Returns a number between 0 and 1.(excluding 1)

Sqr(n) Returns the square root of a number.

Round(n,r) The number n is rounded to r decimalplaces.

Int(n) Returns the largest integer less thanor equal to a number

פונקציות נומריות

SQA

of 86Slide 60

Private Sub cmdEvaluate_Click()

Dim n As Single

Dim root As Single

picResults.Cls

n = 6.76

root = Sqr(n)

picResults.Print root; Int(n); Round(n,1)

End Sub

דוגמא

SQA

of 86Slide 61

Private Sub Command1_Click()Dim x As Double, y As Doublex = 1y = 200Call bigger(x, y)End Sub

Private Sub bigger(first As Double, second As Double)If first > second Then Debug.Print firstElse Debug.Print secondEnd IfEnd Sub

Functions return values

Procedures do not – they just do something

סברוטינות = פונקציות ללא ערך החזר

SQA

of 86Slide 62

ניתן להעביר פרמטרים בשתי צורות••By value

•By reference

העברת פרמטרים

SQA

of 86Slide 63

מעתיקים את By Valueפרמטרים המועברים •התוכן שלהן לפונקציה

שינוי ערך בפונקציה לא משפיע על המשתנים •המקוריים

יוצר משתנים נוספים – דבר המשפיע על הזיכרון •(משמעותי במערכים גדולים)

VBזוהי ברירת המחדל ב•

By valueהעברת פרמטרים -

SQA

of 86Slide 64

הכתובת של הפרמטרים מועברים לפונקציה•

שינוי של ערך בפונקציה גורם לשינוי במשתנים •המקוריים

חוסך בזיכרון ומהיר יותר•

מסוכן יותר•

כדי להשתמש בשיטה זו יש לרשום ליד הפרמטר •ByRef

By referenceהעברת פרמטרים -

SQA

of 86Slide 65

Private Sub Command1_Click)(Dim x As Double, y As Doublex = 1y = 200Call swap)x, y(Debug.Print x, yEnd Sub

Private Sub swap)ByRef first As Double, ByRef second As Double(Dim temp As Doubletemp = firstfirst = secondsecond = tempEnd Sub

by referenceהעברה

SQA

of 86Slide 66

Private Sub Command1_Click()Dim x As Double, y As Doublex = 1y = 2Debug.Print addUp(second:=x, first:=y)End Sub

Private Function addUp(first As Double, second As Double)addUp = firstEnd Function

Named arguments

SQA

of 86Slide 67

Visual Basic

מודולים

SQA

of 86Slide 68

קבצים נפרדים•

מכילים פונקציות, פרוצדורות ומשתנים גלובלים•

אחדformמשמש לקוד ומידע שזקוקים לו ביותר מ•

Modules

SQA

of 86Slide 69

Module example

SQA

of 86Slide 70

משתנים צריכים להיות לוקליים עד כמה שאפשר

Scope חלק בתוכנית שבו ניתן :לפנות למשתנה

Scope – public private dim

SQA

of 86Slide 71

•DIMלוקלי לסברוטינה – כל עוד הסברוטינה רצה –

•Privte\Public על FORMכל עוד ה – FORMפתוח

•Publicבמודול – כל עוד האפליקציה רצה

•Static לוקלי לסברוטינה – שומר ערכו בין ריצות – של הסברוטינה – חי עד סוף התוכנית

זמן חיים – כמה זמן משתנה חי

SQA

of 86Slide 72

Visual Basic

פקדים - חלק ב'

SQA

of 86Slide 73

יישור הפקדים

SQA

of 86Slide 74

Scrollbar control

SQA

of 86Slide 75

Label1

ScrollBar1

Label2 Picture1

Private Sub VScroll1_Change()Picture1.BackColor = RGB(0, 0, VScroll1.Value)Label2.Caption = "Colour is 0, 0, " & VScroll1.ValueEnd Sub

Scrollbarדוגמא לשימוש ב-

SQA

of 86Slide 76

נוספים לירוק ואדוםscrollbarsהוסיפו •

תרגיל

SQA

of 86Slide 77

Radio buttons

SQA

of 86Slide 78

Checkboxes

SQA

of 86Slide 79

Listbox

SQA

of 86Slide 80

Tab Control הוספה -

SQA

of 86Slide 81

Tab Control שימוש -

SQA

of 86Slide 82

• Hidden control

• Interval

• Tick event

• Enabled or not

Timer

SQA

of 86Slide 83

Private Sub Timer1_Timer()Dim currentTime As DatecurrentTime = Now()Label1.Caption = currentTimeEnd Sub

דוגמא לטיימר - שעון

SQA

of 86Slide 84

כתבו תוכנית שעושה אנימציה של כדור שזז על •המסך

וטיימרshapeהשתמשו בפקד של •

הזיזו את הצורה:tickכל פעם שיש •

Shape.left – shape.lest+speed

תרגיל טיימר

SQA

of 86Slide 85

ניתן לצרף מספר פקדים מאותו סוג כמערך •פקדים

בצורה כזו נוכל לשתף קוד שיהיה תקף לכולם •ונוכל לזהות איזה הופעל ע"י אינדקס.

כדי ליצור מערך פקדים יש להעתיק ולהדביק •את הפקד הראשון

מערך פקדים

SQA

of 86Slide 86

Backup

SQA

of 86Slide 87

מאפשרת לשים תמונה בחלון שלנו•מאפיינים חשובים•

•Pictureמכיל את שם הקובץ שיש להציג –

•Srrech אם שלילי התיבה תתאים את עצמה לתמונה ואם – חיובי התמונה תתאים את עצמה לתיבה

מאפשרת לנו לטעון תמונה LoadPictureמתודת •

תיבת תמונה

SQA

of 86Slide 88

התחל פרויקט חדש והוסף למסך תיבת תמונה אחת1)

כתובת של קובץ תמונה Pictureהצב בתוך המאפיין 2) C:\Program Files\Microsoft(ניתן למצוא תמונות ב

Visual Studio\Common\Graphics\Bitmaps(

בדוק מה קורה כאשר מותחים את תיבת התמונה3)

תיבת תמונה - דוגמא

SQA

of 86Slide 89

מאפשר למשתמשים לבחור כונן בזמן ריצה•

מאפיינים חשובים••Driveכולל את שם הכונן שכרגע נבחר –

פקד רשימת כוננים

SQA

of 86Slide 90

מציג למשתמשים רשימה של תיקיות•

מאפיינים חשובים••Pathהכתובת של התיקיה הנוכחית שאנחנו עובדים בה –

פקד רשימת תיקיות

SQA

of 86Slide 91

מציג למשתמשים רשימה של קבצים•

מאפיינים חשובים••Pathהכתובת של התיקיה הנוכחית שאנחנו עובדים בה –

•FileNameשם הקובץ הנבחר –

•Patternמחרוזת עם תבנית של קבצים שיש להציג – dat יציג רק בצים עם סיומת dat*.לדוגמא:

פקד רשימת קבצים

SQA

of 86Slide 92

dirExampleנניח ויש לנו פקד תיקיות בשם • drvExample פקד כוננים בשם

filExampleופקד קבצים בשם

• dirExample.Path = drvExample.Drive• filExample.Path = dirExample.Path• filExample.Path = dirExample.Path

סינכרון הכוננן, תיקיה וקובץ

SQA

of 86Slide 93

Dim YourFile as String If Right(filExample.Path,1) = "\" Then YourFile = filExample.Path + filExample.FileName Else YourFile = filExample.Path + "\" + filExample.FileName End If imgExample.Picture

בחירת תמונה בצורה דינמית

SQA

of 86Slide 94

צור תוכנית שתתן אפשרות לבחור תמונה ותציג אותה

תרגיל – הצגת תמונות