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 1e 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 2e 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.
2.
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. 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. 2. 3. 4. 5. 6. 7.
1
INTEGRATED DEVELOPMENT ENVIRONMENT (IDE) .................................................. 3 VARIABLES .......................................................................................................... 9 STRINGS . ........................................................................................................... 15 CONTROL STATEMENTS ...................................................................................... 21 METHODS EN FUNCTIONS ................................................................................... 29 OBJECTS AND ARRAYS ........................................................................................ 35 FILE IO .............................................................................................................. 43
SECTIE 2: APPLICATION PROGRAM INTERFACE TO SOLIDWORKS
8. 9. 10. 11. 12. 13.
49
DESIGN TABLES . ................................................................................................ 51 MACRO’S EN API HELP . ....................................................................................... 57 THE SOLIDWORKS CONNECTION .......................................................................... 61 AUTOMATED DRAFTING ..................................................................................... 67 CONTROLING PARAMETERS ................................................................................ 73 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
S1
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
1
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 corner.
4
in the top right
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 Figure 4 First button on a form. changes to a new image that indicates the direction you can drag the 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.
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.
Current Events 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
8
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.
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
2
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. 2.
Assigning an integer value to a double variable works fine Assigning a floating point value to an integer rounds the decimal fraction
13
CADCAM Deel IV, Design Automation
WHAT HAVE YOU LEARNED
14
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.
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. 2. 3. 4.
Create a new project StringApplication Create a form with two Button controls ProcessButton and ExitButton Add three TextBox controls: FirstNameTextBox, LastNameTextBox and OutputTextBox 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
3
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 Dim Dim Dim
str1 As String str2 As String ix As Integer dy As Double
str1 str2 ix = dy =
= ”3 “ = “3.4 and more text” Integer.Parse(str1) 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)
InStr(str, str2)
Gives the index of string str2 within str* Gives the index of string str2 within str starting at start*
str.IndexOf(str2, 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)
Puts a numeric integer value from str in i Returns True if successful, otherwise False
Double.TryParse(str, d)
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
20
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.
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
4
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. 2. 3. 4. 5.
Create a new project ColorApplication Create a form with two Button controls ProcessButton and ExitButton Add two TextBox controls: InputTextBox and OutputTextBox Set the OutputTextBox properties Multiline field to True, and set the ScrollBars property to Vertical. 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. 2.
3.
Declares the variables needed within the procedure Retrieves the text typed into the InputTextBox and converts the string value to an integer 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 name = InputTextBox.Text OutputTextBox.Clear() For i = 1 To 12 writeLine(name) Next i End Sub
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 fac = 1 OutputTextBox.Clear() writeLine("Factorial function !(x)") For i = 1 To 12 fac = fac * i writeLine("!(" & i & ") = " & fac) Next i End Sub
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
CADCAM Deel IV, Design Automation
WHAT HAVE YOU LEARNED Program flow is the order in which a program executes its statements. An If/Then statement compares the values of data and decides what statements to execute, based on that
evaluation. The Else and ElseIf clause allow If/Then statements to handle many different outcomes. The End If keywords mark the end of a multi‐line If/Then statement, including multi‐line statements with ElseIf
and Else clauses. Relational operators, equal (=), not equal (<>), less than (<), greater than (>), less than or equal (<=), greater than
or equal (>=), enable programs to compare data in various ways. Logical operators (And, Or, Xor, and Not) enable an If/Then statement to evaluate more than one comparison, and
still resolve the expression in a single value. Repetitive operations in a computer program can be handled efficiently by program loops, including For/Next A For/Next loop instructs a program to execute a block of commands a given number of times. In the For/Next loop For x = num1 To num2, the variable a is the loop’s control variable. The loop limits are num1
and num2. A Do/While loop continues to run as long as its control expression is true. Because this type of loop checks the
control expression before running the loop, a Do/While loop can run zero or more times.
28
METHODS AND FUNCTIONS Until now, your programs have been pretty short; each designed to demonstrate a single programming technique. When you start writing real programs, however, you will quickly discover that they can grow to many pages of code. When programs become long, they also become harder to organize and read. To overcome this problem, professional programmers developed something called modular programming, the topic you will study in this chapter. In this chapter:
Organize programs into small parts Write your own procedures Learn to write functions Discover variable scope Find out how to pass arguments to procedures and functions
PREPARATION Before continuing with this chapter’s tutorial prepare a small program in a similar way as you did for the previous chapters: 1. 2. 3. 4. 5. 6.
Create a new project MethodsApplication Create a form with two Button controls StartStopButton and ExitButton Add a Panel control, name it PaintPanel and change its BackColor Rename Form1 to MainForm Set the Text property of MainForm to “Methods” Create an ExitButton_Click method that invokes Close()
When you run your program you should have something similar to the figure above. Your program code will look like the lines below. Public Class MainForm Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click Close() End Sub Private Sub StartStopButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartStopButton.Click End Sub End Class
29
5
CADCAM Deel IV, Design Automation
A TOP‐DOWN APPROACH A full‐length program might contain twenty or more pages of code, and trying to find a specific part of the program in all that code can be tough. To solve this problem, you can use modular programming techniques. Using these techniques, you break a long program into individual subprograms, each of which performs a specific task. To understand how modular programming works, consider how you might organize the creation of a complete detailed design containing several parts. The main task might be called CREATE. Thinking about creating an entire assembly, however, can be overwhelming. So, to make the task easier, you can break it down into a number of smaller steps. CREATE PARTS CREATE ASSEMBLY CREATE DRAWINGS CREATE BOM After breaking the CREATE task down into steps, you have a better idea of what to do. But creating the part is also a pretty big task. So why not break it down, for each separate part down too? CREATE REFERENCE PLANES CREATE BASE FEATURE CREATE DETAILLING FEATURES CREATE CONFIGURATIONS After breaking each part’s creation down into steps, your assembly creation job is organized much like a pyramid, with the general task on the top. As you work your way down the pyramid, from the main task to the part‐by‐part list, and finally to the tasks for each part, the tasks become more and more specific. Getting back to writing a program, though, which is a more conceptual type of task, you might not have a clear idea of exactly what needs to be done. This can lead you to your being overwhelmed by the project. Breaking The length of a Subprogram programming tasks down into steps is called modular You should break programs into small programming. When you break your program’s modules subprograms in order to make program down into even smaller subprograms you are using a top‐ code easier to understand. To this end, down approach to program design. By using top‐down each subprogram in a program should programming techniques, you can write any program as a perform only a single main task, so it stays series of small, easy‐to‐handle tasks. Visual Basic provides short and to the point. When you try to two types of subprograms you can use when writing cram too much functionality into a programs. The first type, method, is covered in the next subprogram, it loses its identity. If you can’t section. The second type, function, is covered later in this state a subprogram’s purpose in two or chapter. three words, it is probably doing too much.
30
Methods and Functions
USING METHODS One type of subprogram is a method. A method is like a small program within your main program. If you were writing an assembly‐design program, the procedures invoked in the main method might be called CreateParts, CreateAssmbly, CreateDrawings and CreateBOM. The CreateParts procedure would contain all the steps needed to create individual parts, where all parts could have their own Create method or could be created with a generic method that is able to configure the part by its design table; And so on. To define your own method, you use the following statements: ‘method without parameters Sub MyMethodName() … End Sub
Suppose you are working on a program that displays its calculation results graphically. Every data point you have found should be depicted as a small triangle. To setup your program in a nice modular way, you first step is to add a method DrawTriangle() like this. Private Sub StartStopButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartStopButton.Click Triangle() End Sub Sub Triangle() Dim size2 As Integer = 6 Dim g As Graphics Dim x As Integer = 30 Dim y As Integer = 20 g = PaintPanel.CreateGraphics() g.DrawLine(Pens.Black, (x - size2), (y + size2), (x), (y - size2)) 'LL to TOP g.DrawLine(Pens.Black, (x), (y - size2), (x + size2), (y + size2)) 'TOP to LR g.DrawLine(Pens.Black, (x + size2), (y + size2), (x - size2), (y + size2)) 'LR to LL End Sub
The code above introduces some new stuff which needs explanation. In the triangle method four variables are used. size2 holds half the size of the triangle, x/y hold the position of the triangle’s center. The special one however, is g. It is a reference variable that we use to draw on the PaintPanel control’s surface. It receives its value in the assignment statement ‘g = …’ After it has been initialized, all kinds of graphical commands can be given by invoking methods from g, like g.DrawLine. But we also can draw rectangles, ellipses, circles, splines etc. When you run the program and press Start/Stop, it should draw one small triangle for you. As you might notice, the coordinate system of the PaintPanel control has its origin (0,0) in the upper left corner. The X‐axis increments from left to right; the Y‐axis increments from top to bottom!
31
CADCAM Deel IV, Design Automation
METHOD PARAMETERS Methods can have parameters that pass a value to the method, or even return a value to the caller (as in TryParse, where the parsed value is returned). In general, however, they are used to put data in. ‘method with one integer parameter Sub MyMethodName1(ByVal x As Integer) … ‘here I can use the parameter x End Sub
You have your nice Triangle method, but how is it going to draw all the other triangles at their different locations? The first version of the method is not versatile enough. The act of drawing a triangle is the same in all locations, but the values for its location are not. So let’s give the Triangle method two parameters: for its x, and for its y. Sub Triangle(ByVal x As Integer, ByVal y As Integer) Dim size2 As Integer = 6 Dim g As Graphics g = PaintPanel.CreateGraphics() g.DrawLine(Pens.Black, (x - size2), (y + size2), (x), (y - size2)) 'LL to TOP g.DrawLine(Pens.Black, (x), (y - size2), (x + size2), (y + size2)) 'TOP to LR g.DrawLine(Pens.Black, (x + size2), (y + size2), (x - size2), (y + size2)) 'LR to LL End Sub
Modify your code to draw three triangles at three different locations (it will take two extra lines). The Number of Arguments For all practical purposes, a method can have as many arguments as you like. But you must be sure the arguments you specify in the method’s call exactly match the type and order of the arguments in the method Sub line. To use more than one argument in a procedure, separate the arguments with commas. For example, to add the argument y to the Arrow call, you would type Call Arrow(x, y). Then, so the arguments match, you must change the first line of Arrow to Sub Arrow (x As Integer, y As Integer). You can use different variable names in the Sub line, as long as they are the same type. In other words, using the arrow example, you can also type Sub Arrow (col As Integer, length As Integer). In the procedure, you would then use the variable names col and length, rather than the original x and y. Procedures don’t need to have arguments. Just leave the brackets empty.
32
The Order of Arguments You can pass one or more arguments to a method. However, keep in mind that the arguments are passed to the method in the order in which they appear in the method call. The method’s Sub line should list the arguments in the same order they are listed in the method call.
Methods and Functions
VARIABLE SCOPE Now that you know a little about procedures, you should know how Visual Basic organizes variables between procedures. Well it is quit simple, there are two places to define variables: inside a method and outside. LOCAL PARAMETERS The local parameters are defined within a method. They can only be reached inside the method and their life span (the time they exist) is often short. This is because they are created when the execution of a method starts, and they are removed when the method is finished (End Sub). Consider the following code. What will be the value of size2, the moment we enter the method for the 11th time in a row? Precisely: it will be zero, because all variables are zero after they are created. Sub MyMethod() Dim size2 As Integer size2 = size2 + 1 End Sub
GLOBAL PARAMETERS If you want persistent data, where values are remembered over a longer period of time (like in your first Garage program), you need variables that exist longer. These are the global parameters. They are defined in the scope of the class. When you give a look at your code, you can see that all the methods of MainForm are defined within a class called MainForm. In this scope you can define variables as well. The example below show a class with two methods that both access the same parameter size2. The variable is defined inside the class, just like the two methods. Beware not to define size2 more than once; you will get two variables with the same name. The second definition will hide the first variable and you will be debugging late hours! Public Class MainForm Dim size2 As Integer = 6 Sub SetSize(ByVal size As Integer) size2 = size / 2 End Sub Sub Triangle(ByVal x As Integer, ByVal y As Integer) 'use size2 to draw triangles End Sub End Class
Note The clue will be clear:
do use global variables for persistent and shared data; use local variables to hold temporary results. do not use global variables as a substitute for parameters.
33
CADCAM Deel IV, Design Automation
USING FUNCTIONS Functions are another way you can break up your programs into small parts. Methods do something ‐change a variable or display information on the screen for instance‐ but unlike methods, functions return a value to the procedure that calls them. Think of them as the sin(x) function on your calculator. You’ve used Visual Basic functions before in this tutorial; the Parse() function, for example. The value it returns is the numerical representation of the characters in a string. To write your own functions, you can use the definition similar to that of a method, with one addition: since the function is returning a value, the definition has to specify the type of data that it will return. Here are two examples. Function toUpperCaseA(ByVal str As String) As String If (str.StartsWith("a")) Then Return str.ToUpper() Else Return str End If End Function
Invoking the method like below will print AAP in the message box. MsgBox(toUpperCaseA(“aap”))
Whether you choose to define a function or a method is a design decision.
WHAT HAVE YOU LEARNED Modular programming means breaking a program up into a series of simple tasks. Top‐down programming means organizing procedures in a hierarchy, with general‐ purpose procedures at the top,
that call specific‐purpose procedures lower in the hierarchy. Methods and functions are the two types of subprograms you can use when writing a Visual Basic program.
Functions return values, whereas procedures do not. A function declaration includes the keyword Function and the function name, as well as the clause ‘As type’, which
tells Visual Basic the type of value the function returns. Methods and functions may have parameters by which they receive values. At the location where the method is
invoked these are called arguments. Local variables are accessible only within the method in which they appear. Global variables, which are declared in
the scope of a class, are accessible anywhere by all methods of that class.
34
OBJECTS AND ARRAYS In this part we will explain what Objects are (you have used them for some time now). It will provide you with a better understanding and it will make you are programming with more confidence. You will not be defining your own objects however, this is possible but way beyond the scope of this programming introduction. Also note that some versions of Basic (VBA) do not support objects. After that you will dig into the use of arrays, a topic that is important for all scientific and technical computing applications. In this chapter:
Learning about Objects, Methods and Classes Lear how to create and use Objects Understand when to use arrays Create arrays and use them with loops Use of mathematical functions
OBJECTS, METHODS AND PROPERTIES Although you may not have noticed, you have worked with several Visual Basic objects already. All controls you have put on your forms are objects plus the form itself are objects. Objects are not limited to elements of the user interface though. As you enter the world of the CAD‐APIs in the next section, you will find out that assemblies and parts are treated as objects, as well as all the features they contain. In all these examples, the objects represent items defined outside your program’s scope. They are predefined by the Visual Basic system or by the SolidWorks system. But you could define and use your own objects as well. g = PaintPanel.CreateGraphics()
In the above statement, the object is PaintPanel (remember it is a Panel control you used in a previous program). PaintPanel has several methods and functions available. One of these functions, CreateGraphics, is invoked here. Some of your variables will hold objects. For instance the PaintPanel variable, or the variable used for the Graphics environment of PaintPanel are both object variables. They are defined just as regular variables, but there type is a class. Dim PaintPanel As Panel Dim g As Graphics
They always need an initial assignment before you can use its methods or functions (like DrawLine). g = PaintPanel.CreateGraphics() g.DrawLine(Pens.Black, 0, 0, 50, 50)
35
6
CADCAM Deel IV, Design Automation
PREPARATION To prepare for this tutorial, start Visual Basic and re‐open the existing project MethodsApplication of the previous chapter. The method to draw triangles is versatile in the sense that the triangles can go anywhere, but, they always are painted on the PaintPanel control. Let’s change that, so it is able to draw on any graphics object. The Triangle method now looks like this Sub Triangle(ByVal g As Graphics, ByVal x As Integer, ByVal y As Integer) Dim size2 As Integer = 6 g.DrawLine(Pens.Black, (x - size2), (y + size2), (x), (y - size2)) 'LL to TOP g.DrawLine(Pens.Black, (x), (y - size2), (x + size2), (y + size2)) 'TOP to LR g.DrawLine(Pens.Black, (x + size2), (y + size2), (x - size2), (y + size2)) 'LR to LL End Sub
You will need to modify the StartStopButton_Click method because the Triangle method’s parameter list has changed. Doing this, you will see the new code is also more efficient. Imagine how often a graphics object is created if you are drawing hundreds of triangles. In traditional programming techniques, methods and data are considered to be separate items. Object‐ Oriented programming adopts the view that a single entity, an Object, should be used to encapsulate both data and methods. Visual Basic is not a pure Object‐Oriented system (like e.g. Java), but a hybrid programming language that mixes traditional elements with the possibility to use objects. Using objects is a very elegant way to structure your program. With them you can hide the information that is not needed elsewhere: this increases your program’s readability and it prevents other parts of the program from (accidental) disturbance of your data. To make sure you get the picture, we will present a number of terms you will encounter when using objects and digging deeper in the Visual Basic documentation.
Objects are encapsulated — imagine an object as box, containing both its code and its data. This makes them easier to maintain than traditional ways of writing code. Visual Basic objects have properties, methods, and events. Classes are the types to define objects. The most familiar types are the controls you used to build the interface. Properties are data that describe an object. They are what you previously would call (global) variables. Methods are things you can tell the object to do. A method is a synonym for procedure or function. 36
Objects and Arrays
CREATING OBJECTS So far, we have used objects and it is not so clear how we got them (maybe with the exception of the Graphics object in the variable g). We know how to define an object variable, but how can we create it? Well, it is simple, just say you need a new object, and use its class as a function to create it. The next two lines show a) declaration of the variable and b) the creation of an object of the type Point. Dim centerPoint As Point centerPoint = New Point()
The Point object has two properties (kind of variables) that can be accessed: its X‐ and its Y‐value centerPoint.X = 10
The function to create objects often has a number of versions. The code above shows the version for Point() without any parameters. But creating an object often is often accompanied with initialization. So there versions provided, where we can plug in the initial values in one go, like the next code shows. centerPoint = New Point(10, 10)
We can even combine the actions declaration, creation and initialization in one line. This is not less work for the computer, but it delivers more compact and (sometimes) more readable code. Dim centerPoint As Point = New Point(10, 10)
PUTTING THE OBJECTS IN PLACE Now it’s time to put your new acquired knowledge into use in your program. Modify your Triangle method, so it uses three objects for its Top, Left and Right corner point. A few lines are given as an example, plug in missing part yourself. Sub Triangle(ByVal g As Graphics, ByVal x As Integer, ByVal y As Integer) Dim size2 As Integer = 6 Dim pTop, pLeft, pRight As Point pTop = New Point(x, y - size2) pLeft = … pRight = … g.DrawLine(Pens.Black, pLeft, pTop) g.DrawLine(…) g.DrawLine(…) End Sub
By now, you should be capable of implementing a version of Triangle, that handles the following parameter list (yes, it involves modifications inside the Triangle method as well). Triangle(g, new Point(30, 20))
37
CADCAM Deel IV, Design Automation
ARRAYS Using variables makes your program flexible: one algorithm like the triangle‐drawing can be used in many different situations. Thanks to variables, you can conveniently store data in your programs and retrieve it by name. You also can get and store data from your program’s user. The best thing about variables is that they can constantly change value. They are called variables, after all, since they are variable. So far you’ve learned about various types of numerical variables as integer, double and long. You also know about string variables which can hold text. Imagine now, like in a CAD system, your program needs to keep track not just of one or ten points, but of thousands or hundreds of thousands of points. You would need quite a long list of Dim‐statements to create all these variables if Visual Basic (as other programming languages) did not have a smart approach for these situations. It is time to explore one last data type: the array. An array is a single variable that holds many items. The items can be of any type, as long as it is the same type for all of them. The number of items you can store in an array depends on the size you give it in the definition of the array variable. The next line show an array to hold hundred integers. The second line specifies an array to hold strings in a situation where the number of items is unknown yet. However, somewhere in the code, before putting data in the array, one must specify its dimension with a ReDim statement. Dim intArray(100) As new Integer Dim strArray() As String ReDim strArray(10)
Accessing a single elements of an array is accomplished with an index. You write the name of the array variable, and append the index between parenthesis. The lowest index is 1, the highest is the dimension you specified for the array in its declaration. The indexed array is a single item, and it behaves as a variable of that particular type (e.g. a single Integer or String). intArray(1) = 17 intArray(2) = intArray(1) + 3 strArray(10) = “aap” MsgBox(strArray(10))
Note The range for the index does not follow the same convention in all programming language. Most languages use a zero‐based index, where the first element is selected like arr(0); whereas Basic, which by the way is one of the oldest languages around, uses 1‐based indexing.
38
Objects and Arrays
Putting the Icing on the Cake It is time to make our Triangle program a bit more exciting. For the extended version of the program, the steps to take:
add a function that creates random points add a function that calculates the distance between two points make a create function that returns an array filled with points
Random Points We will be using a function that makes random numbers. It is provided in the Random class. First we need a persistent (= global) object created with this random class. The variable is defined in the MainForm class. Public Class MainForm 'Global variables go here Dim randomGenerator As Random = New Random()
Then, we create the definition for our point generating function. Our randomGenerator object creates a new double value between 0.0 … 1.0 every time we call NextDouble(). We can scale this value to a new range, for instance from 0 .. 100, by multiplying it. Function randomPoint() As Point Dim x As Integer x = (100 * randomGenerator.NextDouble()) End Function
The tasks in the function body are 1) get the right scale, 2) put the random values in x and y, 3) create a Point, 4) return the result. You can use the PaintPanels Height and Width property to create the right scaling. If you don’t, your triangles could be drawn outside the panel (=invisible). Function randomPoint() As Point Dim maxX As Integer = PaintPanel.Width Dim maxY As Integer = PaintPanel.Height Dim x, y As Integer x = (…) … Return New Point(x, y) End Function
Distance between Points You need to decide, when you build a function, about: its name, what it will do, its arguments, the kind of results it will return. For the distance function, you may use the following template. As you can see below, it will return an integer distance. For simple graphics, counting the distance in pixels is perfectly ok. In CAD systems (the next tutorial) we need to be more precise and always use the double type for coordinates and hence for distances. Visual Basic contains a library with mathematical functions such as Sin, Cos, Sqrt. You can access then from the Math class (without creating an object as in Random). You recognize Pythagoras’ theorem don’t you? Function distance(ByVal p1 As Point, ByVal p2 As Point) As Integer 'to prevent crashes with large numbers, work with double Dim dx, dy As Double dx = p2.X - p1.X dy = p2.Y - p1.Y Return Math.Sqrt(dx * dx + dy * dy) End Function
39
CADCAM Deel IV, Design Automation Function returning an array with Points The function that returns an array willed with random Point objects receives the number of points as an parameter. 1) An array is declared, with that parameter as the dimension. The dimension does not need to be a constant, as you can see, making this function much more flexible. 2) The array is filled with data, and 3) the array ids returned as the function’s result. Function generate(ByVal size As Integer) As Point() Dim pntArray(size) As Point For index = 1 To size pntArray(index) = randomPoint() Next Return pntArray End Function
Integration To put the newly added functions to work, 1) declare a global pntArray, 2) modify the code of StartStopButton_Click so that a) pntArray is initialized by generate() with say 50 points, b) clear the PaintPanel and c) add a for‐loop to draw triangles at the locations in the points array. Dim pntArray() As Point
To clear the panel, you need a call to a method of the graphics object: g.Clear(Color.Beige)
Note: some of the triangles are painted so close to an edge of the paint panel, that they are not completely visible. This mechanism is called clipping. You could change your random point generator in such a way that no clipping occurs. However, in computer graphics, read in CAD systems, it is quite natural that objects are only draw partially due to zoom and pan operations.
40
Objects and Arrays
GET INTERACTIVE This part of the exercise is a kind of dessert, it tastes good but it can be skipped if you are in a hurry. But when you continue, you will put your first steps in the world of interactive computer graphics. You will extend the program so it handles mouse‐clicks in the paint panel, and highlights triangles that are hit. The steps involved are
modify the Triangle method, so it is able to paint selected triangles and unselected triangles handle the mouse‐click event and get the coordinates of the click‐position draw triangles in red to give visual feedback o the user
Triangle method The method is given an extra argument. It is of type Boolean (remember the values are true or false). The method header will look like this. Sub Triangle(ByVal g As Graphics, ByVal p As Point, ByVal selected As Boolean)
In the method create an extra variable with the name pen of the type Pen. Use an if‐then‐else‐endif construction that assigns the value Pens.Red or Pens.Black to pen. Of course in the if(), the parameter named selected is tested. Dim pen As Pen If (selected) Then … … End If g.DrawLine(pen, pLeft, pTop) …
Now we can paint black as well as red triangles, depending on the value of the third parameter of Triangle(). Initially, no triangles are selected, so set the third argument in StartStopButton_Click to create black shapes. Click position To add an event handler (a method) that is called when the user clicks in the PaintPanel, do this ‐ ‐
Go to the Design tab and select PaintPanel with a single click On the right in the Properties pane, you will see the list of the PaintPanel’s properties. We will need to see its event list/ Click on the lightning symbol , and look for the MouseClick event. Double‐click on it. Visual Basic will create a new method called PaintPanel_MouseClick.
You can return to the regular properties with button on the left of the lightning button.
41
CADCAM Deel IV, Design Automation In the method, create the two variables. The variable d will hold the distance between the click position and the center of a triangle. The variable g is the reference to the graphics object. You will need it to paint the red triangles. Private Sub PaintPanel_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PaintPanel.MouseClick Dim d As Integer Dim g As Graphics g = PaintPanel.CreateGraphics() 'loop to test all triangle locations for a hit … End Sub
Things left to do are to calculate the distance and to take the appropriate action. You already added a method for it, distance, that accepts two points. One point is the click location, which is available in the parameter e. The other point comes from the pntArray holding the triangle centers. d = distance(e.Location, pntArray(index))
Add the loop and calculate the distance as shown above. Then use an if() statement to draw a red triangle when the user clicked close enough to the centre (a distance < 4 worked well in my version). Statement: Your program will respond 2 x faster when you exit the for‐loop as soon as a hit occurs. Can you explain why it is two times, and can you predict another behavior of your program that will change?
WHAT HAVE YOU LEARNED Objects contain methods and properties. The syntax to use a method or function is objectName.MethodName().
The syntax to use a property is objectName.PropertyName. An object variable is declared as a regular variable, but has a Class as its type. Properties are data that describe an object. They are what you previously would call (global) variables. Methods are things you can tell the object to do. A method is a synonym for procedure or function. Object must be created before their methods or properties can be used. An array is a variable that holds many items of the same type. Single elements of an array are selected with an integer index: myArray(index). The index range is 1..size. The type and the dimension of the array is are set at its declaration. Handle click‐events and retrieve the mouse coordinates
42
FILE IO As you have used your computer, you will have noticed that most applications save and load data to and from your hard disk. The applications you write with Visual Basic don’t have to be any different; they too, can save information to a disk file. If you ever need to move data from your program to another or vice versa –be it MathLab, SolidWorks or Excel‐ you are going to love this chapter! In this chapter: In this chapter:
Open and close files, Save data to a file, Load data from a file, Create a file path to My Documents
PREPARATION Before continuing with this chapter’s tutorial prepare a such a program: 1. 2. 3. 4. 5. 6.
Create a new project FileApplication Rename the Form1 to MainForm, set the Form’s text to File IO Create a GroupBox with the text Data points In the GroupBox add three buttons. Set the button’s names and text. Also add a Panel control PaintPanel. Change it’s background color. Add an Exit button
You can copy/paste some of the code from project MethodsApplication into this project: 1. 2. 3. 4.
Method Triangle(), to do the painting Method randomPoint(), to a create random location Method generate(), to create an array with points The global variables randomGenerator and pntArray
43
7
CADCAM Deel IV, Design Automation
STEPS IN ACCESSING A FILE This tutorial covers the strait forward yet very versatile format of the sequential text‐file. Text files are human readable. You can open them with NotePad for example and read the content because they contain the same characters as present on your keyboard. Many programs support reading and writing these files, making it an ideal format to exchange data. Simple file handling is actually an easy process. However, you need to perform three steps to be sure that your program’s data gets properly tucked away in that data structure called a file. Those steps are as follows: 1. 2. 3.
Open the file Send data to the file or read data from the file Close the file
In the following sections, you will cover each of these steps in detail.
OPENING A FILE Probably the most complicated part of managing file IO (Input/Output) is opening the file in the proper mode. You see, not only can files be used to save and load data, but they also can be used to save and load specific kinds of data in specific ways. For example, there is a big difference between opening a file to read a line of text and opening a file to read a database record, even though a file must be opened in both cases. You can’t load data from a file until you’ve saved data to the file. Here is the Visual Basic statement that opens a file in the Output mode: Dim filePath As String = "c:\testdata.txt" FileOpen(1, filePath, OpenMode.Output)
The first number “1” is a number that will be used to reference this opened file. We can chose any number here, as long as it is not at the same time used for another open file. The string that follows the file number is the path and name of the file you want to open. In this case, the file is called “testdata.txt” and is located in the root directory of drive C. Now comes the part that determines the file mode. See the For Output? That tells Visual Basic you want to open the file in the Output mode. This mode enables a program to save data to the disk file. If the file doesn’t already exist, Visual Basic creates it. If the file does exist, Visual Basic gets the file ready to accept output from your program, which includes erasing the current contents of the file.
SAVING DATA TO THE FILE Your file is now open, sitting there patiently waiting to receive data. Something you can accomplish with Visual Basic commands like this: WriteLine(1, "some text") WriteLine(1, "another line”, “ of text") WriteLine(1, x, y, z)
The file number is the same number, the program used to open the file. 44
File IO
After the file number, you place a comma and follow it with the data you want to save to the file. As you can see, you can add one or more data items here. Every method call will generate a single line, all items in the parameter list will be written on this line in the file.
CLOSING THE FILE You finish the task by closing the door to the file’s data. After you place data into the file, you must close the file; otherwise, you will end up losing parts of the data. To close a file, you call upon the Close statement FileClose(1)
TRYING IT OUT When you prepared a program as a basis for this exercise it will take only a few steps to create your fully fledged program that is capable of saving data to disk and loading data from a disk file. Your program has four buttons:
Exit terminates the program New creates a new set of data points and paints them on the screen Save saves the data to a file Load loads the data from a file and points them on the screen
The thing left to do for you is providing these buttons with the appropriate instructions in their click‐event method. The next section will discuss all four of them.
Exit The Exit button needs little effort: just type a single line in the method’s body that calls Close().
NEW The New button should do two things 1. 2.
Assign an array with 50 new points to pntArray. Invoke a method that draws all points contained in the (global!) variable pntArray.
Like pntArray = generate(50) drawAll()
The painting of all triangles is put in a single method drawAll(), because we anticipate that this action is also required for other buttons. You are able to add this method to your program (in case you forgot, look how you wrote the paint‐code in the previous project).
45
CADCAM Deel IV, Design Automation
Save The actions for the Save button are a) create a string with the pathname to the file, b) open the file for output, c) write the data, d) close the file. Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click Dim filePath As String filePath = System.IO.Path.Combine( My.Computer.FileSystem.SpecialDirectories.MyDocuments, "testdata.txt") FileOpen(1, filePath, OpenMode.Output) For index = 1 To 50 WriteLine(1, pntArray(index).X, pntArray(index).Y) Next FileClose(1) End Sub
After reading the discussions in this chapter, the single new item in this code is the construction of a file path. Instead of putting in a fixed path like “c:\temp\testdata.txt”, we use a construction that involves a little more typing by the programmer but will provide a lot of convenience for the user of the program. The question always is “where do I put my files” and the answer is “certainly not all over your computer’s disk, but in a location where everybody expects user data”. This definitely is the My Documents folder. Every user has its own My Documents. Fortunately Microsoft helps us resolving the path to the current user with a utility in System.IO.Combine as is shown in the previous code. When I print the variable filePath on my system, it will say filePath = "C:\Documents and Settings\hans\My Documents\testdata.txt".
46
File IO
Load The actions for the Load button are a) create a string with the pathname to the file, b) open the file for input, c) read data, d) close the file, e) draw the points just read. FileOpen(1, filePath, OpenMode.Input) Dim count As Integer = 0 Dim x, y As Integer Do While (Not EOF(1)) And (count < 50) 'Input(1, line) Input(1, x) Input(1, y) 'get xy from line count = count + 1 pntArray(count) = New Point(x, y) Loop FileClose(1) drawAll()
Reading the file –step b)‐ can use some explanation because it contains some new elements. The input code is contained in a loop. We could have used a for‐loop and read 50 lines, but we are not sure about the number of lines. The common approach reading files is: read until there is nothing more to read. The end of the file is signaled by the EOF function. It returns True, when the End Of File is reached. We want to read, as long as there is no EOF, hence the expression Not EOF(1) in the while loop. Another safe guard is the use of count. As we read lines, we keep track of the number of lines read in the count variable. If the number exceeds 50, we cannot store them in our array, so we stop reading. In other words, the while loop may cycle as long as (not an EOF) AND (less than 50 lines). Inside the loop there are two input statements for the two variables x and y. Together they process one line in the file. After successfully retrieving the coordinates, we can increment count and use count as an index in the array to store the new value. When finished with the loop, you can close the file and update the screen.
THAT’S IT Test you program and check whether it writes a file (open it with NotePad to check). Also check if it is retrieving the original data from the file, after you’ve hit the New button a few times.
47
CADCAM Deel IV, Design Automation
WHAT HAVE YOU LEARNED Accessing a file requires three steps: Opening the file, saving or loading data to or from the file, and closing the
file. The Open statement opens a file in Input or Output mode. WriteLine stores data items in an open file. Every call to WriteLine creates one line in the file. The items in the
parameter list are put in a single line. The Input method loads data from an open file. When a program finishes working with a file, it must close the file with the Close statement. Failure to close the
file properly could result in lost data. The EOF function returns True when the program has reached the end of a file and returns False if the program
has not reached the end of the file. The user’s files are by convention put in the My Documents folder. Microsoft has added a utility to create the file
path to that folder.
48
APPLICATION PROGRAM INTERFACE TO SOLIDWORKS De tweede sectie van de handleiding behandelt de verbinding die gemaakt kan worden tussen zelf ontwikkelde programmatuur en de SolidWorks software. Hierbij wordt gebruik gemaakt van de Application Program Interface (API) van dat systeem. Deze interface bestaat uit een (groot) aantal data‐ types en methodes. Ieder hoofdstuk behandelt een aspect van de mogelijkheden aan de hand van een opdracht, bijvoorbeeld het werken met attributen of het door een programma laten opbouwen van een assembly. Na het doorlopen
Weet je welke soorten functies de API van een CAD‐systeem heeft en kun je er mee werken Kun je Design Tables ontwerpen en gebruiken Weet je wat je wat macro’s zijn en kun je ze zelf maken Kun vanuit je software geometriegegevens opvragen Kun je programma’s ontwikkelen om ontwerpactiviteiten te automatiseren Heb je inzicht in de mogelijkheden, de benodigde ontwikkelinspanning en de voordelen die een CAD‐API een bedrijf kan bieden
49
S2
CADCAM Deel IV, Design Automation
INHOUD Een CAD API biedt een zeer omvangrijke interface naar de functionaliteit die in zo’n systeem aanwezig is. Elke functie die via het scherm is te activeren vindt je ook in de interface terug als methode, plus nog grote groepen methoden die op lagere niveaus in de datastructuur werken. De beschrijving van het geheel beslaat vaak meerdere boekwerken met elk 400 ‐ 600 pagina’s. Het lezen en begrijpen ervan vergt programmeerkennis plus kennis van het specifieke CAD systeem want de API’s zijn niet gestandaardiseerd: ieder systeem heeft een eigen API. Deze tutorial bevat korte oefeningen die elk één van de mogelijkheden demonstreren. Het doorlopen van deze tutorial kost ongeveer 4 uur. De zeven hoofdstukken:
50
Design Tables Afmetingen van onderdelen worden in SolidWorks bepaald door parameters. Design Tables geven de mogelijkheid verschillende configuraties te bouwen van onderdelen of assemblies door zogenaamde driving parameterwaarden te configureren met een spreadsheet. Macros and API Help geven een inleiding gegeven over het gebruik van de SolidWorks macro faciliteiten. De macro taal van SolidWorks is (niet toevallig) dezelfde als de API programmeertaal Visual Basic. Voorbeelden maken duidelijk hoe je macro’s kunt opnemen en afspelen. Tegelijk maakt u kennis met eenvoudige Basic programma’s die opdrachten aan SolidWorks geven. Sletching Hier wordt stap voor stap het eerste ‘echte’ Visual Basic programma gebouwd. Er wordt een programma gemaakt waarmee ruwheidsymbolen in een tekening worden geplaatst. Controling Dimensions is een voorbeeld van het werken met onderdelen families. Uit één tekening en een tabel met parameter waarden wordt een familie van parts gegenereerd. De tabel is een Excel spreadsheet, de celwaarden besturen de dimensies van het onderdeel. Attributen maken, toekennen en opvragen In SolidWorks kunnen gegevens worden toegevoegd aan het model in de vorm van attributen. Eerst wordt een attribuut type gedefinieerd, daarna wordt het aan een feature toegekend, vervolgens kunnen er attribuut waarden in worden gezet. Creëren van een Assembly behandelt een voorbeeld dat een nieuwe assembly aanmaakt met reeds bestaande onderdelen. Vanuit configuratie wensen van een gebruiker/ontwerper wordt de assembly ingericht. Aan de orde komen het toevoegen en plaatsen van onderdelen in de assembly, alsmede het gebruik van geometrische transformaties en mates.
DESIGN TABLES Afmetingen van onderdelen worden in SolidWorks bepaald door parameters. Een parameter ontstaat wanneer een dimension (maat) wordt toegevoegd. De waarde van een parameter kan worden gewijzigd om een nieuwe geometrie te creëren. Design Tables maken het mogelijkheid om verschillende configuraties te bouwen van onderdelen of assemblies door zogenaamde driving parameterwaarden in een spreadsheet te plaatsen. Eén regel in een design table vormt een configuratie met voor iedere parameter een waarde. In de figuur op deze pagina zie je de schets met zijn parameters, en de design table met drie configuraties. In de hoofdstuk leer je design tables te gebruiken.
Dimensies hernoemen Design Tables maken Design Tables invoegen Design Tables aanpassen Configuraties gebruiken
51
8
CADCAM Deel IV, Design Automation
DIMENSIONS HERNOEMEN Bij het plaatsen van features en dimensions worden door het CAD‐systeem automatisch namen toegekend als BaseExtrude1 en D1@Sketch3. Zulke namen zijn vrijwel betekenisloos. In een kleine part heb je snel genoeg uitgezocht hoe het model in elkaar zit. In een part of assembly met honderden features en dimensions daarin tegen, kan het een hele klus zijn om de juiste wijziging aan te brengen. Vooral bij modellen die al een tijdje terug zijn gemaakt of die door een collega zijn opgebouwd is dat lastig. Het onderhoud aan modellen gaat vele malen doeltreffender wanneer je de moeite neemt om de gedachten die je tijdens het modelleren hebt ook even in te typen in de vorm van namen die wel zeggen waarop de parameters betrekking hebben. Voor onderdelen die gebruikt worden in een automatiseringtraject is dit welhaast een must. 1.
2.
Kopieer de folder ..\Install_dir\VBasic naar je werkgebied en open uit de gekopieerde folder ..\VBasic\Start\Design Tables het bestaande part Part_Design_Table.sldprt. Edit de sketch Pakking. De dimensies, zoals in onderstaande figuur, komen in beeld. Tussen haakjes is de naam van de desbetreffende dimensie weergegeven. (zo niet: click View in het menu en selecteer Show dimension names). Deze namen zullen worden gebruikt in de design tables.
Voor de oefeningen zijn een aantal bestanden beschikbaar. Kopieer vooraf de VBasic folder naar je eigen werkgebied en gebruik verder deze kopie.
3.
Verander de naam van de dimensie die de afstand tussen de twee gaten aangeeft (**) in AfstandCenters. Doe dit door de dimensie te selecteren en in het Properties venster in Primary Value de naam te veranderen.
Bij Primary Value is de syntax van de dimensienaam te zien: [Name]@[naamsketch].
4. 5.
Save het aangepaste part onder de naam Pakking. Laat het programma SolidWorks met de Pakking actief en start Microsoft Excel op.
52
Design Tables
DESIGN TABLES AANMAKEN 1.
Open een nieuw werkblad in Excel en voer de informatie in zoals hieronder is weergegeven. In de eerste rij dienen de dimensienamen van de SolidWorks part te worden opgenomen, in de volgende rijen staan de variant‐namen plus hun bijbehorende parameterwaarden.
De maten zijn aangegeven in millimeters.
2.
Zoek in de Pakking.sldprt de dimensienaam D1@Dikte op. Hint Kijk bij de Edit Dimension Access, zie figuur.
3.
Save de spreadsheet onder de naam Pakking.xls in je werkdirectory en sluit Excel.
4.
Ga terug naar de part Pakking in SolidWorks.
INVOEGEN DESIGN TABLES 1.
Click Insert, Design Table. De Design Table PropertyManager verschijnt.
2.
Selecteer de From file optie, click Browse en open de Pakking.xls spreadheet.
3.
Click OK
.
53
CADCAM Deel IV, Design Automation 4.
Het Excel bestand wordt zichtbaar in je part. In dit bestand kan, net als in Excel zelf, gewoon gewerkt worden. Door buiten de spreadsheet in het part te klikken zal het Excel weer verdwijnen. Op elk gewenst moment kan het ook weer worden opgeroepen (zoals verderop nog aan de orde komt).
Wanneer alle dimensienamen uit de spreadsheet (in de 1e rij) door SolidWorks worden herkend, zullen er drie configuraties zijn aangemaakt. 5.
Behalve dat het excelbestand zichtbaar wordt, lijkt er weinig veranderd te zijn. Echter, naast de Default configuratie zijn de drie afmetingen nu ook als configuraties opgenomen. Dit is zichtbaar te maken door het Configuration‐tablad te selecteren onderaan de window van de FeatureManager design tree.
6.
Double click op Variant 1 en kijk wat er gebeurt. Test ook de andere configuraties. De radii aan boven‐ en onderzijde missen duidelijk de tangent relatie. Pas dit aan.
54
Design Tables
DESIGN TABLES AANPASSEN Eenmaal ingevoegde design tables kunnen eenvoudig worden aangepast. 1. 2.
Click Edit, Design Table, Edit Table. De spreadsheet die eerder is ingevoerd verschijnt weer. Verander een aantal waarden en kijk wat het effect daarvan is. Om de nieuwe variant te activeren, moet je buiten de spreadsheet klikken.
Via een design table is het ook mogelijk model features, sketches en reference geometry te onderdrukken. Daarvoor dient in een kolomhoofd de volgende tekst worden opgenomen: $STATE@feature. Waarbij feature de naam is van het feature dat al of niet onderdrukt moet worden. Voordat getoond kan worden hoe dit feature onderdrukken in zijn werk gaat, moet er eerst een feature gemaakt worden in ons part. Als voorbeeld creëren we een extra gat in de pakking. 3.
Selecteer het bovenvlak van de pakking en geef de positie aan waar het gat moet komen.
4.
Click Simple Hole , zoals voorgedaan in bovenstaande plaatje. Geef een diameter op van 10 mm. Laat het gat door de hele dikte van de pakking gaan (through all).
5.
Selecteer de Hole feature in de design tree met een rechtermuis click. Selecteer Edit Sketch. Positioneer het gat volgens onderstaand figuur en verander de dimensienamen zoals is weergegeven (via de properties).
6.
Save het part onder de naam ‘Pakking_met_feature’.
55
CADCAM Deel IV, Design Automation 7.
Click op Edit, Design Table, Edit Table.
8.
Vul de kolommen H,I en J in, zoals is weergegeven. In kolom J kan worden aangegeven of het feature Hole1 wel of niet onderdrukt moet worden in het part; suppressed (S) of unsuppressed (U). Bekijk de verschillende configuraties.
9. 10. Verander (Edit, Design Table, Edit Table) de afronding van de zijkant van de pakking (AfrondingZij@Pakking) door in cel C2 de waarde 30 mm te veranderen naar 40.
Het feature Hole1 blijkt niet meer netjes aan de rand te zitten. Om dit te voorkomen kunnen in de spreadsheet relaties tussen cellen onderling worden opgegeven. 11. Verander nu de dimensie in de Design Table die deze afstand bepaalt (Afstand@Sketch1) zó, dat deze waarde gekoppeld is aan de straal van desbetreffende afronding.
12. Probeer verschillende waarden voor de afronding (cel C2) en bekijk het effect. Doe hetzelfde voor de overige varianten.
13. Save en sluit het aangepaste part.
56
MACROS EN API HELP Dit hoofdstuk geeft een inleiding gegeven in het gebruik van de SolidWorks macro faciliteit. In een macro kunnen een aantal standaard handelingen worden vastgelegd. Een gebruiker kan er, in plaats van steeds weer de zelfde commando’s te geven, bijvoorbeeld eenmalig een aantal commando’s in opnemen en deze vervolgens gebruiken door de macro te starten. De macro taal van SolidWorks is (niet toevallig) dezelfde als de API‐programmeer taal ‐Visual Basic. Het opnemen van macro’s is niet alleen voor gebruikers makkelijk; voor ontwikkelaars is het een snelle manier om inzicht te krijgen in de methodes die voor verschillende handelingen nodig zijn. Met behulp van een voorbeeld wordt uitgelegd hoe je macro’s kunt opnemen en afspelen. Je maakt kennis met eenvoudige Basic programma’s die via API‐aanroepen opdrachten aan Sworks geven. De volgende onderwerpen komen in dit hoofdstuk aan de orde:
Opnemen van Macro’s Afspelen van Macro’s Gebruik van de API Help
U leert om te gaan met macro’s door ze zelf op te nemen en vervolgens de opgenomen code te bekijken en te veranderen.
57
9
CADCAM Deel IV, Design Automation
OPNEMEN EN AFSPELEN VAN MACRO’S In deze paragraaf wordt het opnemen, het veranderen en afspelen van macro’s in SolidWorks behandeld. Ook wordt uitgelegd hoe informatie uit de API Help file gebruikt kan worden. Wanneer de toolbar niet zichtbaar is, kies je View, Toolbars, Macro
1. 2. 3.
4. 5.
Start SolidWorks en select Tools, Macro, Record. Open een nieuw part en creeer in het Front Plane een sketch. Teken rechte lijn in en sluit de sketch. Stop het opnemen van de macro door op de Stop button in de macro toolbar te clicken. Save de macro in je eigen werkdirectory. Bekijk de zojuist opgenomen macro via Tools, Macro, Edit en kies de juiste file. Is te achterhalen wat hiervoor is opgenomen?
6.
Open de SolidWorks API Help documentatie. Selecteer de Index‐tab en type in “NewDocument”. NewDocument() is de eerste methodes die wordt aangeroepen in Sub Main(). Hieronder zie de Help info. Het beschrijft de functie en de parameters van de methode en er worden links gegeven naar voorbeeldtoepassingen.
Open de API Help files van SolidWorks via de SolidWorks menubalk: Help,
58
Macros and API Help
Iedere keer dat SolidWorks een nieuw part opent, krijgt het part een naam met een oplopend nummer.
7. Ga nu terug naar SolidWorks en run de Marco enkele malen. Iedere keer krijg je een nieuwe part en wordt een sketch toegevoegd. Je kunt switchen naar een ander Part via het Window commando in het SolidWorks menu (linker figuur). Wanneer je alle parts bekijkt, zie je in de feature tree dat alle sketches die de marcro heeft gemaakt in Part1 terecht zijn gekomen (rechter figuur).
8. Sluit alle parts (maar niet het programma). 9. Edit de macro via het commando in de macro toolbar. Het is niet zo’n luxe ontwikkelomgeving als Visual Studio, maar je kunt editen en de macro runnen. Ook de syntax is iets anders: methoden hebben wel parameters, maar deze staan niet tussen haakjes. Sub main() Set swApp = Application.SldWorks Set Part = swApp.NewDocument("C:\ProgramData\SolidWorks\SolidWorks 2010\templates\Part.prtdot", 0, 0, 0) swApp.ActivateDoc2 "Part1", True, longstatus Set Part = swApp.ActiveDoc Dim myModelView As Object Set myModelView = Part.ActiveView myModelView.FrameState = swWindowState_e.swWindowMaximized boolstatus = Part.Extension.SelectByID2("Front Plane", "PLANE", 0, 0, 0, False, 0, Nothing, 0) Part.SketchManager.InsertSketch True Part.ClearSelection2 True Dim skSegment As Object Set skSegment = Part.SketchManager.CreateLine(0#, 0#, 0#, 0.040712, 0#, 0#) Part.ClearSelection2 True Part.SketchManager.InsertSketch True Set myModelView = Part.ActiveView myModelView.FrameState = swWindowState_e.swWindowMaximized End Sub
10. Je kunt overigens we haken om de parameters plaatsen , maar de methode moet dan worden aangeroepen met Call ervoor zoals in de regel hieronder. Wel zo duidelijk. Call swApp.ActivateDoc2("Part1", True, longstatus)
11. De regel die het probleem met de sketch veroorzaakt staat hierboven. Wanneer een docoment geladen is, maakt het deze actief. Dat heeft hetzelfde effect als wanneer een gebruiker in het Window menu Part1 kiest. Alle invoer daarna komt in de actieve part , dat is dus altijd Part1. Maak de macro meer algemeen toepasbaar door die regel uit te schakelen (zet er een commentaar ‘ voor) of te verwijderen. Test daarna opnieuw (met de run button). ‘Set Part = swApp.ActivateDoc ("Part1", True, longstatus)
12. Creëer een meer complexe macro, waarbij meer handelingen worden verricht. Vergelijk de gecreëerde code met de code die over het betreffende onderdeel te vinden is in de help file. Plaats bijvoorbeeld een cirkel met als middelpunt het eindpunt van de eerste lijn.
59
CADCAM Deel IV, Design Automation
API DOCUMENTATIE De volledige API documentatie is te vinden onder het Help menu. 1.
2.
3. 4. 5.
6.
7.
60
Kies API Help Wanneer je een specifieke functionaliteit zoekt, terwijl de functienaam niet bekend is, is het gebruik van de Index‐tab van de API help documentatie en enkele kernwoorden de snelste manier om de functie te vinden. Zoek de functie op om een lijn te creëren door in te typen “Create Line”.
Als blijkt dat de Index‐tab niet de gewenste informatie oplevert, kan de Find‐tab geraadpleegd worden, deze zoekactie neemt echter meer tijd in beslag. Zoek via de Find‐tab informatie op over het concentrisch maten in een assembly. Deze zoekfunctie lokaliseert de AssemblyDoc::AddMate functie Click op Display en bekijk het informatie scherm. Via de API‐Help kunnen ook programmeer voorbeelden gevonden worden. Deze voorbeelden kunnen als basis dienen voor hetgeen dat gebouwd moet worden. Wanneer je de naam niet precies weet kan de Search optie nuttig zijn. Zoek bijvoorbeeld ‘mass’ naar het voorbeeld (VBA) van het ophalen van mass properties van je een model. Let er op dat er voorbeelden in Visual Basic .NET zijn gegeven, maar andere in het VBA dialect.
Je kunt de voorbeelden eenvoudig zelf testen door ze te copy /pasten in een eigen macro!
THE SOLIDWORKS CONNECTION Dit hoofdstuk legt uit hoe de communicatie tussen van zelf ontwikkelde software met SolidWorks wordt gerealiseerd. Het programma is een zogenaamde Stand‐Alone applicatie, net als Word of Excel, die communiceert met een ander Stand‐Alone programma, in dit geval dus SolidWorks. Het voordeel deze aanpak boven het gebruik van (uitgebreide) macro’s zijn, de uitgebreide mogelijkheden van de User Interface en dat gebruiksvriendelijkheid van de ontwikkelomgeving (Visual Studio en daarmee ook Visual Basic zijn gepolijste producten). Het bouwen van een geïntegreerde toepassing met de knopjes in het SolidWorks menu –zoals PhotoWorks of CamWorks‐ vergt programmeervaardigheid buiten de scope van dit vak. In een aantal stappen wordt een programma opgebouwd. Aan de hand van instructies met toelichting voeg je code toe aan een ‘lege’ applicatie en bouw je een klein programma.
Openen bestaand Visual Basic project Toevoegen van de API bibliotheken Uitleg Programma Structuur Eerste Run Programma Uitbreiden van het Programma
De doelen zijn: leren hoe de SolidWorks verbinding tot stand komt en hoe je opdrachten aan het CAD‐ systeem geeft. Dit alles in een ontwikkelomgeving waar je al aan gewend bent, de Visual Basic Express van Microsoft. Hoewel dit programma niet veel ‘doet’, levert het begrip op. Verder kan het dienen als basis voor het bouwen van eigen toepassingen.
61
10
CADCAM Deel IV, Design Automation
OPEN A VISUAL BASIC PROJECT De manier van programmeren en de link naar SolidWorks wordt uitgelegd aan de hand van een al opgezet Visual Basic programma. Het is de bedoeling dat je deze zogenaamde startcode stap voor stap uitbreidt tot een goed werkende applicatie. Kopieer uit de folder ..\Install_dir\VBasic\Start de folder WindowsApplication VB SW naar je werkgebied. Start Visual Basic en open het bestaand project WindowsApplication VB SW.sln uit de directory in je werkgebied. Het bestaande programma bevat al basiscode. Dubbel‐klik in de Solution Explorer op MainForm om de form zichtbaar te krijgen. De code die bij de form hoort kan in beeld gebracht worden met een rechter‐muis‐klik op MainForm in de Explorer, gevolgd door View code. 1.
Voor deze oefening zijn twee VB projecten beschikbaar. Eén versie in ..\Start en één in ..\Finish Kopieer vooraf de VBasic folder naar je eigen werkgebied en gebruik verder deze kopie.
De programma tekst die nu verschijnt is de code waarmee verder gewerkt wordt.
De User Interface is compleet met omgeving en de aanroep van de event‐methodes. Van de code is het frame van het programma aanwezig. Door het toevoegen van eigen programmaregels bouw je het om tot een werkende applicatie. We beschrijven hierna de code per button.
62
The SolidWorks Connection
GEBRUIK VAN LIBRARIES Veel softwareonderdelen die je gebruikt voor de ontwikkeling van een programma zijn ondergebracht in bibliotheken. Voorbeelden zijn de Controls die je gebruikt voor je User Interface, maar ook de Math bibliotheek of de SolidWorks API. De meest gebruikte bibliotheken worden standaard door Visual Studio gevonden. De SolidWorks API moeten we echter zelf toevoegen. Het project WindowsApplication VB‐SW dat je hebt geladen bevat deze referentie al voor SolidWorks 2010. Heb je een nieuwere versie van SolidWorks, of start je met een nieuw project, dan kun je deze referenties toevoegen (of opnieuw toevoegen).
In de Solution Explorer, dubbel‐klik op de My Project node. In de Project Designer (tab), klik op de References tab. Controleer of deze referenties voorkomen, of ze voor de juiste SolidWorks versie zijn, en of ze kunnen worden gevonden. Verwijder referenties met een foutmelding.
Als ze er niet zijn, klik je op de Add button onder de References lijst. Selecteer voor SolidWorks twee entries: “Type Library” en “Constant type library” zoals in de afbeelding hieronder.
Klik op OK en sluit de Project Designer venster (Tab blad).
63
CADCAM Deel IV, Design Automation
CONNECT EN EXIT BUTTON Het programma heeft één globale variabele met als naam sldWorks. Deze variabele bevat een object dat de verbinding met SolidWorks onderhoud. Kijk maar bovenin de code, onder de definitie van de class MainForm, of je deze variabele ziet staan. De taak voor de Connect button is het initialiseren van de verbinding. Wanneer SolidWorks al draait verbindt het programma zich daarmee, anders start het zelf een SolidWorks op. Wanneer de verbinding lukt wordt dat zichtbaar op de Form in het Process ID venster. In het eerste stukje code wordt een object gemaakt en de verbinding tot stand gebracht (kan seconden duren). Ook het tweede stukje is eenvoudig: hier bepalen we dat dit programma, en niet de gebruiker kiest of SolidWorks kan worden afgesloten, en we kiezen ervoor om SolidWorks zichtbaar te maken. In het derde groepje statements wordt het nummer van het proces opgehaald in ter info in de TextBox control geplaatst. Plaats deze code in de body van de methode ConnectButton_Click. ' Fire up SolidWorks: ' - this will create an object of the "SldWorksClass". swApp = New SldWorks.SldWorks() ' Make the SolidWorks main window visible. ' do I take control or the user?? swApp.UserControl = False swApp.Visible = True ' Update the process ID text box. ProcIdTextBox.Text = swApp.GetProcessID().ToString()
Na de start behandelen we ook de finish. Het programma kan worden beëindigt met een klik op de Exit button. Hier moeten we de verbinding netjes beëindigen, om te voorkomen dat SolidWorks hangt, of dat er gegevens verloren gaan. De gebruiker mag kiezen of hij/zij SolidWorks in de lucht wil houden doormiddel van de checkbox op de form. Als Exit SolidWorks niet is aangevinkt, wordt dit programma beëindigt en blijft SolidWorks gewoon staan. De eerste actie bij deze button‐click is het testen van de waarde van de CheckBox control. Dat doe je door te kijken naar de waarde van de property Checked. Zo ja: beëindig SolidWorks door de ExitApp methode aan te roepen. Daarna sluit de MainForm. Plaats deze code in de body van de methode ExitButton_Click. If (SwExitCheckBox.Checked = True) Then ' Exit SolidWorks: ' - the SolidWorks main window will disappear. swApp.ExitApp() End If ' Close myself Close()
Je kunt nu het programma testen. De twee knoppen die je hebt toegevoegd zouden hun werk moeten doen. Als er succesvol een verbinding wordt gemaakt zie je een Process ID verschijnen.
64
The SolidWorks Connection
NEW PART BUTTON Het zal geen verrassing zijn dat de New Part knop een nieuwe Part gaat aanmaken. Er gebeurt hetzelfde als wanneer een (SolidWorks) gebruiker op File, New, Part klikt. In die part maken we een sketch met een paar lijnen net als in de vorige Macros en API Help tutorial. De verbinding naar SolidWorks is beschikbaar in de globale variabele sldWorks. Voor de zekerheid testen we toch maar of die een waarde heeft gekregen. Misschien heeft de gebruiker niet op Connect gedrukt, of is SolidWorks helemaal niet geïnstalleerd op dit systeem. Stap twee is het creëren van de nieuwe part. Waar de gebruiker bladert in een folder met templates moeten we hier in de methode aanroep de keuze opgeven. Let op de “_” aan het eind van de regel. Het zegt “dit statement gaat op de volgende regel verder”. Daarna willen we de gebruiker laten zien wat er gebeurt: de Part‐view wordt maximaal afgebeeld (een Maximize van het document). Er wordt een sketch object aangemaakt nadat de Front Plane is geselecteerd. En in de sketch worden twee lijnsegmenten toegevoegd. De coördinaten lijken klein maar het zijn SI eenheden, meters dus. Elementen die worden toegevoegd zijn automatisch geselecteerd. Dat maken we ongedaan met een ClearSelection. Als laatste sluiten we de sketch en inserten deze in de part met de optie rebuild=true. Vervolgens déselecteren we de sketch‐feauture. Plaats deze code in de body van de NewPartButton_Click Methode. If (swApp Is Nothing) Then Exit Sub ' create new part part = swApp.NewDocument("C:\ProgramData\SolidWorks\SolidWorks 2010" _ & "\templates\Part.prtdot", 0, 0, 0) ' view it maximized Dim myModelView As SldWorks.ModelView myModelView = part.ActiveView myModelView.FrameState = SwConst.swWindowState_e.swWindowMaximized ' create sketch on Front Plane Dim boolstatus As Boolean boolstatus = part.Extension.SelectByID2("Front Plane", "PLANE", _ 0, 0, 0, False, 0, Nothing, 0) part.SketchManager.InsertSketch(False) ' create a series of line/arcs Dim skSegment As SldWorks.SketchSegment skSegment = part.SketchManager.CreateLine(0.0#, 0.0#, 0.0#, 0.04, 0.0#, 0.0#) skSegment = part.SketchManager.CreateLine(0.04, 0.0#, 0.0#, 0.04, -0.04, 0.0#) part.ClearSelection2(True) ' insert sketch & clear selection part.SketchManager.InsertSketch(True) part.ClearSelection2(True)
Note Je komt met enige regelmaat in de API calls methodenamen tegen die eindigen op een cijfer 2, 3 of hoger. Dit zijn nieuwere versies. De oude blijven nog één of twee versies van SolidWorks aanwezig maar zijn op een gegeven moment verdwenen. Als waarschuwing staat in de documentatie (ja onder SolidWorks Help, API Help Topics) Obsolete. Superseded by ClearSelection2().
65
CADCAM Deel IV, Design Automation
ADD LINE BUTTON Het Add Line commando gaat in een geopende schets een extra lijnstuk en een cirkel plaatsen. Daarvoor dient de gebruiker een sketch te hebben geopend. De eerste controle ken je al, deze test of er überhaupt een SolidWorks verbinding actief is. De tweede test controleer op een actieve part, en de derde test op een geopende sketch. De gebruiker dient dus een Edit Sketch commando te hebben gegeven. Al deze checks lijken overbodig, maar je wilt natuurlijk niet dat je programma bij iedere vergissing van de gebruiker crasht. Voor diezelfde gebruiker is het ook vervelend wanneer het programma iets niet wil, zonder daar een duidelijke melding bij te geven. Bedenk dat controles weinig moeite kosten, noch voor de computer noch voor de programmeur, en dat ze veel gebruiksgemak opleveren. Daarna het creëren van een lijn en een cirkel tussen twee punten, gevolgd door het de‐selecteren en het sluiten van de sketch zoals je ook bij de vorige button zag. Plaats deze code in de body van de AddLineButton_Click Methode. If (swApp is Nothing) then Exit Sub 'check for open part part = swApp.ActiveDoc If (part Is Nothing) Then MsgBox("Please open a part", MsgBoxStyle.Exclamation) Exit Sub End If 'check for open sketch If (part.SketchManager.ActiveSketch Is Nothing) Then MsgBox("Please open sketch first") Exit Sub End If 'create line and circle, insert sketch, clear selection Dim skSegment As SldWorks.SketchSegment skSegment = part.SketchManager.CreateLine(0.0#, 0.02, 0.0#, 0.02, 0.0#, 0.0#) skSegment = part.SketchManager.CreateCircle(0.0#, 0.02, 0.0#, 0.02, 0.0#, 0.0#) part.ClearSelection2(True) part.SketchManager.InsertSketch(True)
66
AUTOMATED DRAFTING In dit hoofdstuk wordt uitgelegd hoe het toevoegen van tekst en geometrie aan een tekening in zijn werk gaat. Je gaat een applicatie realiseren die ruwheidsymbolen in een SolidWorks tekening kan toevoegen. De volgende stappen komen hierbij aan de orde:
Pictogram op een button Lijnen, cirkels en tekst Raadplegen API documentatie Omgaan met de schaal van een Drawing sheet
Het aangeven van een locatie in een tekening en een klik op de gewenste afbeelding is alles wat er nodig is om een ruwheidsymbool te plaatsen. In de volgende paragrafen wordt duidelijk hoe je een dergelijk programma kunt opbouwen.
67
11
CADCAM Deel IV, Design Automation
OPEN A VISUAL BASIC PROJECT De manier van programmeren en de link naar SolidWorks wordt uitgelegd aan de hand van een al opgezet Visual Basic programma. Het is de bedoeling dat je deze zogenaamde startcode stap voor stap uitbreidt tot een goed werkende applicatie. Kopieer de folder ..\Install_dir\VBasic naar je werkgebied en start Visual Basic. Open het bestaand project Sketching.sln uit de gekopieerde directory ..\VBasic\Start\Sketching\.. 1.
Click File, Open project, Sketching.sln
Voor deze oefening zijn twee VB projecten beschikbaar. Eén versie in Sketching\Start en één in Sketching\Finish Kopieer vooraf de VBasic folder naar je eigen werkgebied en gebruik verder deze kopie.
2.
Click View, Project Explorer. Open het MainForm.frm door een double click. De form van de dialog verschijnt.
Het bestaande programma bevat al basiscode. De programma code kan in beeld gebracht worden met een rechter‐muis‐klik op MainForm in de Explorer, gevolgd door View code. 3.
De programma tekst die nu verschijnt is de code waarmee verder gewerkt wordt.
Het is het frame van het programma. Door het toevoegen van eigen programmaregels bouw je het om tot een werkende applicatie. Eerst volgt er uitleg over de code die er nu staat.
68
Automated Drafting
PROGRAMMA STRUCTUUR Je hebt inmiddels al zoveel button‐click programma’s gezien dat je deze snel zult doorgronden. Het programma bestaat uit één form genaamd MainForm. Dit is het venster dat wordt afgebeeld wanneer het programma start. Hierop zijn drie knoppen aanwezig om drie verschillende symbolen te kunnen maken. Naast de rechter knop staat een text box. De tekst die de gebruiker daar invult Op de knoppen wordt in het symbool geplaatst zoals het ook op de afbeelding op de button is staan plaatjes. Zulke knoppen weergegeven. De andere twee symbolen hebben geen tekst. Er zijn drie button‐click event methoden aanwezig, maar deze hebben nog geen invulling. Het is de bedoeling dat je die methoden gaat maken.
kun je ook zelf maken. Via de property Image, kun je een bitmap-file importeren. Bitmaps (tif / bmp) van 48 x 48 pixels voldoen meestal prima.
EERSTE RUN PROGRAMMA Nu de programma structuur bekend is kun je al eens kijken wat het programma doet. 1.
Click
2.
Click op de eerste afbeelding . De volgende messagebox verschijnt op het scherm. Vergelijk de tekst in de box met de code zoals in de vorige paragraaf is geprogrammeerd. Stop het programma door op de Stop knop in de taakbalk te klikken.
3.
4.
(run). De nevenstaande dialog verschijnt
69
CADCAM Deel IV, Design Automation
UITBREIDEN VAN HET PROGRAMMA Omdat de implementatie voor , het derde symbool, het meest uitgebreid is van de drie, wordt hiervan de methode stap voor stap gerealiseerd. De andere twee symbolen kun je vervolgens op vergelijkbare wijze realiseren.
DOEL Het is de bedoeling dat dit symbool: na aanklikken van button3, verschijnt op een geselecteerd punt in de drawing in SolidWorks. Er wordt begonnen met de geometrie van het symbool. Naast het geselecteerde punt is er nog een gegeven noodzakelijk voor de dimensies van het ruwheidsymbool: de grootte van het symbool. De tekst die moet worden toegevoegd komt later aan de orde. Het teken wordt geconstrueerd met behulp van 3 punten: het punt dat wordt geselecteerd –punt 1‐ en de twee eindpunten van de schuine lijnstukken.
IMPLEMENTATIE Het eerste dat we doen is een connectie met het SolidWorks programma maken. Daarna volgen twee controles: 1) is er een document geopend en 2) is dat document een drawing. In deze 2e controle zie je iets nieuws, namelijk het gebruik van constanten die al in de SolidWorks API zijn gedefinieerd. Ze staan per groep in een class (lichtblauw). De class DocumentTypes bevat constanten voor Part, Assembly en Drawing. Het zijn gewoon integers maar deze schrijfwijze is vele malen meer leesbaar dan wanneer er zou staan “(swDoc.GetType() <> 3)“. ' connect to SW swApp = New SldWorks.SldWorks() swDoc = swApp.ActiveDoc
' Use the active document.
' no document, nothing to do If swDoc Is Nothing Then MsgBox("No document loaded or program attached to different " _ & "SolidWorks session!", MsgBoxStyle.Question, vbInformation) Exit Sub End If ' swDoc is a ModelDoc, which can be a Part, Assembly or Drawing If (swDoc.GetType() <> SwConst.swDocumentTypes_e.swDocDRAWING) Then MsgBox("Please open a drawing document.", MsgBoxStyle.Question, vbInformation) Exit Sub End If
Bekijk ook info in de API‐help van GetType. Daar zijn er heel veel van. Welke versie moet je hier hebben? Juist, swDoc is een ModelDoc2 object.
70
Automated Drafting
Dit stukje programma kun je al testen. Het is verstandig om dat regelmatig te doen. Zo’n werkwijze heet incremental testing. Het is makkelijker om fouten te vinden in een klein stukje code, dan om 1000 tegels in te typen en dan maar te zien wat er gebeurt. Start SolidWorks en open een nieuwe drawing. Plaats enkele lijnen in die tekening en selecteer een eindpunt. Ga nu terug naar je programma en start de test. Als het goed is krijg je geen enkele foutmelding: niet van Visual Studio (programmeer fouten), maar ook niet van het programma zelf (No document loaded). De volgende actie is het achterhalen van een geselecteerde locatie. Hiervoor wordt de Selectie Manager gebruikt. Via selMgr kunnen we geselecteerde objecten en locaties ophalen. Ook kijken we of de gebruiker wel iets heeft geselecteerd (Count > 0). PickPt heeft van GetSelectedPoint een array met drie double variabelen gekregen. Op index (0,1,2) staan de XYZ‐waarden. Hiermee kunnen we de juiste coördinaten voor de lijnen van het symbool berekenen. ' get selected point Dim selMgr As SldWorks.SelectionMgr selMgr = swDoc.SelectionManager Dim PickPt As Object 'Door de gebruiker geselecteerde punt PickPt = selMgr.GetSelectionPointInSketchSpace(1) If (selMgr.GetSelectedObjectCount = 0) Then swApp.SendMsgToUser2("Select a location first...") Else Dim x2, y2, x3, y3 As Double 'Eindpunten van de lijnen x2 = PickPt(0) + 0.005 y2 = PickPt(1) + 0.01 x3 = PickPt(0) - 0.0025 y3 = PickPt(1) + 0.005 ' .. End If
Om ongewenste verschuivingen tengevolge van Grid‐snap of Object‐snap te voorkomen schakelen we die optie tijdelijk uit. Je programma mag echter geen gebruikersinstellingen zomaar aanpassen, dus slaan we de huidige waarde op, om die later weer terug te kunnen zetten. Eindelijk tekenen we nu de drie lijnstukken van het symbool. ' add directly to database, to avoid snapping to grid or other ' but save old value, so we can restore it Dim oldAddToDB As Boolean = swDoc.GetAddToDB() swDoc.SetAddToDB(True) swDoc.CreateLine2(PickPt(0), PickPt(1), 0.0#, x2, y2, 0.0#) swDoc.CreateLine2(PickPt(0), PickPt(1), 0.0#, x3, y3, 0.0#) swDoc.CreateLine2(x3, y3, 0.0#, (x3 + 0.005), y3, 0.0#)
71
CADCAM Deel IV, Design Automation De tekst vergt iets meer moeite. Wanneer de gebruiker een schaal van 1:10 of 1:50 heeft ingesteld, maakt dat veel uit voor de grootte waarmee tekst wordt afgebeeld. De teksthoogte wordt namelijk niet in sheet‐ coordinaten ingevoerd maar in database (= SI) coordinaten. Dus rekenen we zelf terug door de ingestelde schaal op te vragen. In de documentatie die je vindt in SolidWorks, Help, API, staat onder GetProperties (ISheet) het volgende The return value is the following array of seven doubles: [ paperSize, templateIn, scale1, scale2, firstAngle, width, height ] where: paperSize = Paper size. This value is a long packed into a double and is represented by the swDwgPaperSizes_e enumeration. templateIn = Template index. This value is a long packed into a double and is represented by the swDwgTemplates_e enumeration. scale1 = Scale numerator. scale2 = Scale denominator. firstAngle = Value is a boolean packed into a double and returns True if the sheet is using first angle projection and false if not. width = Paper width. height = Paper height.
Voor de schaal is er dus een teller en een noemer gedefinieerd, op index 2 en 3 van de array met doubles. Kijk in de API handleiding welke parameters de methode CreateText2() verwacht en beredeneer waarom je symbool op de juiste plaats komt. Je kunt zelf de variabelen bovenaan in Button3_Click declareren. sheet = swDoc.GetCurrentSheet() Dim sheetProps As Object = sheet.GetProperties() scaling = sheetProps(2) / sheetProps(3) textHeight = 0.0025 ' 2.5 mm textX = (x3 - 0.0005) * scaling textY = (y3 + (2 * textHeight)) * scaling ' grab text from text box NN = "N" + NnTextBox.Text() ' put text on the symbol swDoc.CreateText2(NN, textX, textY, 0.0#, textHeight, 0.0#)
De methode wordt afgerond (binnen de if-else-endif) met deselectie van de aangemaakte elementen en het terug zetten van de Auto‐snap optie. ' deselect & restore AddToDB swDoc.ClearSelection2(True) swDoc.SetAddToDB(oldAddToDB) End If
Test het programma zorgvuldig. Het in orde wanneer je geen VB fouten krijgt en zonder crash symbool 3 kunt tekenen op de plaats waar je daarvoor in de tekening hebt geklikt. De code voor symbool 1 en 2 kun je met copy /paste en wat edit werk nu op eigen kracht realiseren.
72
CONTROLLING PARAMETERS In een Parametric CAD systeem is het geometriemodel opgehangen aan parameters. De parameters worden in schetsen en features als variabelen gecreëerd en er worden waarden aan toegekend. Dit hoofdstuk laat zien hoe je parameters kunt benaderen in de datastructuur van het CAD‐systeem, hoe je waarden opvraagt en hoe je nieuwe waarden toekent. Het is een belangrijk mechnisme waarmee je vanuit je eigen software de controle krijgt over alle afmetingen en attributen van een geometriemodel. De SolidWorks terminologie heeft enkele inconsistenties in de naamgeving van de gehanteerde begrippen. In de volgende tabel zijn de belangrijkste begrippen voor dit hoofdstuk naast elkaar gezet om een mogelijke verwarring te voorkomen of in ieder geval verminderen. CAD terminologie Model is een representatie van de geometrie of van andere eigenschappen van een product. Parameter is een variabele waarmee het model kan worden gewijzigd. Dimensie is een afmeting in het model.
Configuratie is een set onderdelen en parameterwaarden.
SolidWorks Model is een Part, Assembly of Drawing.
API / Visual Basic Model is een object van de class ModelDoc2.
Dimension is een maat in een schets of feature, met een naam en een waarde. Display dimension is een visuele weergave van een bemating in een Drawing view of ander afbeelding van het model.
Dimension is een object van de class Dimension. Een Dimension bestuurt een maat geometrie. Display dimension is een object van de class IDisplayDim. Een dimension kan meer dan een keer zijn afgebeeld, bijvoorbeeld in meerdere aanzichten van een tekening. Dit zijn IDisplayDim objecten. Ze refereren naar hetzelfde Dimension object. Een dimension (parameter) waarde kan in de Actuele configuratie worden gewijzigd, maar ook in alle configuraties tegelijk.
Configuration is een combinatie van een features en parameters, waarbij de waarden in een Design table staan.
In dit hoofdstuk:
Doorzoeken user selection Opzoeken van parameters Parameterwaarde opvragen Nieuwe parameterwaarden toekennen Het gebruik van API constanten
73
12
CADCAM Deel IV, Design Automation
VOORBEREIDING Voor deze tutorial heb je een SolidWorks part nodig en het Visual Basic programma dat wordt uitgebreid tot de uiteindelijke toepassing. SOLIDWORKS PART
Start SolidWorks en creëer een nieuw part. Voeg een Sketch toe, met daarin een gesloten contour. Plaats enkele Dimensions in de schets. Sluit de sketch af en maak een 3D model met de Extrude feature. Je hoeft het part niet te saven, maar laat wel het SolidWorks programma actief. Ze de weergave van Dimension Names aan door deze optie te kiezen in het View menu. VISUAL BASIC PROJECT
Kopieer uit de folder ..\Install_dir\VBasic\Start de folder Controlling Parameters naar je werkgebied. Open het project Controlling Parameters.sln uit die directory in je werkgebied.
74
Controlling Parameters
PROGRAMMA FUNCTIONALITEIT Een SolidWorks dimension (SolidWorks terminologie) heeft een naam. Deze naam wordt, net als de namen van features, in eerste instantie door het systeem zelf toegekend. Voorbeelden zijn D1 of D2 als namen voor de parameters die zijn gekoppeld aan een maat (Dimension) zoals je ze in een Sketch feature plaatst. Om duidelijk te maken om welke D1 het gaat, wordt daar de featurenaam aan toegevoegd als in D1@Sketch1. Met het programma dat je gaat bouwen kunnen dimensions in een Part worden opgezocht en aangepast. Dit kan op twee manieren: door invoer van de naam of door selectie in SolidWorks. Van de gevonden parameter worden de naam en de waarde weergegeven. De waarde kan worden gewijzigd door een nieuw ingevoerde waarde toe te kennen of door een schaalfactor toe te passen. Linksonder geeft een indicator aan of de verbinding met SolidWorks en een geopende Part kan worden gemaakt: rood = nee, groen is ja.
HULP METHODEN Het zal duidelijk zijn dat de knoppen van het programma (zie bovenstaande figuur) alle vier hun eigen click‐event methode krijgen. Voor met de invulling daarvan aan de slag te gaan, voegen we eerst twee ondersteunende functies toe. Methoden of functies pas je toe wanneer een stuk code op meer dan één plek wordt gebruikt ‐of‐ wanneer de code van een methode niet meer op het scherm past. connectToPart() Is de methode die een verbinding met SolidWorks opent en een referentie naar het open document ophaalt. De kleur van de indicator, de IndicatorPanel control, wordt aangepast om het resultaat zichtbaar te maken. swApp en swPart zijn globale variabelen die ook in de button‐click methoden zullen worden gebruikt. De fuctie geeft een boolean waarde terug: False=mislukt, True=ok. Private Function connectToPart() As Boolean ' This function tries to an open a Part in SolidWorks ' Returns True for succes, False in case of failure ' Additional the color of the Indicator Panel is set to show the current state: ' -green = ok, red = fail ' Fire up SolidWorks: ' - this will create an object of the "SldWorksClass". swApp = New SldWorks.SldWorks() If (swApp Is Nothing) Then IndicatorPanel.BackColor = Color.Red Return False End If
75
CADCAM Deel IV, Design Automation 'check for open part swPart = swApp.ActiveDoc() If (swPart Is Nothing) Then IndicatorPanel.BackColor = Color.Red Return False Else IndicatorPanel.BackColor = Color.LightGreen End If ' Make the SolidWorks main window visible. ' do I take control or the user?? swApp.UserControl = False swApp.Visible = True Return True End Function
De tweede hulpmethode is findSelectedDimension(). Er wordt twee locale variabelen gebruikt: swDim is een Dimension object, slMgr is een referentie naar een Selection Manager object. Via slMgr wordt opgevraagd hoeveel geselecteerde items er zijn, en met dat aantal wordt een loop gestart. Per item wordt getest of het een DisplayDim item is. Op het beeldscherm worden DisplayDim objecten weergegeven en niet de Dimension objecten. De DisplayDim objecten hebben wel een referentie naar het originele Dimension object dat we zoeken.
Zodra een item van dat type is gevonden wordt een resultaat teruggegeven –Return swDim‐ (en daarmee de loop voortijdig beëindigd). Als er niets van onze gading is geselecteerd wordt er Nothing terug gegeven.
Private Function findSelectedDimension() As SldWorks.Dimension ' This function tests whether one of the selected objects is a dimension. ' It returns the found dimension or Nothing Dim swDim As SldWorks.Dimension Dim slMgr As SldWorks.SelectionMgr ' any items selected? slMgr = swPart.SelectionManager For index = 1 To slMgr.GetSelectedObjectCount2(-1) ' check the types, we are looking for Dimensions If (slMgr.GetSelectedObjectType3(index, -1) = _ SwConst.swSelectType_e.swSelDIMENSIONS) Then ' yes, the user selcted a dimension Dim swDispDim As SldWorks.DisplayDimension swDispDim = slMgr.GetSelectedObject6(index, -1) ' dimensions can be displayed in many views ‘ (hence one Dimension has many DisplayDim's) ' we want the real thing: the parameter that controls geometry swDim = swDispDim.GetDimension2(0) Return swDim End If Next Return Nothing End Function
Voeg beide hulpmethoden toe aan de code van je eigen programma. Je vindt de methode headers aan het eind van de code van MainForm.
76
Controlling Parameters
FIND De methode FindButton_Click() checkt met de eerste hulpmethode of er een part is geopend. Gaat dat goed, dan test de methode of er een naam is ingevuld in de NameTextBox. Als er tekst staat wordt daarmee naar een Dimension object gezocht door Parameter(). Als het veld leeg is wordt de lijst met geselecteerde items doorzocht op een Dimension object door je eigen methode findSelectedDimension(). 'check for open part If (Not connectToPart()) Then MsgBox("Please open a part", MsgBoxStyle.Exclamation) Exit Sub End If ' search for a name or use the selected dimension If (NameTextBox.Text <> "") Then ' search the featurelist for the dimension 'name' in the textbox swDim = swPart.Parameter(NameTextBox.Text) Else ' no name in the textbox, maybe the user selected a dimension swDim = findSelectedDimension() End If
Het tweede deel van de methode verwerkt de informatie. Wanneer er geen Dimension object is gevonden krijgt de gebruiker daarvan een melding. Is er wel een gevonden, dan worden naam en waarde op et scherm gezet. Neem er notie van de dit programma de millimeters als eenheid gebruikt. Voor het afbeelden (en na inlezen) moeten deze worden omgerekend naar SI‐eenheid voor lengte. De schaalfactor is als globale waarde gedefinieerd bovenin je programma. ' if found, show its values If (swDim Is Nothing) Then MsgBox("Dimension " & NameTextBox.Text & " not found", MsgBoxStyle.Exclamation) Exit Sub Else ' update form: show dimension in [mm] NameTextBox.Text = swDim.GetNameForSelection() ValueTextBox.Text = (swDim.GetSystemValue2("") / screenToSI).ToString End If
Je kunt nu beide invoermogelijkheden van het programma testen (met SolidWorks actief).
Voer een dimension name in en kijk of met Find de juiste data erbij wordt gevonden Maak het naamveld leeg en selecteer een dimension in SolidWorks. Test of met het commando Find de naam en waarde worden afgebeeld.
77
CADCAM Deel IV, Design Automation
CHANGE De methode ChangeButton_Click() wijzigt de waarde van de afgebeelde parameter. De methode begint dus met enkele tests:
Is er een geopende Part? connectToPart() Is er een dimension geselecteerd (Not swDim Is er iets in NewValueTextBox ingevuld?
is Nothing)
Als dit allemaal ok is, kan de waarde uit de genoemde textbox worden geconverteerd naar een double. In de Strings tutorial heb je gezien in “Converting Strings to Numbers”, hoe de Double.TryParse methode daarvoor gebruikt kan worden. Dan volgt een conversie naar de juiste eenheden en het toekennen van die waarde aan de swDim parameter. Hieronder zie je een stukje van die code. If (conversie is OK) Then ' valid number, convert it to SI units & set dimension newValue = newValue * screenToSI swDim.SetSystemValue3(newValue, _ SwConst.swSetValueInConfiguration_e.swSetValue_InThisConfiguration, "") End If
In de bovenstaande code komt ook het gebruik van constanten weer terug. Het zijn lange betekenisvolle namen voor doodgewone integers. In de API manual zie je bij de methodeaanroep de verwijzing naar het type. Als je dat type intypt (het lichtblauwe deel) geeft Visual Basic je alle constantennamen in een lijst waar je uit kunt selecteren. Type maar in een methode deze regel: SwConst.swSetValueInConfiguration_e.
Zodra je de ‘.’ invoert, verschijnt de lijst met opties. Test het Change commando. Zet daarvoor SolidWorks en je eigen programma naast elkaar op het scherm. Je ziet dan meteen hoe door de wijziging van de parameter je model wordt aangepast.
SCALE EN EXIT Beide laatste commando’s kun je op eigen kracht afronden. Vergeet niet dat na aanpassing van de waarde ook de ValueTextBox.Text ververst moet worden (net als na een succesvolle Find). Note Er zijn drie methoden van naamgeving voor Dimensions in SolidWorks: binnen een Feature, binnen een Part en voor gebruik in een omgeving met meerdere parts en assemblies. De API bevat voor alle drie een verschillende methode om die naam op te halen. swDim Name > D1 swDim Selection name> D1@Sketch1 swDim Full name > D2@
[email protected]
78
CREATING ASSEMBLIES Er zijn veel ontwerpsituaties waarin de oplossing bestaat uit een assembly die is opgebouwd uit standaard delen. Dit hoofdstuk laat zien hoe softwareinstructies zulke oplossingen vliegensvlug kunnen creeeren. De assembly kan een wisselende configuratie van onderdelen bevatten, terwijl de onderdelen zelf ook ook configureerbaar kunnen zijn. Daarmee wordt deze aanpak een ideale techniek om de verscheidenheid aan oplossingen te vergroten en tegelijk de hoeveelheid parts beperkt te houden. Je gaat in dit hoofdstuk een programma maken dat een assembly opbouwt als bouwgroep fungeert voor een motorfietskoppeling. De onderwerpen in dit hoofdstuk:
Onderdelen in een Assembly toevoegen Onderdelen positioneren met mates Onderdelen verplaatsen met geometrische transformaties Top Down ontwikkelen
VOORBEREIDING Voor deze tutorial heb je SolidWorks parts nodig en het Visual Basic programma dat wordt uitgebreid tot de uiteindelijke toepassing. SOLIDWORKS PARTS
Bij deze opdracht worden drie onderdelen gebruikt die al zijn gemodelleerd. Voor een goede werking van het programma dat je gaat uitwerken moeten die bestanden bereikbaar zijn. Maak daarvoor de map SWparts aan in je eigen My Documents folder. Kopieer daar de volgende drie bestanden naar toe: BaseDisk.sldprt, metalDisk.sldprt en FibreDisk.sldprt . VISUAL BASIC PROJECT
Kopieer uit de folder ..\Install_dir\VBasic\Start de folder Creating Assemblies naar je werkgebied. Open het project Creating Assemblies.sln uit die directory in je werkgebied. Je kunt het programma al starten en krijgt dan het rechts afgebeelde window op je scherm.
79
13
CADCAM Deel IV, Design Automation
THE CLUTCH Het programma dat je gaat bouwen configureert het platenpakket voor een koppeling. Het is een natte koppeling, wat betekent dat de koppelingsplaten gesmeerd worden met olie. Dit type koppeling vindt je in vrijwel alle hedendaagse motorfietsen als element in de aandrijflijn tussen de motor en de versnellingsbak. Hieronder zie je drie afbeeldingen. Links staat een exploded view met bovenaan een drukgroep met daaronder een platenpakket, en onder in de hoek de inner housing (5) en de outer housing (2) (flink in‐zoomen). De afbeelding rechtsboven is een inner housing. Rechtsonder zie je een foto van het platenpakket met om‐en‐om de stalen en de fiber platen.
Inner housing
Exploded view clutch Yamaha XS 650
Set clutch plates plus springs
WERKING De inner housing is gemonteerd op de ingaande as van de versnellingsbak. Om dit onderdeel worden om‐en‐om stalen en fiber platen geplaatst. Op de foto zie je van beide één gemonteerd. De inner housing heeft een vertanding waarop de binnenvertanding van de stalen platen past. Bij de outer housing is het omgekeerd. Die heeft sleuven waar de nokken in vallen die de fiber platen op hun buitendiameter hebben. De outer housing heeft tandkrans die wordt aangedreven door een tandwiel op de krukas. Het platenpakket wordt op elkaar geduwd door een zestal veren. Daarmee is de verbinding rotatiegesloten. Activeren van de koppeling haalt de spanning van de veren en daarmee de druk van het platenpakket. In die toestand kunnen de inner‐ en outer housing vrij van elkaar draaien.
80
Creating Assemblies
DE STARTVERSIE Het programma heeft een eenvoudige User Interface die dit moet het gaan doen:
Exit – verlaat het programma Generate – bouwt de assembly volgens de ingestelde specificaties Pairs – het aantal paren (staal + fiber) koppelingsplaten in de assembly Clutch type – er kunnen drie typen koppeling worden gemaakt. Het type bepaalt met welke configuratie van de stalen‐ en fiber plaat de assembly wordt opgebouwd. Rpm en Power – Twee invoervelden die nog niet worden gebruikt. Hier kan t.z.t. een specificatie worden opgegeven van de eigenschappen van de oplossing –note in tegenstelling tot de andere velden, waar je opgeeft hoe je oplossing er uit ziet!
GLOBALE VARIABELEN EN HET LOAD EVENT Er worden in het programma maar twee globale variabelen gebruikt. De eindversie zal bijna tien methoden en functies bevatten, maar voor de communicatie daarmee ga je vooral parameters gebruiken. De swApp variabele is een oude bekende en hoeft geen toelichting. In de declaratie van de variabele configNames zie je dat het een array variabele is: een array van strings. Er is nog niet opgegeven hoeveel elementen de array heeft en er wordt ook nog geen data ingezet. ' global variables Dim swApp As SldWorks.SldWorks Dim configNames As String()
' connection to the SolidWorks API ' array with configuration names
Je bent al bekend met methoden die worden uitgevoerd zodra een button wordt ingedrukt. Deze methoden zijn zogenaamde Event Handlers. Er bestaan ook andere gebeurtenissen waarvoor een event handler kan worden ingevuld. Bijvoorbeeld Form Load, het event dat ontstaat zodra een Form object voor het eerst op het scherm wordt geplaatst. Dat tijdstip is een geschikt moment om de initialisatie van een programma uit te voeren. Dubbelklik op MainForm in de Solution Explorer om de MainForm [Design] zichtbaar te maken. De form is nu geselecteerd, je ziet de eigenschappen in het Properties venster rechts onder het venster van de Solution Explorer. Het properties venster heeft vier knopjes. Met knop 1 en 2 kun je de volgorde van de properties veranderen: (1) Categorized of (2) Alphabetical. Met (3) Propeties zoals je gewend bent, of (4) Events, alle events die er beschikbaar zijn. Probeer ze alle vier. Klik nu op , zoek het Load event op en dubbelklik daar; je springt nu net als bij dubbelklik op een button naar de juiste methode. Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' create the list of clutch configurations configNames = {"Standard", "High", "Racing"} ' enter the names in the typelist ComboBox CluchTypeComboBox.Items.AddRange(configNames) ' watch the index, first one is 0 CluchTypeComboBox.SelectedIndex = 0 ' deafult no disk pairs PairsTextBox.Text = "4" End Sub
81
CADCAM Deel IV, Design Automation De parts die in de assembly worden geplaatst kennen verschillende configuraties. De configuraties zijn in de MetalDisk en FibreDisk parts opgeslagen als een embedded spreadsheet. Je hebt dit al eerder gezien in het hoofdstuk over Design Tables. De lijst van mogelijke configuratienamen zijn voor beide parts gelijk. Dezelfde lijst hebben we in het programma ook nodig, vandaar dat we ze nu in de variabele configNames stoppen. Neem er notie van dat een array geïnitialiseerd kan worden met items tussen { } brackets. De gebruiker kan de configuratie kiezen uit een lijst in de User Interface. Dit is een ComboBox, de control heeft hier de naam ClutchTypeComboBox. De lijst met items is bereikbaar als de property Items. Aan Items voegen we onze namenlijst toe met de methode AddRange(). Het eerste item in de lijst wordt zichtbaar gemaakt (anders blijft het keuzeveld blank). Het laatste wat gedaan wordt is de initialisatie van het aantal paren disk in PairsTextBox. Zodra het programma wordt gestart, krijgt het veld de waarde 4. De gebruiker kan het natuurlijk altijd veranderen.
GENERATE BUTTON Het eerste deel van de Generate event methode bestaat uit controles van ingevoerde waarden. Als eerste de check of SolidWorks actief is. Die code zal je niet verrassen. Het aantal plaatparen vergt uitgebreidere code, maar niets wat je nog niet kent. Met TryParse wordt geprobeerd de text uit PairsTexBox control te converteren naar een integer type. Als dat niet lukt volgt een foutmelding; lukt het wel dan controleer je de waarde. Wanneer we langs alle controles komen heeft de variabele noDiskPairs een bruikbare waarde voor het aantal plaatparen. Het derde stukje is eenvoudig. De ComboBox heeft een property die het item oplevert dat de gebruiker in de lijst heeft geselecteerd. De variabele configName bevat nu de naam van de configuratie. Private Sub GenerateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateButton.Click Dim configName As String ' name of the configuration Dim noDiskPairs As Integer ' number of disk pairs in the assembly ' connect to SolidWorks swApp = New SldWorks.SldWorks() If (swApp Is Nothing) Then MsgBox("Cannot connect to SolidWorks", MsgBoxStyle.Exclamation) Exit Sub End If ' find the number of disk-pairs If (Integer.TryParse(PairsTextBox.Text, noDiskPairs) = False) Then MsgBox("Invalid number of pairs", MsgBoxStyle.Exclamation) Exit Sub Else If (noDiskPairs < 1) Or (noDiskPairs > 12) Then MsgBox(PairsTextBox.Text & " outside valid range [1..12]", _ MsgBoxStyle.Exclamation) noDiskPairs = 0 Exit Sub End If End If ' get the name of the configuration configName = CluchTypeComboBox.SelectedItem()
De GenerateButton_Click methode bestaat al. Voeg de code daarin toe.
82
Creating Assemblies
Het tweede deel van de Generate event methode bevat de methode aanroepen die het werk uitvoeren. Het zijn drie brokjes en het begint met een methode om een nieuwe assembly aan te maken. Daarna worden de onderdelen geladen waarmee de assembly wordt opgebouwd. Die parts zijn nu open in SolidWorks, maar ze maken nog geen onderdeel uit van de assmbly. Dat gebeurt in de laatse regel. De methoden newAssmbly, openPart en buildAssembly ga je zelf bouwen. In de volgende subhoofdstukken wordt dit toegelicht. ' create a new assembly Dim swAssembly As SldWorks.AssemblyDoc swAssembly = newAssembly() If (swAssembly Is Nothing) Then MsgBox("Failed to create new assembly", MsgBoxStyle.Exclamation) Exit Sub End If ' load the three parts Dim baseDisk, metalDisk, fibreDisk As SldWorks.PartDoc baseDisk = openPart("BaseDisk.sldprt") metalDisk = openPart("MetalDisk.sldprt") fibreDisk = openPart("FibreDisk.sldprt") If (baseDisk Is Nothing) Or (metalDisk Is Nothing) Or (fibreDisk Is Nothing) Then MsgBox("Failed to open part BaseDisk, MetalDisk or FibreDisk", _ MsgBoxStyle.Exclamation) Exit Sub End If ' put it together buildAssembly(configName, noDiskPairs, swAssembly, baseDisk, metalDisk, fibreDisk) End Sub
TOP DOWN DEVELOPMENT Je kunt zien dat de complexiteit niet groot is. Alles wat je tot nu toe hebt gelezen is begrijpelijk. De kunst van het succesvol programmeren is het opdelen in deelproblemen. Die deelproblemen laat je door een methode oplossen. Wil je een nieuwe assembly? Dan doe je alsof die methode bestaat en gebruikt hem, inclusief zijn parameters en het teruggegeven resultaat. Daarvoor voeg je een lege methode aan je code toe ‐de method stub‐ met de juist naam, parameterlijst en resultaat type. Private Function newAssembly() As SldWorks.AssemblyDoc Dim swAssy As SldWorks.AssemblyDoc Return swAssy End Function Private Function openPart(ByVal partName As String) As SldWorks.PartDoc Dim swPart As SldWorks.PartDoc Return swPart End Function Private Sub buildAssembly(ByVal ByVal ByVal ByVal ByVal ByVal End Sub
configName As String, noDiskPairs As Integer, swAssembly As SldWorks.AssemblyDoc, baseDisk As SldWorks.PartDoc, metalDisk As SldWorks.PartDoc, fibreDisk As SldWorks.PartDoc)
Voeg de method stubs aan je code toe, zodat je het programma tijdens het ontwikkelproces kunt testen.
83
CADCAM Deel IV, Design Automation
DRIE HULPMETHODEN newAssembly De methode die een nieuwe assembly als resultaat terug geeft voert zijn taak uit in twee stappen. Het eerste stuk code bepaalt de naam van de template. In SolidWorks kan de gebruiker voor part, assembly en drawing een document instellen dat als template dient. Met de methode GetUserPreferenceStringValue kun je allerlei standaard string values opvragen. De parameter van de methode is een constante van het type swUserPreferenceStringValue. Al met al is de code wel lees/begrijpbaar, maar niet makkelijk te verzinnen. Je moet het een keer gezien hebben vandaar dit voorbeeld. De laatste regels maken een nieuw document op basis van de opgegeven template. Wanneer het type een tekening is kan met de overige argumenten de afmeting van het tekenvel worden opgegeven.
De code levert een file path dat werkt op iedere computer met solidworks, in mijn geval komt er uit "C:\ProgramData\ SolidWorks\SolidWorks 2010\templates\Assem bly.asmdot"
Dim assyTemplate As String Dim swAssy As SldWorks.AssemblyDoc ' get template name ' bedenk het maar! dit kost wat clicks door de API help assyTemplate = swApp.GetUserPreferenceStringValue( _ SwConst.swUserPreferenceStringValue_e.swDefaultTemplateAssembly) If (assyTemplate = "") Then MsgBox("Please define a Default Assembly Template " _ & "before running this program", _ MsgBoxStyle.Exclamation) Return Nothing End If ' value = instance.INewDocument2(TemplateName, PaperSize, Width, Height) swAssy = swApp.INewDocument2(assyTemplate, 0, 0.0#, 0.0#) Return swAssy
Voeg de code toe in je methode. Controleer de template instellingen van je SolidWorks installatie. Ze zijn te vinden onder Tools, Options, Template Locations. Je kunt nu al even testen. Het is een goede gewoonte om dat regelmatig te doen. openPart In de methode openPart wordt, net als in de methode hiervoor, hoofdzakelijk een file‐path probleem opgelost. We willen het pad naar een folder swParts in de My Documents folder van de gebruiker. Hiervoor moeten we nu niet bij SolidWorks te rade maar bij Windows. Voor My Documents is een methode aanwezig. De subfolder plak je er aan vast. Wanneer die niet bestaat krijgt de gebruiker een foutmelding. Dim errors, warnings As Integer Dim swPart As SldWorks.PartDoc ' get pathname to parts Dim path As String path = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments) _ & "\SWparts" If (Not System.IO.Directory.Exists(path)) Then MsgBox("Please put the part templates in " & vbCrLf & _ path & vbCrLf & "before running this program", _ MsgBoxStyle.Exclamation) Return Nothing End If
84
Creating Assemblies
swPart = swApp.OpenDoc6(path & "\" & partName, _ SwConst.swDocumentTypes_e.swDocPART, _ SwConst.swOpenDocOptions_e.swOpenDocOptions_LoadModel, _ "", _ errors, _ warnings) Return swPart
Het tweede stuk bevat één aanroep van de methode OpenDoc6(). In de API documentatie vindt je welke argumenten er moeten worden meegegeven. De belangrijkste is natuurlijk het pad naar de file die je wilt openen. buildAssembly De method buildAssembly heeft een lange parameterlijst. We krijgen het aantal plaatparen binnen plus de naam van de configuratie en verder de assembly, de baseDisk, metalDisk en fibreDisk. Dus alles is er, je hoeft het alleen nog samen te voegen. Dat gaat met de methode AddComponent van de assembly. De eerste parameter van AddComponent is de path‐name van de part. Die part moet overigens geladen zijn maar dat is hiervoor al gebeurd. De drie getallen aan het eind zijn de XYZ‐waarden van de positie van de part‐oorsprong in het coördinatensysteem van de assembly. Daar doen we niets mee, de onderdelen worden op hun plek gedirigeerd met de mates die mateDiskByID gaat aanbrengen. De code begint met het plaatsen van één baseDisk (de rode) en één metalDisk (blauw). Voordat de rest wordt toegevoegd ondergaat de baseDisk een rotatie van 180 graden om de Y‐as. Die methode wordt verderop toegelicht. Dim errorState As Integer Dim component1, component2 As SldWorks.Component2 swApp.ActivateDoc2(swAssembly.GetTitle(), False, errorState) ' add parts, first base + metal component1 = swAssembly.AddComponent5(baseDisk.GetPathName(), 0, "", False, "Default", 0.0#, 0.0#, 0.0#) component2 = swAssembly.AddComponent5(metalDisk.GetPathName(), 0, "", False, "Default", 0.0#, 0.0#, 0.0#) component2.ReferencedConfiguration = configName ' flip the base part in z-direction to prevent mate problems component1.Transform2 = flipZdirection() mateDisksByID(swAssembly, component1, component2)
Er kan een situatie ontstaan waarin er niets gebeurt. Je programma lijkt het te doen, maar in SolidWorks heb je geen resultaat. Foutmeldingen verschijnen er ook niet. Waarschijnlijk zijn er dan meerdere SolidWorks.exe processen actief en communiceert je programma met een andere dan die op het scherm staat. Stop dan SolidWorks en je programma (niet Visual Basic). Start de Task manager en controleer of er nog SldWorks.exe processen actief zijn. Beëindig deze. Start daarna een nieuwe SolidWorks en probeer je programma nog eens.
85
CADCAM Deel IV, Design Automation
De andere platen worden in paren toegevoegd. Als je het aantal weet, en dat is hier zo, is het gebruik van een for‐loop een logische keuze. mateDiskByID voegt twee mates toe tussen de parts die worden opgegeven. De platen hebben allemaal een referentie‐as in het rotatiecentrum en twee referentie‐vlakken op de beide contactvlakken. 1. 2.
De Axis1 van beide parts krijgen een COINCIDENT/ALIGNED mate. RefPlane2 van de 1e part krijgt een COINCIDENT/AGAINST mate met de RefPlan1 van de 2e part.
Er wordt wel wat gegoocheld met de variabelen component1 en component2. Er staat commentaar in de code, daarmee zou je het moeten kunnen volgen. ' add pairs, fibre + metal For index = 1 To noDiskPairs ' mate previous metal to new fibre component1 = component2 component2 = swAssembly.AddComponent5(fibreDisk.GetPathName(), 0, "", False, "Default", 0.0#, 0.0#, 0.0#) component2.ReferencedConfiguration = configName mateDisksByID(swAssembly, component1, component2) ' mate new fibre to new metal component1 = component2 component2 = swAssembly.AddComponent5(metalDisk.GetPathName(), 0, "", False, "Default", 0.0#, 0.0#, 0.0#) component2.ReferencedConfiguration = configName mateDisksByID(swAssembly, component1, component2) Next
Verder wordt in de code hierboven ook de juiste configuratie van de parts ingesteld. De configuratie bestuurt de plaatdikte. Door de mates hoeven we niet te rekenen voor een juiste positionering, ieder plaatdikte is ok. Tenslotte nog wat code voor een rebuild en visualisatie van de resulterende assembly. Je zou het niet zelf verzinnen, maar de manier om het te ontdekken is zelf een assembly in elkaar zetten (twee platen en een mate) en de daarvan opgenomen macro bestuderen / gebruiken. ' rebuild etc. swAssembly.ClearSelection2(True) swAssembly.EnableAssemblyRebuild = True swAssembly.ForceRebuild2(True)
86
Creating Assemblies
AANBRENGEN VAN MATES Mates aanbrengen via de API gaat niet veel anders als met menu commando’s in SolidWorks. Je selecteert de geometrie waar je de mate mee wilt definiëren en je kiest het juiste type mate. De methode AddMate3 is onderdeel van een software‐extensie op ModelDoc2. Je haalt eerste die extensie op en bewaart ‘m in de variabele swExt. De andere voorbereidende handeling is het uitsplitsen van de part name. In de mate is alleen de eenvoudige naam nodig zonder extensie; bijvoorbeeld Assem1 uit de volledige naam Assem1.SLDASM. De SelectByID2 krijgt een complete string aangeboden om de juiste feature aan te duiden; bijvoorbeeld “Axis1@MetalDisk‐1@Assem3”. In dit geval wordt reference geometry geselecteerd, maar je kunt er voor kiezen edges of surfaces te gebruiken. Bestudeer de API info over deze methode. Let op de je de laatste versie (IModelDocExtension) bekijkt. Note Let er op dat je in selectByID altijd namen gebruikt. Wanneer je een macro opneemt en in de geometrie selecteert, komen de selectiecoördinaten in de macro terecht. Als de afbeelding iets is verschoven zal je code niet meer werken (er wordt als het ware naast de figuur geklikt). Selecteer daarom bij het opnemen van een macro de onderdelen in de Feature Tree. Dat is hetzelfde als selectie op naam. Dim boolStatus As Boolean Dim errorState As Integer ' get reference to assembly's extended function set Dim swExt As SldWorks.ModelDocExtension swExt = swApp.ActiveDoc().Extension Dim assyName, compName1, compName2 As String assyName = getModelSimpleName(swAssembly) compName1 = component1.Name2 compName2 = component2.Name2 ' add coincident mate on axes of rotation boolStatus = swExt.SelectByID2("Axis1@" & compName1 & "@" & assyName, "AXIS", 0, 0, 0, False, 1, Nothing, SwConst.swSelectOption_e.swSelectOptionDefault) boolStatus = swExt.SelectByID2("Axis1@" & compName2 & "@" & assyName, "AXIS", 0.0#, 0.0#, 0.0#, True, 1, Nothing, SwConst.swSelectOption_e.swSelectOptionDefault) swAssembly.AddMate3(SwConst.swMateType_e.swMateCOINCIDENT, SwConst.swMateAlign_e.swMateAlignALIGNED, False, 0.0#, 0.0#, 0.0#, 1.0#, 1.0#, 0.0#, 0.0#, 0.0#, False, errorState)
Plaats bovenstaande code in mateDisksByID en test dan eerst deze versie.
Het juiste aantal parts wordt geplaatst De mates op Axis1 reference geometry moet worden aangebracht. Alle onderdelen staan in de oorsprong
Het laatste stukje code van buildAssembly dient de tweede mate te maken tussen twee referentievlakken van twee opvolgende platen. Voeg code toe die de vlakken selecteert met selectType PLANE en voeg een mate toe met de optie AlignAGAINST. Test nu opnieuw. ' add coincident mate of front- and back surface
87
CADCAM Deel IV, Design Automation
TRANSFORMATIE Een component in SolidWorks termen is een onderdeel van een assembly. Het onderdeel kan een part zijn, maar het kan ook zelf een assembly zijn. Op die manier kan een geneste assembly structuur worden gecreëerd. De component moet natuurlijk een plek in de ruimte van z’n assembly krijgen. Dat wordt gerealiseerd met een transformatiematrix. Hierin wordt de locatie en de oriëntatie vastgelegd. De transformatie is een 4 x 4 matrix en ze is als property van de component op te vragen en te wijzigen. Verder bestaan er een hoeveelheid hulpmethoden om de matrix op te bouwen. We kunnen bijvoorbeeld eerst transleren naar een rotatiepunt, dan roteren, dan weer terug transleren naar de oorsprong om rotatie om een willekeurig punt te realiseren. De methode hieronder is een hulpfunctie die zo’n matrix bouwt. Door de naamgeving van de variabelen zal het redelijk begrijpbaar zijn wat er gebeurt. Het rotatiecentrum is de oorsprong, de rotatie‐as is een vector die in Y‐richting wijst, en de hoek is Pi (inderdaad, gebruik SI‐eenheden meters en radialen). Function flipZdirection() As SldWorks.MathTransform Dim swXform As SldWorks.MathTransform Dim rotCenter As SldWorks.MathPoint Dim rotAxis As SldWorks.MathVector Dim angle As Double rotCenter = swApp.IGetMathUtility.CreatePoint({0.0#, 0.0#, 0.0#}) rotAxis = swApp.IGetMathUtility.CreateVector({0.0#, 1.0#, 0.0#}) angle = Math.PI swXform = swApp.IGetMathUtility.CreateTransformRotateAxis( _ rotCenter, rotAxis, angle) Return swXform End Function
Proberen Verander de hoek maar eens in Pi/4 om te zien wat er gebeurt, maar zet ze ook weer terug. De flipZ methode moet de BaseDisk de juiste orientatie in de assembly te geven. Andere operaties op de matrix vindt je in de API help over de MathUtility. Alle stukjes van de puzzel liggen nu op hun plaats. Met de applicatie die je hebt gebouwd kunnen nu verschillen assembly‐configuraties worden gegenereerd.
THE END Gefeliciteert! Je hebt het eind van de serie tutorials bereikt. Je hebt nu kennis van technieken om ontwerpprocessen te versnellen (automatiseren) en kunt toepassingen realiseren waarin SolidWorks bestuurd wordt door een Visual Basic programma. In dit proces heb je een flits‐cursus programmeren gevolgd, in een Object‐Oriented omgeving met een professionele ontwikkel tool. Dit is een ervaring die je zeker ook in andere situaties goed van pas komt. Je kent een flink aantal mogelijkheden van de API van SolidWorks en begrijpt dat de API’s van CAD‐ systemen niet hetzelfde zijn, maar dat ze wel op elkaar lijken. Je inzicht in de mogelijkheden om ontwerpactiviteiten efficiënt in te richten met deze techniek is dus universeel toepasbaar. Zelf bouwen zal er na je opleiding waarschijnlijk niet van komen, maar door in je bedrijf de mogelijke toepassingen te identificeren help je die omgeving een stap vooruit. Je hebt nu voldoende kennis om de afsluitende opdracht van dit practicum met succes af te ronden.
88