CADCAM HANDLEIDING DEEL IV



Vergelijkbare documenten
MyDHL+ Van Non-Corporate naar Corporate

Firewall van de Speedtouch 789wl volledig uitschakelen?

SAMPLE 11 = + 11 = + + Exploring Combinations of Ten + + = = + + = + = = + = = 11. Step Up. Step Ahead

Introductie in flowcharts

2019 SUNEXCHANGE USER GUIDE LAST UPDATED

B1 Woordkennis: Spelling

Preschool Kindergarten

Add the standing fingers to get the tens and multiply the closed fingers to get the units.

Settings for the C100BRS4 MAC Address Spoofing with cable Internet.

ANGSTSTOORNISSEN EN HYPOCHONDRIE: DIAGNOSTIEK EN BEHANDELING (DUTCH EDITION) FROM BOHN STAFLEU VAN LOGHUM

Group work to study a new subject.

MyDHL+ ProView activeren in MyDHL+

My Inspiration I got my inspiration from a lamp that I already had made 2 years ago. The lamp is the you can see on the right.

Tentamen Objectgeorienteerd Programmeren

FOR DUTCH STUDENTS! ENGLISH VERSION NEXT PAGE. Toets Inleiding Kansrekening 1 8 februari 2010

Het beheren van mijn Tungsten Network Portal account NL 1 Manage my Tungsten Network Portal account EN 14

Functioneel Ontwerp / Wireframes:

The first line of the input contains an integer $t \in \mathbb{n}$. This is followed by $t$ lines of text. This text consists of:

Basic operations Implementation options

!!!! Wild!Peacock!Omslagdoek!! Vertaling!door!Eerlijke!Wol.!! Het!garen!voor!dit!patroon!is!te!verkrijgen!op! Benodigdheden:!!

ALGORITMIEK: answers exercise class 7

Shipment Centre EU Quick Print Client handleiding [NL]

EM7680 Firmware Update by OTA

Hoe te verbinden met NDI Remote Office (NDIRO): Apple OS X How to connect to NDI Remote Office (NDIRO): Apple OS X

Data Handling Ron van Lammeren - Wageningen UR

Activant Prophet 21. Prophet 21 Version 12.0 Upgrade Information

z x 1 x 2 x 3 x 4 s 1 s 2 s 3 rij rij rij rij

After that, the digits are written after each other: first the row numbers, followed by the column numbers.

Classification of triangles

Engels op Niveau A2 Workshops Woordkennis 1

ATOS Viewer for Dental Frameworks User Manual

RECEPTEERKUNDE: PRODUCTZORG EN BEREIDING VAN GENEESMIDDELEN (DUTCH EDITION) FROM BOHN STAFLEU VAN LOGHUM

ETS 4.1 Beveiliging & ETS app concept

General info on using shopping carts with Ingenico epayments

Eye Feature Detection Towards Automatic Strabismus Screening

Illustrator Tutorial - How to Create a Watch

Quality requirements concerning the packaging of oak lumber of Houthandel Wijers vof ( )

Deel 1: schriftelijk deel

Procedure Reset tv-toestellen:

Luister alsjeblieft naar een opname als je de vragen beantwoordt of speel de stukken zelf!

Comics FILE 4 COMICS BK 2

Concept of Feedback. P.S. Gandhi Mechanical Engineering IIT Bombay

It s all about the money Group work

How to install and use dictionaries on the ICARUS Illumina HD (E652BK)

Read this story in English. My personal story

L.Net s88sd16-n aansluitingen en programmering.

Borstkanker: Stichting tegen Kanker (Dutch Edition)

(1) De hoofdfunctie van ons gezelschap is het aanbieden van onderwijs. (2) Ons gezelschap is er om kunsteducatie te verbeteren

Lists of words from the books, and feedback from the sessions, are on

Four-card problem. Input

Stars FILE 7 STARS BK 2

MyDHL+ Exportzending aanmaken

DALISOFT. 33. Configuring DALI ballasts with the TDS20620V2 DALI Tool. Connect the TDS20620V2. Start DALISOFT

FOR DUTCH STUDENTS! ENGLISH VERSION NEXT PAGE. Toets Inleiding Kansrekening 1 7 februari 2011

Handleiding Installatie ADS

FOR DUTCH STUDENTS! ENGLISH VERSION NEXT PAGE

Interaction Design for the Semantic Web

The upside down Louisa tutorial by Dorothée: Noortjeprullemie.blogspot.be Written for Compagnie M.: m.com

FOR DUTCH STUDENTS! ENGLISH VERSION NEXT PAGE

MyDHL+ Duties Taxes Paid

Het handboek van KDE Screen Ruler. Lauri Watts Vertaling van het handboek: Niels Reedijk Vertaler/Nalezer: Alexander S. Koning

MyDHL+ Dangerous Goods

Appendix A: List of variables with corresponding questionnaire items (in English) used in chapter 2

CHROMA STANDAARDREEKS

FOR DUTCH STUDENTS! ENGLISH VERSION NEXT PAGE. Toets Inleiding Kansrekening 1 22 februari 2013

Chromosomal crossover

GS1 Data Source. Guide to the Management of Digital Files for Suppliers

Handleiding Zuludesk Parent

Calculator spelling. Assignment

Hoe met Windows 8 te verbinden met NDI Remote Office (NDIRO) How to connect With Windows 8 to NDI Remote Office (NDIRO

L.Net s88sd16-n aansluitingen en programmering.

De grondbeginselen der Nederlandsche spelling / Regeling der spelling voor het woordenboek der Nederlandsche taal (Dutch Edition)

The genesis of the game is unclear. Possibly, dominoes originates from China and the stones were brought here by Marco Polo, but this is uncertain.

FAAC DRIVER. Driver install procedure for FAAC boards. Installatieprocedure voor driver voor FAAC-kaarten.

Opgave 2 Geef een korte uitleg van elk van de volgende concepten: De Yield-to-Maturity of a coupon bond.

OPEN TRAINING. Onderhandelingen met leveranciers voor aankopers. Zeker stellen dat je goed voorbereid aan de onderhandelingstafel komt.

GS1 Data Source. Guide to the management of digital files for data suppliers and recipients

Main language Dit is de basiswoordenschat. Deze woorden moeten de leerlingen zowel passief als actief kennen.

LONDEN MET 21 GEVARIEERDE STADSWANDELINGEN 480 PAGINAS WAARDEVOLE INFORMATIE RUIM 300 FOTOS KAARTEN EN PLATTEGRONDEN

1. Voor het installeren wordt geadviseerd een backup te maken van uw database en bestanden.

Zo werkt het in de apotheek (Basiswerk AG) (Dutch Edition)

Find Neighbor Polygons in a Layer

/ /

A2 Workshops Grammatica Heden

Plotten. technisch tekenwerk AUTOCAD 2000

Programmeren. Cursus Python

Leeftijdcheck (NL) Age Check (EN)

Handleiding Digipass DP310

0515 DUTCH (FOREIGN LANGUAGE)

Today s class. Digital Logic. Informationsteknologi. Friday, October 19, 2007 Computer Architecture I - Class 8 1

S e v e n P h o t o s f o r O A S E. K r i j n d e K o n i n g

EM7580 Firmware Update by Micro SD card

Systeem Wand Samenstellings Applicatie. Cabinet configuration tool. Nederlandse handleiding

The Future of Publishing MediaLAB Amsterdam Create-IT Applied Research University of Amsterdam. Version 1 Test plan phase 2.

OUTDOOR HD BULLET IP CAMERA PRODUCT MANUAL

LDA Topic Modeling. Informa5ekunde als hulpwetenschap. 9 maart 2015

01/ M-Way. cables

ICARUS Illumina E653BK on Windows 8 (upgraded) how to install USB drivers

Travel Survey Questionnaires

Transcriptie:

TUTORIALS / MANUAL CTW CADCAM HANDLEIDING DEEL IV DESIGN AUTOMATION H. Tragter AUGUSTUS 2011 COURSE ID: 191124200 PRINTS: 0 PRICE: 0,00

PREFACE Deze handleiding is onderdeel van een serie van drie CAD/CAM handleidingen die worden gebruikt in het onderwijs van de faculteit Construerende Technische Wetenschappen (CTW) van de Universiteit Twente. Het eerste deel, CAD/CAM handleiding SolidWorks deel I, behandeld het 3D modelleren van prismatische vormen, hat maken van samenstellingen van onderdelen en het maken van tekeningen. Het is 1 e jaars studiemateriaal voor de opleidingen Werktuigbouwkunde en Industrieel Ontwerpen. Het tweede deel staat in het teken van het modelleren van dubbelgekromde vormen zoals we die in de hedendaagse consumentenproducten tegen komen. Aan de orde komen surface modelling, dunwandige producten en het modelleren van een matrijs. Het is 2 e jaars stof voor IO en Wtb. Het laatste deel uit de serie deze handleiding behandeld mogelijkheden van de interface die hedendaagse CAD systemen bezitten ten behoeve van de communicatie met andere software. Met een dergelijke communicatie kunnen bedrijven grote voordelen behalen in hun ontwerpprocessen, zeker in een tijdsgewricht waarin alle activiteiten een versnelling lijken te ondergaan. De onderzoeksgroep OPM heeft een traditie waar het gaat om onderzoek dat uitmondt in grensverleggende technologie. De groep ontwikkelt Computational Synthesis techniek waarmee volgende generaties ontwerpsystemen op een intelligente manier product creatieprocessen kunnen ondersteunen. De eerste stappen op die route hoe krijg je een CAD systeem onder controle leer je in deze handleiding. Ir. Hans Tragter Vakgroep OPM Fac. CTW / Universiteit Twente. i

CADCAM Deel IV, Design Automation INTRODUCTIE Bedrijven opereren in specifieke marktsegmenten en ontwikkelen daarvoor ook eigen producten. In hun ontwikkel en ontwerpprocessen komen veel handelingen voor die zich herhalen. Deze routinematige werkzaamheden kunnen worden versneld met behulp van verschillende technologie die in de meeste CAD systemen voorhanden zijn. Deze handleiding richt zich op één van deze technologieën: de customization van systemen door eindgebruikers. Hierbij wordt eigen ontwikkelde software aan een standaard CAD systeem toegevoegd. De software kan de vorm hebben van macro s of spreadsheets, maar ook van een module compleet met eigen menu s. Ook de schaalgrootte varieert. Soms zijn het enkele tientallen instructies om een zelf gemaakt symbool met bijbehorende attributen te plaatsen. In andere situaties zijn het inspanningen waarbij meerdere medewerkers fulltime werken aan software die automatisch het detailontwerp genereert voor bijvoorbeeld industriële stoomketels of een complete slachtlijn voor pluimvee. Deze handleiding geeft voorbeelden van verschillende customization technieken in de vorm van tutorials: stapsgewijze opdrachten met een toelichting, waarin je zelf zogenaamde CAD applicaties bouwt. Op deze manier verkrijg je inzicht in de mogelijkheden van de techniek en ben je in staat om ze toe te passen. Tevens krijg je zicht op de inspanningen die nodig zijn en de voordelen die een bedrijf er mee kan behalen. De handleiding bestaat uit twee secties: 1. In de eerste sectie krijg je een inleiding in de programmeertaal Visual Basic. Het is geen programmeercursus maar een introductie zodat je met een computertaal uit de voeten kunt. Behandeld wordt het concept variabele, het gebruik van objecten en besturingsstructuren om instructies te herhalen en/of facultatief uit te voeren. Je zult later in je opleiding en werkomgeving nog vaak plezier hebben van deze vaardigheid. 2. De tweede sectie maakt de stap naar het programmeren in een CAD omgeving. De complexiteit is hier meteen een stukje hoger, een CAD systeem is een ingewikkeld stuk software, maar we beginnen met eenvoudige oefeningen. Uiteindelijk leer je o.a. geometrie gegevens opvragen, eigen gegevens aan een CAD model toevoegen, een assembly in elkaar zetten en een ontwerpconfiguratie besturen. Bij de oefeningen wordt gebruik gemaakt van Visual Basic (van Microsoft) en SolidWorks (van Dassault). Beide worden in de industrie veel gebruikt, maar ze zijn niet het enige dat er bestaat op die gebieden. De concepten waarmee je leert werken kun je echter ook terugvinden in en gebruiken bij andere programmeertalen en CAD systemen van andere leveranciers. ii

Design CONTENTS SECTIE 1: THE VISUAL BASIC PROGRAMMING LANGUAGE 1 1. INTEGRATED DEVELOPMENT ENVIRONMENT (IDE)... 3 2. VARIABLES... 9 3. STRINGS... 15 4. CONTROL STATEMENTS... 21 5. METHODS EN FUNCTIONS... 29 6. OBJECTS AND ARRAYS... 35 7. FILE IO... 43 SECTIE 2: APPLICATION PROGRAM INTERFACE TO SOLIDWORKS 49 8. DESIGN TABLES... 51 9. MACRO S EN API HELP... 57 10. THE SOLIDWORKS CONNECTION... 61 11. AUTOMATED DRAFTING... 67 12. CONTROLING PARAMETERS... 73 13. CREËREN VAN EEN ASSEMBLY... 79 iii

THE VISUAL BASIC PROGRAMMING LANGUAGE Er is gestreeft naar een efficiente instructie voor het verwerven van programmeervaardigheid. Daarmee is het geen handleiding voor dummies geworden maar juist het tegendeel. Deze sectie van de handleiding bevat zeven tutorials waarmee je je de basis vaardigheden van het programmeren eigen kunt maken. Het hanteert een aanpak waarin je in beknopte voorbeelden en oefeningen alle belangrijke basisbegrippen langs ziet komen. Daarbij bouw je vanaf het begin de software in een moderne object georiënteerde omgeving. De behandelde abstracties zijn universeel toepasbaar in iedere programmeertaal. Deze sectie van het dictaat is Engelstalig. Daarmee sluit het goed aan op de begrippen uit de softwarewereld en de interface van je ontwikkelomgeving. Na het doorlopen Weet je wat een geïntegreerde softwareontwikkelomgeving (IDE) is en kun je er mee werken Ken je de belangrijkste datatypen en kun je het juiste type kiezen Kun je variabelen gebruiken, inclusief character strings en arrays Kun je besturingsturingstructuren met herhalingen en beslissingen ontwikkelen Kun je bestaande methoden en functies gebruiken en nieuwe definiëren en ontwikkelen Kun je gegevens van je programma naar een file schrijven en gegevens inlezen INHOUD De inhoud is een selectie van de essentiële onderwerpen uit een heel pallet van onderwerpen die een beginnerscursus programmeren kan bieden. Het doorlopen van deze tutorial kost 4 tot 6 uur. De zeven hoofdstukken: Integrated Development Environment (IDE) introduceert het programma Visual Studio van Microsoft. Je leert een project aanmaken en een eenvoudig programma creëren. Variables De opbergplek voor gegevens en de sleutel voor het gebruik van objecten zijn variabelen. Je leert de belangrijkste data typen kennen en gebruiken. Strings Opslaan en manipuleren van character gebaseerde informatie. Control Statements worden gebruikt om instructies te herhalen en/of facultatief uit te voeren. Aan de orde komen o.a. de begrippen als boolean expressie en loop index. Methods en Functions vormen een belangrijk element in het redeneren over en het reduceren van de complexiteit an problemen. Je leert bestaande methodes gebruiken en nieuwe ontwikkelen. Objects and Arrays Arrays zijn belangrijk voor het efficiënt verwerken van grote hoeveelheden gegevens zoals voorkomt in scientific computing. Objecten zijn vooral van belang voor een overzichtelijke programmastructuur en het creëren van herbruikbare code. File IO gaat over het schrijven van informatie vanuit het programma naar een file en het lezen van gegevens uit een file. 1

INTEGRATED DEVELOPMENT ENVIRONMENT In this chapter you will learn the basic skills you need to create a simple program. This knowledge will be important to you as you explore the language itself in the next part of the manual. In this chapter: Start a new Visual Basic programming project Use controls to build a user interface Write program source code Convert a program into an executable Windows application Figure 1 The opening screen of Visual Basic 2010 Express In the exercises of this section the Visual Basic 2010 Express software is used to create the illustrations. Since there are different dialects of the Basic programming language as well as different development environments (IDE s), your screen and your programming code might look slightly different. The covered functionality however, will be present in all modern tools. 3

CADCAM Deel IV, Design Automation THREE PROGRAMMING STEPS CREATING THE USER INTERFACE A program s user interface enables the user to interact with the program. The user interface comprises any objects that the user manipulates in order to give commands or information to the program. Such objects include buttons, menus, and text boxes, to name just a few. Visual Basic makes it easy to create a user interface by providing a set of ready to go controls in a toolbox. All you have to do to create your user interface is start a new project and position the controls on the form, which is the object that represents the program s main window. In this chapter, you will create only a very simple user interface, learning just enough so you can understand the sample programs in the next sections. Go ahead and start Visual Basic. Your screen will look as in Figure 1 on the previous page. Double click New Project puts a new dialog on the screen. Figure 2 Dialog to select the kind of new project. In this dialog, you select the kind of project you want. Enter a name for the project, e.g. My Application, in the Nema field, then select Windows Forms Application to start a new project. In this tutorial we will only deal with window applications. Visual Basic then creates a Form object for your program s window, as well as displays a bunch of goodies in the toolbox, Project window, and Properties window. The Figure 3 shows how Visual Basic should look at this point. Inside the left border of the window, you will probably have two buttons. One is called Toolbox. Hovering over this button with your mouse will expand it automatically. You can fix it on your screen by clicking the middle thumb nail icon in the top right corner. 4

Integrated Development Environment Figure 3 Visual Basic with a fresh project and an expanded Toolbox on the left side. Do you see all those icons in the toolbox? Each icon represents one of the controls you can use to build your program s user interface. Button, Label and TextBox are the ones that will be used most frequently, but you will recognize others as well since the very same controls are also used to create other programs like Word and SolidWorks. Your goal right now is to get a general idea of how to create a Visual Basic program. How to put a button on your new form? Just click the Button control in the toolbox and click in Form1 on the location you want your button. When it is clicked once, it will be selected and have resize handles as in Figure 4. See the small squares that border the button object? Those are the button s sizing handles. You can change the size of the button by placing your mouse pointer over one of the sizing handles, holding down the left mouse button, and dragging the handle. When you place your mouse pointer over a sizing handle, the mouse pointer changes to a new image that indicates the direction you can drag the Figure 4 First button on a form. handle. If you move your mouse over a control, a Move icon appears and you can drag the control to another location. 5

CADCAM Deel IV, Design Automation ADDING THE PROGRAM SOURCE CODE You now have a button in a form, which is all fine and good except for the fact that the button does nothing. Click the Start button on Visual Basic s toolbar. (When your mouse pointer is over the correct button, a little box appears containing the word Start Debugging (F5). When you click the Start button, Visual Basic runs your program. You will see your Form1 as a small program window that looks like this: Go ahead and click your program s Button1. What s important to notice is that clicking it doesn t make the program do anything useful. This is because we did not tell it what to do. However, resizing, minimize and maximize work, as well as the close button in the right of the title bar. End your program by clicking the red close icon in the title bar, or on the Stop button in Visual Basic. Return to Visual Basic s main window. Now, double click your form s Button1. A new window, the Form1 s code window pops up, as shown in the following figure. Current Events Note that you have a new tab Form1.vb*, next to the tab Form1.vb[Design]* where we are designing our form. Click on the tabs, to see what happens. Notice that, with the tabs, we can work on two aspects of a single item (the Form) in our program. Many of the things that happen in a Visual Basic program happen in response to events. An event is nothing more than something the user or the computer does to inter act with your program. For example, when you clicked your program s Button1, you caused a Click event. To tell Visual Basic what to do with this event, you must complete the Button1 Click event procedure. You will have learned plenty of other events by the time you get to the end of this section. When you double clicked the Button object, Visual Basic not only displayed the code window, but also generated some program source code for you. This piece of source code is called a procedure. To put it simply, whenever a user clicks Button1, Visual Basic goes to the Button1_Click procedure and performs all the commands the procedure contains. When you ran the program previously and clicked the button, Visual Basic also executed to the Button1_Click procedure. Unfortunately, you have not yet placed commands in the procedure, so nothing happened. You can change that easily, by adding the next source code line to the method, between the Sub and the End Sub Lines. Now, run the program again (by clicking the Start button). When you click Button1 this time, a message box appears with the message Visual Basic rocks. MsgBox( Visual Basic rocks ) 6

Integrated Development Environment As you might have already guessed, the MsgBox command tells Visual Basic to display a message box. The text between the brackets after the MsgBox command is the message it should display. You will see the MsgBox command a lot throughout this tutorial. In the next section you will see how to convert your Visual Basic program into a standalone application. CREATING YOUR PROGRAM S EXECUTABLE FILE Now you will save your project and create a Windows application. If you look in the File menu, you will see a command called Save All. It will store all the project s file in one folder (it suggests My Application1, but you can give the project the same name as your application). Then, from the View menu, select Solution Explorer. This will put an extra pane on the right of your screen where you can find all components added to your application: in this case one project and Form1. The screen will look as in Figure 5. Figure 5 The Visual Basic screen, with the Solution Explorer enabled. Then, in the menu, click Build, Build My Application. The path to your application s executable can be found when you first click My Application in the Solution Explorer pane, and then look in the Properties pane at the value of the Project Folder field (see Figure 5). Build menu Do not have a Build menu? You can get it by changing the IDE settings to "Expert Settings." To do this, go to Tools > Settings and then choose Expert Settings. 7

CADCAM Deel IV, Design Automation Now that Visual Basic has converted your program to an executable file, you don t need it to run the program. Exit from Visual Basic with the command File Exit. Find the file My Application.exe in the Explorer (in my case it is in My Documents\Visual Studio 2010\Projects\My Application\My Application\bin\Release ). Double click My Application.exe, and your Visual Basic application appears on the screen. Go ahead and click the Button1 to display the message box end exit the program. WHAT HAVE YOU LEARNED To create a Visual Basic application, you build a user interface, write the program source code, and then compile the program into an executable file. You build a user interface by placing controls from Visual Basic s toolbox on your program s form. You can resize a control (and the form) by dragging the control s sizing handles, which appear when the control is selected. One way to display the code window is to double click the object for which you want to write program code. When the user clicks a button, Visual Basic generates a Click event. The program code you add to the button s Click event procedure determines what the button does. The File menu s Make command converts your Visual Basic program into a standalone Windows application. 8

VARIABLES A computer would not be of much use if you did not have a way of getting data in and out of it. For example, to understand computer input and output, let s say you want to make a calculation. Your first task is to get the characters that make up the numbers into your computer s memory where you can manipulate them. When you finish typing and changing the numbers, you need a way to get the results out of the computer s memory to a place where it can be read by humans or other programs. You need an output device (typically the screen or a file), to which you can send it into a form that is useful. In this chapter: Understand input and output Discover variables and how to declare them Use TextBox controls for input Use Label controls to give the user information 9

CADCAM Deel IV, Design Automation VARIABLES AND INPUT To get user input into your Visual Basic programs, you can use an item called a TextBox control. Suppose, for example, you re writing a program that needs to keep track of the number of cars in a parking garage. Suppose also that when the user runs the program, the first thing he or she must do is input the current car count. To solve this problem, try this: Start a new Visual Basic project named Variables. Then place a TextBox control and a Button control on the form like below. Your program will become much more readable when you are using meaningful names. Select the button (so that the resize handles show up), and look at your properties pane on the right of the screen. You will find the (Name) field with value Button1. Change this name into InitialButton. Then scroll down to the Text field and put in the text Initial without the quotes. Your button s name now is InitalButton, and it has the text on it Initial. In a similar way change the name of the TextBox control to InitialTextBox. Double click the InitialButon to display its procedure in Visual Basic s code window. Complete the code. You need to declare a variable named carcount, that will hold a number (whole numbers like 1, 6 3 are called Integer). In the method, we will get the value from the textbox and store it in the variable. Just to show what is happening, we put in an extra MsgBox command. Public Class Form1 Dim carcount As Integer Private Sub InitialButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InitialButton.Click carcount = InitialTextBox.Text MsgBox("Currently there are " & carcount & " cars") End Sub End Class In the message box, we glue pieces of information together with a & character Now, run the program, type a number into the text box, and click the button. When you do, Visual Basic jumps to the button s procedure, where the program grabs your input from the text box, and prints the results in the message box, as shown in this figure. 10

Variables DECLARING VARIABLES Variables can exist as many different types. When you write a program, you have ideas about what kind of data the variables will hold and you inform Visual Basic. This is called explicit declaration. When you declare a variable, you not only tell Visual Basic the variable s name, but also how the variable is to be used, with the Dim statement in your program. The types of data you have encountered so far are: Integer for a whole number, like 1, 3, 7, 6, 0 String for sequence of characters, like aap noot mies or Currently there are Be aware of the difference however, between 3 and 3. The data types are different, hence the operations a computer can execute with them. The first is a number, and can be used in arithmetic operations. The second is a sequence of characters as can be entered with a keyboard and it is used for searching (names), writing information on the screen etc. Type casts Sometimes we want to convert one type into another. Visual Basic handles these conversions automatically. But there are situations it cannot deal with. For instance when we enter ten in your program, to initiate the presence of 10 cars in the garage; Here a runtime error occurs and your program stops with the following error message: VARIABLE TYPES There are many different types to store different kinds of data. This table lists the most common types. Data Type Storage Range Byte 1 byte 0 to 255 Boolean 2 bytes True or False Integer 2 bytes 32,768 to 32,767 Double (double precision floating point) 8 bytes 1.79769313486232E308 to 4.94065645841247E 324 for negative values; 4.94065645841247E 324 to 1.79769313486232E308 for positive values Date 8 bytes January 1, 100 to December 31, 9999 Object 4 bytes Any Object reference String (variable length) 10 bytes + string length 0 to approximately 2 billion characters Variant (with numbers) 16 bytes Any numeric value up to the range of a Double 11

CADCAM Deel IV, Design Automation LABELING YOUR TEXT BOXES A TextBox control without a label is confusing. After all, unless you tell the user what you expect him to enter, how will he know what to do? Because you frequently need to prompt for information in programs, Visual Basic provides a special control, called a Label control, for labeling items in a window. You can easily add a label to the program you re working on. First, place a Label control on the form, dragging it into place above the TextBox control. Notice that, when you move it close to the TextBox, it automatically aligns. Then, change the Label control s Text property to Initial number of cars (without the quotes). You can make this change by clicking the label to select it as shown in this figure, and then changing the value of the Text property in the Properties pane,. INPUT AND OUTPUT FIELDS Now that you have learned a little about input, let s try to add output as well. Start by placing two extra buttons and give them the names PlusButton and MinusButton. The idea is that they can be used to increment or decrement the number of cars. Adjust the Text properties, so they show the same text as in the figure. Also place an extra TextBox control named ParkedCarsTextBox. This control is output only. If we switch its Readonly property from False to True, the user is no longer able to type a value in this control (its grayed). Add labels where necessary so you form looks like the figure on the right. Your event handler for your Plus and Minus buttons needs to do two things: increment or decrement the carcount variable Update the text displayed in ParkedCarsTextBox The program code to be added looks for the MinusButton looks like: Private Sub MinusButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MinusButton.Click carcount = carcount - 1 ParkedCarsTextBox.Text = carcount End Sub Now, run the program to test all buttons. The one thing that fails, as you probably notice, is the update of the output when the InitialButton is used. Can you replace the MsgBox code with something more sensible in this situation? By the way, to make the Exit button work, you need an instruction to close the main form (Form1) of your program: Close() 12

Variables TYPE CONVERSION If you look back at the previous program, you can find the following line in the InitialButton_Click method. We have discussed that Visual Basic performs an automatic conversion in this line: from the TextBox control its string value to the Integer type of carcount. carcount = InitialTextBox.Text Also other type conversions are possible. For instance when we have two variables, one of the Integer type to hold a whole number, and one of the Double type to hold a number with a decimal fraction. Dim myint As Integer Dim mydouble As Double Now, let us examine what happens when assigning these to each other: myint = 10 mydouble = myint Console.WriteLine( myint & myint &, mydouble & mydouble) Prints: myint = 10, mydouble = 10.0 mydouble = 10.3 myint = mydouble Console.WriteLine( myint & myint &, mydouble & mydouble) Prints: myint = 10, mydouble = 10.3 mydouble = 0.71245 myint = mydouble Console.WriteLine( myint & myint &, mydouble & mydouble) Prints: myint = 1, mydouble = 0.71245 The variable myint cannot hold a floating point number like 10.3. When Visual Basic solves the expression in the assignment, it rounds the value to the nearest integer, which is 10, because you asked it to store the value in an integer. Visual Basic assumes that you know what you are doing and gives you no warning of the conversion (other languages do). Conclusions: 1. Assigning an integer value to a double variable works fine 2. Assigning a floating point value to an integer rounds the decimal fraction 13

CADCAM Deel IV, Design Automation WHAT HAVE YOU LEARNED String literals must be enclosed in quotation marks. Variables are named places in memory where a program can store data. A variable is declared with a type and a meaningful name. Numeric variables can hold only numeric values. String variables can hold only text (or numbers that the computer treats as text). Visual Basic converts data type automatically. While converting from one type to another, you may lose information. You can use TextBox controls to get input from a program s user. You should use Label controls to label text boxes. You can switch a textbox control to Read only. A TextBox control s Text property holds the text in the control, whereas a Label control s Text property holds the text displayed in the label. Type conversions may lose information. 14

STRINGS Most information laid on your computer screen is in text form. Because textual display is so important in computing, Visual Basic has a number of actions and commands that manipulate text. These functions enable you to join two or more strings of characters into one, find the length of a string, extract a small portion of a string, and convert numbers to strings or strings to numbers. In this chapter, you will to use many of Visual Basic s string handling functions. In this chapter: Join strings together Calculate the length of a string Manipulate substrings Convert between strings and numbers PREPARATION Before continuing with this chapter s tutorial do the following: 1. Create a new project StringApplication 2. Create a form with two Button controls ProcessButton and ExitButton 3. Add three TextBox controls: FirstNameTextBox, LastNameTextBox and OutputTextBox 4. Add labels to the TextBox controls The OutputTextBox does initially look like the other two, but you can change it. Select the control (as shown), and then go to the Properties pane. Change the Multiline field to True, and set the ScrollBars property to Vertical. Now you can change its height and adjust its position in the form. 15

CADCAM Deel IV, Design Automation JOINING STRINGS You will often have two or more strings in your programs that you must combine into one. For example, you might have a user s first name and last name in two separate strings. In order to get the user s entire name into a single string, you have to concatenate the two strings. Use Visual Basic s concatenation operator, which is the ampersand on your keyboard, to handle this string handling task. Simply joining the strings, however, is not a complete program statement; you also must tell Visual Basic where to store the new string. To do this, use Visual Basic s assignment operator, the equals sign (=). The assignment operator for strings works just like the assignment operator for numeric variables. To see how all this works, look at these lines: Dim str1 As String Dim str2 As String Dim str3 As String str1 = This is str2 = a test. str3 = str1 & str2 OutputTextBox.Text = str3 These lines first declare three string variables and assign strings to two of the variables, str1 and str2. The string of characters itself is placed within a pair of double quotes. Then, the sixth line joins the first two strings together with an & operator and assigns the result to the third string variable, str3. Change the code in the ProcessButton_Click event so that it appends the first and last name and outputs the result in Output TextBox control. THE LENGTH OF A STRING Every string has a length, which is the number of characters contained in that string. For example, the string Why did the chicken cross the road? has a length of 35 because it contains 35 characters. Theoretically, a string can have any length, from 0 to infinity. In Visual Basic, however, a string is much more conservative and cannot exceed 0 to 32.767 characters. Sometimes in your program, you might need to know the length of a string. To find the length of a string variable, you can access one of its properties (Yes variables can also have properties like controls!), as in the following code. The first line declares an Integer; the second line copies the value to this variable. Dim length as Integer length = str1.length Change the ProcessButton_Click method to display the length of str3. As you see, we do not necessary need to copy the value to a variable first. OutputTextBox.Text = The length of str3 is & str3.length 16

Strings SPECIAL CHARACTERS We have created a nice multi line textbox, so it s time to find out how it has to be used. The characters in a string are normally regular visible characters like a, b,c etc. We can, however, put also control characters in a string. Two of the most important control characters are Carriage Return (CR) and Linefeed (LF). They date back to the time of mechanical typewriters: CR puts your paper such that you continue writing at the left, LF moves you to a fresh line, below the current one. Visual Basic provides us with a string that contains these two characters. The variable is called vbcrlf. Additionally, also the textbox has nice methods that we can use to display multiple strings with text. It has a method Clear(), that clears all content, and a method AppendText() that can be used as often as needed to plug in text strings. The following code should show you how it all works. Implement it in your own program. Sub Testje() Dim str3 As String = "This is a test." OutputTextBox.Clear() OutputTextBox.AppendText(str3 & vbcrlf) OutputTextBox.AppendText("Length = " & str3.length & vbcrlf) End Sub Can the same result be obtained with the next statements? Sub Testje() Dim str3 As String = "This is a test." OutputTextBox.Text = str3 OutputTextBox.Text = The length of str3 is & str3.length End Sub Note The lines above define a method Testje. A method can be invoked (started) from another point in your code by simply mentioning its name followed by brackets as shown in the example below. Private Sub ProcessButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProcessButton.Click Testje() after Testje, this line would be executed next End Sub After a method it is finished (when it reaches End Sub), execution continues with the line after where it was started. 17

CADCAM Deel IV, Design Automation EXTRACTING A SUBSTRING Just as you can join strings to create a larger string, so too can you separate strings into smaller strings called substrings. Visual Basic has several special string handling functions that were created especially to extract whatever portion of a string you need. Warning The methods for manipulating strings may vary per Visual Basic version. The Visual Basic Express environment is the latest and most modern approach for this functionality. However the scripting language VBA, as used inside Excel and SolidWorks, implements an different non object oriented approach. In this part of the manual we will follow the modern style. There is a table at the end of this chapter that gives you the alternative functions to obtain the similar results in the VBA dialect of the language. To get a section from a string, you use its SubString function. This functions has two integer arguments. This first one indicates the starting position (counting from left to right, and starting at position 0); the second argument specifies the length of the substring (the number of characters you want). Dim str1 As String Dim str2 As String str1 = This is a long test string. str2 = str1.substring(5, 2) OutputTextBox.Text = str2 After execution of the code above, str2 will contain is. FINDING SUBSTRINGS Now that you know how to extract a substring from a larger string, you might wonder how you can find the exact substring you want. Suppose, for example, you have a string containing a list of names, and you want to find the name Twitdum. The function IndexOf was created for just this task. Dim str1 As String Dim index As Integer str1 = Hans Twidum Gerald Friz index = str1.indexof( Twidum ) When you find the position of the string, simply use SubString to extract the actual string. After finding the first occurrence of a substring, you might want to search the rest of the string for another occurrence. After all, your name list might contain more than one Twitdum. To continue searching, you use the second form of the IndexOf. This second form takes as arguments not only the string to search and the substring for which to search, but also the starting position of the search. 18

Strings CONVERTING STRINGS TO NUMBERS You probably remember that there s a big difference between numerical values and text strings, even if the text string contains numeric characters. Numerical values, such as the number 5 or the integer variable number, can be used in mathematical operations Strings however cannot. Visual Basic includes functions that let you convert number strings into numerical values that can be used in mathematical operations. You can also convert in the other direction from numerical values into strings. Note Rember that the names of the conversion functions depend on the dialect of Visual Basic. At the end of this chapter is a list showing the two most common sets. To convert a string into a numerical value (when possible), use the Parse function. The following statements make ix equal to 3 and dy equal to 3.4: Dim str1 As String Dim str2 As String Dim ix As Integer Dim dy As Double str1 = 3 str2 = 3.4 and more text ix = Integer.Parse(str1) dy = Double.Parse(str2) In this example, because the characters and more text are not numerical characters, Parse does not look at them, because it stops at the first space. If Parse cannot convert the string at all, as in the case of number = Integer.Parse( Apples ), it will generate a runtime error and your program stops. In general you do not want your program to crash, when the user makes a typing mistake. For that reason, there is another version available: TryParse(). It returns a Boolean value of True when it can successfully make a number from the text, and it returns False when not. Dim str3 As String = "Apples" If (Integer.TryParse(str3, ix)) = True) Then 'I received have a valid number in ix Else I didn t MsgBox("Invalid number " + str3) End If The construction above executes the lines of code conditionally. The chapter about Control Statements will explain this topic. CONVERTING NUMBERS TO STRINGS You have used the conversion from a numeric value to a string value already a number of times by the time you reach this point of the tutorial. That you did not have to bother is because of the smartness of Visual Basic s automatic Type casting. In the code of the next lines for instance, the integer value is converted to a string before it is appended to the first string and assigned to the TextBox control. Dim ix As Integer = 3 Dim str3 As String str3 = ix.tostring() But you can do explicit conversions as well using the.tostring() method of a numerical variable as shown next. Most Types in Visual Basic provide such a method, and you can find mere examples in the References section on the next page. 19

CADCAM Deel IV, Design Automation REFERENCES The methods for manipulating strings vary per Visual Basic version. The Object Oriented Visual Basic, as in Express or Visual Studio editions, is the latest and modern approach for this functionality. However the scripting language VBA, as used inside Excel and SolidWorks, is also very common. This following table provides a side by side list with compatible functionality. Note however, that the VBA indexes characters from 1, whereas Visual Basic (as most other languages) starts at index 0. Visual Basic VBA Explanation str.length Len(str) Returns the length of string str str.start() Left(str, length) Start section of string str with a specified length str.substring(start, length) Mid(str, start, length) Mid section of string str with a specified length str.substring(start) Right(str, length) End section of string str with a specified length str(index) Mid(str, index, 1) Get the single character at position index str.indexof(str2) str.indexof(str2, start) InStr(str, str2) Gives the index of string str2 within str* Gives the index of string str2 within str starting at start* * If not present, returns 1 respectively 0 i = Integer.Parse(str) i = Val(str) Returns a numeric integer value from str d = Double.Parse(str) d = Val(str) Returns a floating point value from str Integer.TryParse(str, i) Double.TryParse(str, d) Puts a numeric integer value from str in i Returns True if successful, otherwise False Puts a numeric value from str in d Returns True if successful, otherwise False str = i.tostring() str = Str(i) Returns a string value from a numeric variable WHAT HAVE YOU LEARNED String literals must be enclosed in quotation marks. You can use the ampersand operator & to join strings together. This process is called concatenation. The equals sign (=) can be used with strings just as it is used with numerical values. Specifically, you use the assignment operator to set a string variable to a specific string value. The length of a string is the number of characters contained in the string. An empty string contains no characters and so has a length of 0. A substring is a portion of a larger string. The function IndexOf is used to search for occurrences of a substring. There are functions to convert strings to numerical values and vice versa. 20

CONTROL STATEMENTS In previous chapters, you learned much about the way Visual Basic works. You now know how to type programs, how to input and output data and how to handle strings. But these techniques are merely the building blocks of a program. To use these building blocks in a useful way, you have to understand how computers make decisions. In this chapter, you learn how your programs can analyze data in order to decide what parts of your program to execute or repeat. Now it is time to learn how you can control your program s flow, the order in which the statements are executed so that you can do different things based on the data your program receives. In this chapter: Discover the If /Then statement, Replaced the If /then statement with the Select Case statement, Write a For/Next loop, Use variables in For/Next loops, Discover how to use Do Until, Do/Loop While and Do/Loop Until loops. 21

CADCAM Deel IV, Design Automation PREPARATION Before continuing with this chapter s tutorial prepare a small program in a similar way as you did for the previous chapter: 1. Create a new project ColorApplication 2. Create a form with two Button controls ProcessButton and ExitButton 3. Add two TextBox controls: InputTextBox and OutputTextBox 4. Set the OutputTextBox properties Multiline field to True, and set the ScrollBars property to Vertical. 5. Add labels to the TextBox controls Give your Form1 a name that better represents what it is: MainForm. In the Solution Explorer right click on Form1.vb, and rename it to MainForm.vb Now, in the Form s design tab click in the form to select it (but not on a control). The selection handles are displayed, just as in the top picture. You now could resize your form. Instead we will change its title. Go to the Properties pane and change the Text property into Color. PROGRAM FLOW AND BRANCHING Program flow is the order in which a program executes its code. Your programs so far in this tutorial have had sequential program flow. Truth is, almost all program code executes sequentially. However, virtually every program reaches a point where a decision must be made about a piece of data. The program must then analyze the data, decide what to do about it, and jump to the appropriate section of code. This decision making process is very important to computer programming. It is called conditional branching. 22

Control Statements THE IF /THEN STATEMENT Most conditional branching occurs when the program executes an If /Then statement, which compares data and decides what to do next, based on the result of the comparison. If the comparison works out one way, the program performs the statement following the Then keyword. Otherwise, the program does nothing and drops to the next program line. This gives each comparison two possible outcomes. If (choice = 1) Then End If A simple If /Then statement includes the keyword If followed by a Boolean expression. The Boolean expression is the section between the () brackets. You follow the Boolean expression with the keyword Then and, finally, with the statement that you want executed if the Boolean expression is true. A Boolean expression is an expression that evaluates to either true or false. For example, the expression (3 + 4 = 7) is true, whereas the expression (6 = 9) is false, just as ( aap = noot ) is false. To get feeling for the if statement, place the following code in the method that handles the ProcessButton click event. Private Sub ProcessButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProcessButton.Click Dim choice As Integer Dim entry As String entry = InputTextBox.Text choice = Integer.Parse(entry) If (choice = 1) Then MsgBox("You chose red.") BackColor = Color.Red End If If (choice = 2) Then MsgBox("You chose green.") BackColor = Color.Green End If If (choice = 3) Then MsgBox("You chose blue.") BackColor = Color.Blue End If End Sub The even procedure performs the following actions: 1. Declares the variables needed within the procedure 2. Retrieves the text typed into the InputTextBox and converts the string value to an integer 3. Uses If /Then statements to determine which message box to display and which color to set to the background. Try the program yourself. Run the program and then type a value from 1 to 3 into the input box. Click the Process button, and the program displays a message box that tells you the color you selected. 23

CADCAM Deel IV, Design Automation ELSE AND ELSIF Often, when testing a condition, you will want to execute some code in when the value is True, and another piece of code when the expression is False.. Here you can add an Else to your control statement like shown below. If (choice = 1) Then Else End If We can use such a statement, to test the validity of the input. We use the TryParse function instead of Parse (Yes, the one introduced in the chapter about Strings). TryParse returns a value True when successful and False when the conversion not succeeded. This is precisely what is needed in the If. Also note that If /Then s can be nested. Private Sub ProcessButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProcessButton.Click Dim choice As Integer Dim entry As String entry = InputTextBox.Text If (Integer.TryParse(entry, choice)) Then If (choice = 1) Then MsgBox("You chose red.") BackColor = Color.Red End If If (choice = 2) Then MsgBox("You chose green.") BackColor = Color.Green End If If (choice = 3) Then MsgBox("You chose blue.") BackColor = Color.Blue End If Else MsgBox("Please enter a number from 1..3") End If End Sub One thing to notice about this program is what happens if you type a value 1. Although you, yes you, know that the value will not be also 2 or 3 at the same time, the program continues happily testing for these values after it executed the first If /Then block. This is inefficient and unclear code as well. When we know that the conditions are exclusive, it is appropriate to use an If /Then / ElseIf construction. The following lines show this more compact and efficient version. entry = InputTextBox.Text If (Integer.TryParse(entry, choice)) Then If (choice = 1) Then MsgBox("You chose red.") BackColor = Color.Red ElseIf (choice = 2) Then MsgBox("You chose green.") BackColor = Color.Green ElseIf (choice = 3) Then MsgBox("You chose blue.") BackColor = Color.Blue End If Else MsgBox("Please enter a number from 1..3") End If 24

Control Statements BOOLEAN EXPRESSIONS The Boolean expressions within If /Then statements and other control structures can be made more elaborate then we have seen so far. We can for instance test numeric values on equality, but also on greater or smaller; Or test whether a number is within a range. To do this, we need more operators. REALATIONAL OPERATORS The previous programs in this chapter used only the equal operator to compare values. Often you will need to compare values in other ways. You might, for example, want to know if a value is less than or greater than another value. Visual Basic features an entire set of relational operators you can use in If /Then statements and other types of comparisons. Relational Operators Meaning = Equal <> Not equal < Less than > Greater than <= Less than or equal >= Greater than or equal LOGICAL OPERATORS A single comparison in an If /Then statement often isn t enough to determine whether data matches your criteria. How can you be sure, for example, that the user enters a number within a specific range? A way to ensure that data is in the correct range is to use logical operators in your If /Then statements. Visual Basic features four logical operators. Logical Operators And Or Xor Not Meaning True if both sides of the expression are true True if one or both sides of the expression are true True if only one side of the expression is true Reverse true to false and vice versa 25

CADCAM Deel IV, Design Automation FOR /NEXT LOOP One strength of a computer is its unprecedented ability to do the same task repeatedly without getting tired or making mistakes. The control structure to create such a repetition in Visual Basic is the For /Next loop. It instructs a program to perform a block of code a specified number of times. You could, for example, use a For /Next loop to instruct your computer to print those 10,000 address labels. Because you don t currently have an address file, however, let s say you want to print a message on the screen 12 times. The end of the block of statements is marked by Next i. Arrived at that point, the loop variable increments with 1 and execution jumps to the associated For at the top of the block. For i = 1 To 12 Next i A For /Next loop has control variable. Typically, software developers use the name i, j or k for it. If you follow this convention your code will be easier readable by your colleagues. To make your life easier, you can add a helper method to your program. It s task is to write a text string to the OutputTextBox, and append a CR/LF string, so that the next append will appear on a new line. Add this code to the end of your program, just before the End Class line. Sub writeline(byval str As String) OutputTextBox.AppendText(str) OutputTextBox.AppendText(vbCrLf) End Sub End Class Now you can plug in some new code in your ProcessButton_Click event method. Private Sub ProcessButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProcessButton.Click Dim i As Integer Dim name As String End Sub name = InputTextBox.Text OutputTextBox.Clear() For i = 1 To 12 writeline(name) Next i USING VARIABLES IN LOOPS Just as with most numerical values in a program, you can substitute variables for the literals you ve used so far in your For/Next loops. To see how this works, modify your program so that it prints values of the factorial! function. Private Sub ProcessButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProcessButton.Click Dim i As Integer Dim fac As Integer End Sub fac = 1 OutputTextBox.Clear() writeline("factorial function!(x)") For i = 1 To 12 fac = fac * i writeline("!(" & i & ") = " & fac) Next i 26

Control Statements DO WHILE LOOP Unlike a For /Next loop, which loops the number of times given in the loop limits, a While loop continues executing as long as its control expression is true. The control expression is a Boolean expression much like the Boolean expressions you used with If statements. In other words, any expression that evaluates to true or false can be used as a control expression for a While loop. Do While (i > 0) Loop A typical use for a While is a search algorithm, where you do not know in advance where or when your item will be found. We can use it to modify the Factorial algorithm, so it can calculate any function value. Note The! function s value rapidly grow very big. To account for these large values, it is better to use a different type of integer: the Long. The maximum value of a Long is Private Sub ProcessButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProcessButton.Click Dim i, x As Integer Dim fac As Long x = Integer.Parse(InputTextBox.Text) fac = 1 i = x Do While (i > 0) fac = fac * i i = i - 1 Loop writeline("!(" & x & ") = " & fac) It is possible to declare multiple variables of the same type in a single Dim statement. End Sub 27