De presentatie wordt gedownload. Even geduld aub

De presentatie wordt gedownload. Even geduld aub

Hoofdstuk 9 - Grafische User Interface : Deel 1

Verwante presentaties


Presentatie over: "Hoofdstuk 9 - Grafische User Interface : Deel 1"— Transcript van de presentatie:

1 Hoofdstuk 9 - Grafische User Interface : Deel 1
Inleiding Windows Forms Event handling model Control properties en layout Labels, Textbox en button Groupbox en panels Checkbox en radiobuttons Picturebox Mouse event handling Keyboard event handling Validatie Creatie controls at run time Nice to know : Visual inheritance allows you to see the controls on the base form and to add new controls. In this walkthrough you will create a base form and compile it into a class library. You will import this class library into another project and create a new form that inherits from the base form. During this walkthrough, you will learn how to: Create a class library project containing a base form. Add a button with properties that derived classes of the base form can modify. Add a button that cannot be modified by inheritors of the base form. Create a project containing a form that inherits from BaseForm. Ultimately, the walkthrough will demonstrate the difference between private and protected controls on an inherited form Scenario Steps The first step is to create the base form. To create a class library project containing a base form From the File menu, choose New and then Project to open the New Project dialog box. Create a Windows Application named BaseFormLibrary. For details, see Creating a Windows Application Project. To create a class library instead of a standard Windows application, right-click the BaseFormLibrary project node in Solution Explorer and select Properties. In the properties for the project, change the output type from Windows Application to Class Library and click OK. From the File menu, choose Save All to save the project and files to the default location. The next two procedures add buttons to the base form. To demonstrate visual inheritance, you will give the buttons different access levels by setting their Modifiers properties. To add a button that inheritors of the base form can modify On the Windows Forms tab of the Toolbox, double-click Button to add a button to the form. Use the mouse to position and resize the button. In the Properties window, set the following properties of the button: Set the Text property to Say Hello. Set the (Name) property to btnProtected. Set the Modifiers property to Protected. This makes it possible for forms that inherit from Form1 to modify the properties of btnProtected. Double-click the Say Hello button to add an event handler for the Click event. Add the following line of code to the event handler: ' Visual Basic MessageBox.Show("Hello, World!") // C# MessageBox.Show("Hello, World!"); To add a button that cannot be modified by inheritors of the base form Switch to design view by clicking the Form1.vb [Design] tab above the Code Editor, or by pressing SHIFT+F7. Add a second button and set its properties as follows: Set the Text property to Say Goodbye. Set the (Name) property to btnPrivate. Set the Modifiers property to Private. This makes it impossible for forms that inherit from Form1 to modify the properties of btnPrivate. Double-click the Say Goodbye button to add an event handler for the Click event. Place the following line of code in the event procedure: ' Visual Basic MessageBox.Show ("Goodbye!") // C# MessageBox.Show ("Goodbye!"); From the Build menu, choose Build to build the class library. Once the library is built, you can create a new project that inherits from the form you just created. To create a project containing a form that inherits from the base form From the File menu, choose Add Project and then New Project to open the New Project dialog box. Create a Windows application named InheritanceTest. For details, see Creating a Windows Application Project. To add an inherited form Right-click the InheritanceTest project and select Add and then Inherited Form. In the Add New Item dialog box, verify that Inherited Form is selected, and click OK. In the Inheritance Picker dialog box, select Form1 from the BaseFormLibrary project as the form to inherit from and click OK. This creates a form in the InheritanceTest project that derives from the form in BaseFormLibrary. Open the inherited form in the Windows Forms Designer by double-clicking it, if it is not already open. In the Windows Forms Designer, the inherited buttons have a glyph ( ) in their upper corner, indicating they are inherited. Select the Say Hello button and observe the resize handles. Because this button is protected, the inheritors can move it, resize it, change its caption, and make other modifications. Select the private Say Goodbye button, and notice that it does not have resize handles. Additionally, in the Properties window, the properties of this button are grayed to indicate they cannot be modified. Finally, move the mouse pointer over the button, and a ToolTip will appear indicating how the control was inherited. Right-click the InheritanceTest project in Solution Explorer and select Set As Startup Project. Right-click the InheritanceTest project in Solution Explorer and select Properties. In the InheritanceTest Property Page dialog box, set the Startup Object to be the inherited form (most likely Form2). Press F5 to run the application, and observe the behavior of the inherited form. Visual Basic.NET

2 9.1 Inleiding System.Windows.Application klasse beheert de applicatie at run-time System.Windows.Forms namespace bevat de controls voor het maken van een form-based applicatie. De Windows Forms klasse hierarchy Control Scrollable Control Windows.System.Application : de klasse voor het beheren van je applicatie at runtime. (vglbaar met app in VB6). Je kan niet instantieren van deze klasse, daar er maar 1 instantie bestaat voor de duur van het runnen van je applicatie. Aplication object bevat methodes om applicatie te starten Application.Run (eventueel met optionele parameter die weergeeft welke form hij moet opstarten. Als je die opgeeft zal de applifcatie stoppen als je dit formulier sluit. Als applicatie toch dient te draaien dien je eerst een show te doen en dan een run ) en applicatie te stoppen Application.Exit (vb frmFirst.Show; Application.Run()). Het application klasse kan je ook gebruiken om informatie op te halen zoals application.startuppath = installatiepad van applicatie) Klasse object = de hoogste supperklasse waar alle .NET objecten van erven. MarshalByRefObject : bevat code die lifetime management van objecten aanpakt. Erft van Object. Component : bevat basisimplementatie van Icomponent interface, wat object sharing tussen applicaties mogelijk maakT. Erft van MarshalBYREFOBject De klasse control, erft van component en is de basis van alle controls in de namespace System.Windows.forms. Deze klasse handelt alle basisfuncties zoals sizing, visibility, tab order af. Het handelt ook vensterhandles (HWND) af, zoals de creatie en destructie van vensterhandles. In control zijn tevens het merendeel van de vensterberichten opgenomen (zoals WM_CREATE, WM_WINDOWPOSCHANGED,...). Deze klasse verschaft de basisfunctionaliteit voor gegevens invoer, aanwijsapparaten en het instellen van begrenzingen. Deze klasse behandelt user input through the keyboard and mouse, defines the bounds and size of the control, provides a windows handle, and provides message handling and security. It does not incorporate any painting (the actual rendering of the graphical interface of the control), nor does it incorporate any specific user interaction functionality. The author must provide all of these aspects through custom code. (The Windows Control Library template is not available in the Standard Edition of Visual Basic ); De klas scrollableControl is afgeleid van Control en erft dus alle functionaliteit daarvan. Hij voorziet bovendien in de functionliteit om horizontaal of verticaal te scrollen en ruimte voor schuifbalken De klasse containercontrol is afgeleid van scrollable control en biedt de mogelijkheid extra controls te herbergen, tezamen met de benodigde functies, zoals focus beheer en navigatie met de tab-toets. Formulier erft van container control. En stelt een venster in een applicatie voor. De properties laten toe tal van verschillende formulieren te tonen. Ozlas dialoggvensters, MDI,... Kent bovendien een titelbalk, onregelmatige vensters, systeemmenu’s en standaardcontrols. Ook Usercontrol is afgeleid van containercontrol. Deze klasse biedt de mogelijkheid om zelf controls te maken gebruik makend van Windows Form Designer die in een applicatie gebruikt kunnen worden. Hij kent door overerving alle standaardfunctionaliteit van positionering, tekenen en herbergen van controls en geheugenbeheer. Een forms is een klasse, 7 niveau’s verwijderd van de object klasse Container Control Form User Control Visual Basic.NET

3 9.2 Windows Forms Gebruik : Gebruikersinterface van het programma
bevat alle besturingselementen waar een gebruiker mee werkt (container van besturingselementen en componenten) Kan een dialog, window of MDI Window zijn Erft van de klasse System.Windows.Forms.Form. Laat visual inheritance toe Code behind Windows Forms Bevat constructor – Sub New() Bevat initializer – Sub InitializeComponent() Bevat destructor – Sub Dispose() Tot voor kort steunde softwareontwikkeling zwaar op de Win32 API. Dit is nu verleden tijd. We beschikken nu over de kracht van overerving. We beschikken nu over een System.Windows.forms - framework dat gelijk is voor elke programmeertaal. Een formulier is nu gewoon een klasse. Een formulier kent eigenschappen, methodes en events net als alle andere klassen. Een form is een instantie van een klasse. Deze structuur laat visual inheritance toe, zo kan je forms creeeren die erven van andere forms. Als je een Windows applicatie start, gebeurt het erven automatisch. Als je ergens een form creeert moet je zelf de referentie leggen en de inheritance toevoegen. Het algemene ontwerppoces van een windows applicatie bestaat erin om formulieren te maken, zijn properties in te stellen, controls toe te voegen en de properties in te stellen en de event handlers te implementeren. Als we een formulier ontwerpen (kan visueel) wordt tal van code gegenereerd : Sub New is constructor (vervangt form_initialize event inVB6) Initializer : het instellen van properties at design time dient eigenlijk om initiele waarden te voorzien at runtime. In .NET creeert de Windows Form Designer deze subroutine die de instellingen van de properties at designtime bevat. Deze sub wordt opgeroepen vanuit de constructor Destructor : (in VB6 form_unload) en Form_Closed event. Igv non modal form, wordt de dispose methode aangeroepen om een form te sluiten. Igv modal form moet je dit zelf aanroepen. Treating forms as objects Forms are graphical objects that make up your applications user interface. Within Visual Basic, classes define how forms are displayed and what they can do. When a form is displayed at runtime, Visual Basic .NET creates an instance of the Form class that you can use like any other object. You can add custom methods and properties to forms and access them from other forms or classes in your application. To create a new method for a form Add a procedure declared as Public, as in the following code: ' Create a custom method on a form. Public Sub PrintMyJob() '. '.Add code for your method here. '. End Sub To add a new field to a form Declare a public variable in the form module, as in the following code: Public IDNumber As Integer To access methods on a different form Create a new instance of the form whose methods you want to access. When you reference a form name, you are actually referencing the class the form belongs to, not the object itself. Note   Visual Basic 6 provided, for each form class, an implicit global variable with the same name as the form class. Visual Basic .NET does not provide an implicit variable declaration. Assign the form to an object variable. The object variable references a new instance of the form class. The following example correctly calls the PrintMyJob procedure: Dim newForm1 As New Form1 newForm1.PrintMyJob In the previous example, the new form is not displayed. It is not necessary to show a form object to use its methods. To display the new form, you need to add the following code: newForm1.show Visual Basic.NET

4 9.2 Windows Forms Ontwerpraster kan je definiëren via Tools > Options > Windows Form Designer Of per form ShowGrid, SnapToGrid, GridSize systeemmenu Knoppen Minimize, Maximize, Close Ontwerpraster Op het form staat een grid. Die kan je wijzigen via Tools > Options en selecteer dan Windows Form Designer. Elke form kan zijn eigen grid definieren via de properties ShowGrid : al dan niet tonen van Grid SnapToGrid : bepaalt of child control zich aligneert met de grid GridSize : afstand in pixels tussen de verschillende dots in de grid. De defaultwaarden voor deze settings kan je instellen via Tools > Options Visual Basic.NET

5 9.2 Windows Forms Properties Text : tekst in de titelbalk.
AcceptButton : specifieert de knop op het formulier die actief wordt als de gebruiker de ENTER-toets drukt AutoScroll : automatisch tonen van scrollbars CancelButton : specifieert knop die geactiveerd wordt adhv ESC Controlbox, Maximizebox, MinimizeBox : weergave van maximaliseerknop, minimaliseerknop en systeemvak DockPadding : stelt de ruimte in tussen de binnenrand container en docked controls Font : lettertype (is de default voor de andere controls op form) FormBorderStyle : de randstijl van het formulier. Bepaalt weergave van formulier en of gebruiker form al dan niet kan resizen MinimumSize, MaximumSize : laat een programmeur toe een GUI layout te ontwerpen voor een bepaalde range. formBorderstyle : None : geen border, gebruiker kan form niet resizen FixedSingle : met 3D border, maar gebruiker kan form niet resizen .. Sizeable en SizeableToolWindow : user kan form resizen. In alle andere gevallen niet. AutoScroll : daar form erft van ScrollableControl klasse heeft het automatisch scrollbars ter beschikking MinimumSize, MaximumSize : in VB6 moest je in het Resize event ervoor zorgen dat de grootte van het formulier nooit onder een bepaalde waarde kwam. Je resette daar gewoon de hoogte of breedte terug naar de grens. In VB.NET behandelen die 2 properties dit voor jou Fonts : gedragen zich anders dan in VB6. Controls erven font.Backcolor en font.forecolor van hun parent controls. Als de font voor een control niet is ingesteld, dan erft de control van zijn parent. Dit laat toe dat je het font van de parent aanpast en alle controls worden automatisch aangepast. Visual Basic.NET

6 9.2 Windows Forms Icon : pictogram in titelbalk en bij minimalisatie formulier MinimumSize, MaximumSize : minimum en maximum grootte van form Localization : de positie van het formulier (top, left) tov container(bvb het scherm.) Size : de grootte van het formulier in pixels (hoogte en breedte) StartPosition : beginpositie formulier(centerScreen,…) Windowstate: wordt formulier gemaximaliseerd, geminimaliseerd of normaal weergegeven bij opstart. Minimumsize en maximumsize beide van datatype size. Vb dim maxsize as New Size() Maxsize.height = 500 Maxsize.width = 500 Me.maximumSize = maxsize Visual Basic.NET

7 9.2 Windows Forms Forms kent ook een Controls collectie
Voorbeeld : leegmaken van alle tekstvakken op form If Me.Controls(i).GetType Is GetType(System.Windows.Forms.Textbox) Then Me.controls(i).clear End If The Controls collection is used in building dynamic forms. A dynamic form contains a variable number of controls, which can be increased or decreased during the course of the application. It's not a very common situation, but it's fairly easy to create forms in your code. You can even write code to generate forms by populating the Controls collection. The dynamically generated controls wouldn't be nearly as useful if you didn't have a method to connect them to events. What good would it do to add a dozen buttons to a form if you couldn't write event handlers to respond to their events? To create an event handler at runtime, create a subroutine that accepts two arguments—the usual sender and e arguments—and enter the code you want to execute when a specific control receives a specific event. Let's say you want to add one or more buttons at runtime on your form and these buttons should react to the Click event. Create the ButtonClick() subroutine and enter the appropriate code in it. Once the subroutine is in place, you must connect it to an event of a specific control. The ButtonClick() subroutine, for example, must be connected to the Click event of a Button control. The statement that connects a control's event to a specific event handler is the AddHandler statement, whose syntax is as follows: AddHandler(control.event, New System.EventHandler(AddressOf subName))For example, to connect the ProcessNow() subroutine to the Click event of a button called "Calculate," use the following statement: AddHandler(Calculate.Click, _ New System.EventHandler(AddressOf ProcessNow)) The ProcessNow() subroutine is a delegate for the control's Click event handler. In your delegate, you can use the sender argument to find out which control fired the event. The expression sender.Text, for example, returns the value of the Text property of the control that fired the event. Or, you can cast the sender argument to the proper control type. If the ProcessNow() delegate handles the Click event of the controls Button1 and Button2, the sender.Text property's value will be the name of the button that was clicked. Visual Basic.NET

8 9.2 Windows Forms Methods Activate : Activeert het formulier en geeft de focus Close : sluit het formulier. (wordt ook aangeroepen als gebruiker x-knop klikt). Alle resources worden vrijgegeven (roept Dispose methode aan) Een gesloten formulier kan je niet opnieuw openen. Hide : verwijdert formulier van scherm, maar niet uit het geheugen. Gebruik dit als je het formulier van het scherm wilt, maar de gegevens nog nodig hebt. New : constructor. VB.NET genereert automatisch de code bij ontwerpen van formulier. Roept de methode InitializeComponent aan. Creëert de besturingselementen en initialiseert hun properties Show : toont een modeless formulier ShowDialog : toont een modal dialog box Finalize : destructor. Aangeroepen door garbage collector Het actieve venster is het frontmost venster en heeft een highlighted titlebar. Een venster wordt het actieve venster als de gebruiker ergens binnen het venster klikt. Tijdens de interactie met vensters, heeft het actieve venster de focus. Events getriggered by mYForm=New Form geen myForm.Show Handlecreated Load VisibleChanged MyForm.Activate Activated Myform.Hide Deactivate Myform.Close Deactivate Sluit form en roept dispose methode aan om alle windows resources vrij te geven Wordt ook aangeroepen als gebruiker x-knop klikt Closing Tijdens closing event kan je CancelEventArgs.Cancel property op true zette waardoor close niet gebeurt Closed HandleDestroyed Disposed MyForm.Dispose Gebruik de Close methode om je form te beeindigen Myform=nothing Releases de verwijzing. De GC roept dan de finalize methode aan (Unload event in VB6; is vervangen door Closing en close event) Visual Basic.NET

9 9.2 Windows Forms Events Startup Form
Activated : treedt op wanneer het formulier wordt geactiveerd Closed : treedt op wanneer het formulier wordt gesloten. Deactivated : treedt op wanneer het formulier de focus verliest Load : treedt op voordat het formulier voor de eerste keer wordt geopend. Startup Form Bepaalt welke form eerst geladen wordt bij runnen applicatie Project > Properties > Startup Object Load : delegate eventhandler Eventhanlders van form : ga naar code venster. Als je form1 selecteert dan zie je niet overgeerfde of overridable events van een form. Andere events zie je door te klikken op overrides of baseclass Visual Basic.NET

10 9.3 Event-Handling Model GUI’s zijn Event driven : de loop van het programma wordt bepaald door gebeurtenissen. Event informatie wordt doorgegeven aan Event Handlers Events zijn gebaseerd op delegates Objecten die verwijzen naar methodes Handelen als tussenpersoon tussen objecten die events creëren (event senders) en methodes die events afhandelen (event receivers) Event multicasting Bevat meerdere handlers voor 1 event GUI’s zijn eventdriven : ze genereren events als de gebruiker interageert met de GUI meer bepaald met de controls op een venster (vb via de muis of keyboerd) worden events gegenereerd. Bvb bewegen van muis, klikken van muis, typen in textbox, sluiten van venster. Events zijn boodschappen verstuurd door het programma om aan een object of verzameling van objecten te signaleren dat er een actie is gebeurd. Vb Klikken van OK knop in messagebox genereert event. De messagebox zal event afhandelen. Nl de messagebox component wordt afgesloten wanneer event wordt afgehandeld. Event informatie wordt doorgegeven aan event handlers, dit zijn methodes die worden opgeroepen als resultaat van een gebeurtenis. Events zijn gebaseerd op delegates. Dit zijn objecten die verwijzingen naar methodes bevatten. Delegates laten toe dat klassen methodes kunnen specifieren die enkel een naam en implementatie zullen krijgen als de klasse geinstantieerd wordt. Dit is heel handig voor event handlers. Bvb de creator van de Form class moet de naam en de implementatie van de methode die het click event afhandelt niet opgeven. Gebruik makend van delegates kan de klasse specifieren wanneer zo’n event handler kan opgeroepen worden. Als je je eigen form creeert, kan je de naam van de eventhandlers opgeven en zijn implementatie. Zolang dat de event handler geregistreerd werd met de juiste delegate, wordt de methode korrect aangeroepen. 1maal een event gegenereerd zal het systeem elke methode (event handler) aanroepen referenced by teh delegate. Elke methode in de delegate moet dezelfde signatuur hebben (parameters), daar aan alle methodes dezelfde informatie wordt doorgegeven. Alle controls hebben reeds voorafgedefinieerde delegates die oereenkomen met de events die ze genereren. Windows Forms zijn event driven, is all about responding to events (zoals klikken). Programmeren voor Windows is gekend als event-driven programmeren. Delegates zijn het fundament van events in.NET. Een delegate is in zijn eenvoudigste vorm een functiepointer waarmee een functie indirect via een verwijzing naar die functie kan worden aangeroepen. Het begrip delegate(afgevaardigde, gevolmachtigde) komen we overal in het dagelijkse leven tegen. Wanneer we bvb aandelen of obligaties willen aanschaffen doen we dit gewoonlijk via een tussenpersoon. Een effectenmakelaar is dus een delegate, want via hem regelen we de koop en verkoop van onze aandelen. De makelaar regelt op zijn beurt de transactie via de beurs of een andere organisatie. Een investeerder weet vaak niet bij welke organisatie hij moet zijn; de effectenmakelaar regelt dit voor . De makelaar heeft hier de functie van delegate. In .net hebben delegates de functie om events te verwerken(zoals kopen en verkopen). This event model uses delegates to bind events to the methods used to handle them. The delegate allows other classes to register for event notification by specifying a handler method. When the event occurs, the delegate calls the bound method. Delegates can be bound to a single method or to multiple methods, referred to as multicasting. When creating a delegate for an event, you (or the Windows Forms Designer) typically create a multicast event. A rare exception might be an event that results in a specific procedure (such as displaying a dialog box) that would not logically repeat multiple times per event. A multicast delegate maintains an invocation list of the methods it is bound to. The multicast delegate supports a Combine method to add a method to the invocation list and a Remove method to remove it. When an event is recorded by the application, the control raises the event by invoking the delegate for that event. The delegate in turn calls the bound method. In the most common case (a multicast delegate) the delegate calls each bound method in the invocation list in turn, which provides a one-to-many notification. This strategy means that the control does not need to maintain a list of target objects for event notification — the delegate handles all registration and notification. Delegates also allow multiple events to be bound to the same method, allowing a many-to-one notification. For example, a button-click event and a menu-command–click event can both invoke the same delegate, which then calls a single method to handle these separate events the same way. The binding mechanism used with delegates is dynamic — a delegate can be bound at run time to any method whose signature matches that of the event handler. This feature allows you to set up or change the bound method depending on a condition and to dynamically attach an event handler to a control. Events zijn eigenlijk niets anders dan boodschappen die gestuurd worden van 1 object naar een ander. In .NET het object dat het event triggert wordt de event sender of event raiser genoemd. De objecten die het event ontvangen en verwerken worden event receivers of event listeners genoemd. In .Net worden events geimplementeerd dmv delegates. Een delegate object bevat een verwijzing naar event handlers die worden doorgegeven van de event sender naar de event receiver. Als je dubbelklikt op bvb een knop btnOK krijg je een nieuwe lijn code Friend WithEvents btnOK As System.Windows.Forms.Button Private Sub btnOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOK.Click Een nieuw object van de Object A raises event E Delegate for event E Handler 1 for event E Handler 3 for event E Handler 2 for event E calls Visual Basic.NET

11 9.3 Event-Handling Model Voorbeeld van event
WithEvents keyword : indien je events gegenereerd door dit object wenst af te handelen Friend WithEvents lblOutput As System.Windows.Forms.Label ' handler for click event on lblOutput Private Sub lblOutput_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles lblOutput.Click 74 MessageBox.Show("Label was pressed") End Sub ' lblOutput_Click Event receiver Handles + naam van de event sender(s) Start Windows Application project In design : Plaats een label op formulier. Pas naam aan in lblOutput en text “click me”. .net heeft code geschreven in de background. Code kan je bereiken via het tabblad Rechtermuisklik ergens in design mode > View code ... WithEvents keyword : zegt de compiler dat de methodes die events afhandelen voor dit object geidentificeerd worden door handles componentnaam.eventNaam. Dus als we de methode click kiezen in de drop down bovenaan, creeert .Net een een methode signatuur die overeenstemt met de click event handler delegate, en plaatst de handles ... Achteraan de methode signatuur. Dit vertelt aan de compiler dat deze methode click events afhandelt getriggered door labeloutput. Maar je kan meerdere methodes definieren die ook labeloutput click afhandelen. Daarom creeeren we een nieuwe methode met dezelfde signatuur als de click delegate en voegen we achteraan handles lbloutput.click toe. Dit heet event multicasting. De volgorde waarin de methodes worden opgeroepen is onbepaald. Elke eventhandler heeft een signatuur. Gespecifieerd door event delegate. Hier worden 2 objecten meegegeven nl een verwijzing naar het object dat de event gegenereerd heeft (sender) en een event argument object e. E is van het type eventArgs. EventArgs is een basisklasse van objecten die event informatie bevat. Wordt verder in dit hoofdtsuk besproken. Om een event handler te definieren dienen we dus eerst de signatuur van delegate te vinden bovenaan in dropdown. .NET creeert een methode met de juiste signatuur, met de naam controlnaam_eventnaam. In help : class members > events > als je daar een event aanklikt Krijg je event naam. Als je op link eventhandler klikt krijg je de delegate/ Event-handling code toont message box Sender : Verwijzing naar object dat event gegenereerd heeft Event arguments object Visual Basic.NET

12 9.3 Event-Handling Model Meerdere events koppelen aan 1 event handler
Private Sub btnSender1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSender1.Click, btnSender2.Click MessageBox.Show("Hello from Receiver 1") End Sub Een delegate wordt gebruikt om boodschappen te communiceren tussen de sender en de receiver. Event sender kan delegeren naar meerdere receivers The order in which events are raised in Windows applications is of particular interest to developers concerned with handling each of these events in turn. When a situation calls for meticulous handling of events, such as when you are redrawing parts of the form, an awareness of the precise order in which events are raised at run time is necessary. For an overview of events in Windows Forms, see Introduction to Events in Windows Forms. For details about the makeup of event handlers, see Introduction to Event Handlers in Windows Forms. Another aspect of Windows Forms architecture is covered in Anatomy of the Visual Basic Code Behind Windows Forms. Standard Click Event Firing Behavior All Windows Forms controls raise events in the same order when a mouse button is pressed and released (regardless of which mouse button), except where noted for individual controls. The following is the order of events raised for a single mouse-button click: MouseDown event. Click event. MouseUp event. The following is the order of events raised for a double mouse-button click: DoubleClick event. (This can vary, depending whether the control in question has its StandardDoubleClick ControlStyles bit set to true. For more information on how to set a ControlStyles bit, see the Control.SetStyle Method.) Individual Controls The following controls do not conform to the standard Click event behavior: Button control Left click: Click Right click: No Click events raised Left double-click: Click, Click Right double-click: No Click events raised CheckBox control RadioButton control TextBox control Left double-click: Click, DoubleClick ListBox control Note   The event behavior detailed below happens whether the user clicks on an item or not (that is, a mouse click or double-click anywhere within the ListBox control raises these events). CheckedListBox control Note   The event behavior detailed below happens whether the user clicks on an item or not (that is, a mouse click or double click anywhere within the ListBox control raises these events) ComboBox control Note   The event behavior detailed below happens whether the user clicks on the edit field, the button, or on an item within the list. RichTextBox control Left click: No Click events raised Left double-click: No Click events raised ListView control Note   The event behavior detailed below happens only when the user clicks on the items in the ListView control. No events are raised for clicks anywhere else on the control. In addition to those described below, there are the BeforeLabelEdit and AfterLabelEdit events, which may be of interest to developers wishing to use validation with the ListView control. Right click: Click Right double-click: Click, DoubleClick TreeView control Note   The event behavior detailed below happens only when the user clicks on the items themselves or to the right of the items in the TreeView control. No events are raised for clicks anywhere else on the control. In addition to those described below, there are the BeforeCheck, BeforeSelect, BeforeLabelEdit, AfterSelect, AfterCheck, and AfterLabelEdit events, which may be of interest to developers wishing to use validation with the TreeView control. For details on the data sent by the system when these events are raised, see EventArgs Class. For details on monitoring user input to the keyboard for modifier keys (such as the SHIFT, ALT, and CTRL keys), see Determining Which Modifier Key Was Pressed. Control Painting Behavior Toggle controls, such as the controls deriving from the ButtonBase class, have a distinctive painting behavior. It is as follows: The user presses the mouse button. The control paints in the pressed state. The MouseDown event is raised. The user releases the mouse button. The control paints in the raised state. The Click event is raised. The MouseUp event is raised. Note   If the user moves the pointer out of the toggle control while the mouse button is down (such as moving the mouse off the Button control while it is pressed), the toggle control will paint in the raised state. Visual Basic.NET

13 9.4 Controls Demo Visual Basic.NET

14 9.4 Control Properties en layout
Besturingselementen erven van de klasse Control in de Namespace System.Windows.Forms Properties BackColor : achtergrondskleur van een control BackgroundImage : achtergrondafbeelding van control Enabled : specifieert of een control gebruikt kan worden Focused : specifieert of control op dit moment de invoerfocus heeft (read-only) Font : lettertype van control ForeColor : voorgrondkleur van control. Bepaalt meestal kleur van Text property Het object Control is de bron van veel eigenschappen die de ontwikkelaar ter beschikking staan heeft via de afgeleide controls. Anchor : Als je een control anchored left-right of top-bottom : Knop blijft op dzelfde afstand van bvb left en right, wat betekent dat de knop geresize zal moeten worden. Als jE bvb top-left : dan blijft de afstand top-left behouden, grootte van knop ook. Als je enkel top doet : behoudt hij bij resizen van formulier de afstand tot de top, de grootte van de knop blijft behouden en er wordt proportioneel berekend wat afstand tot links en rechts is. Opm. Pas anchoring aan pas als je volledig formulier getekend hebt. Want als je bij design bvb formulier vergroot dan worden de anchoring regels al toegepast, en niets is vervelender dan bij vergroeten van formulier dat dan de grootte van alle controls wordt aangepast. Docking : plakken van een control aan 1 van de randen van formulier. specifieert tegen welke zijde van de container een control wordt gedokt. Wanneer de eigenschap is ingesteld, wordt het aanpassen van de afmetingen van de control automatisch afgehandeld. ‘Dockable’ controls vereisen programmacode die de vensterbeweging narekent in samenhang met de instelling van deze eigenschap. Een goed vb van een docked control is bvb een menubar(docked top) en een statusbar(docked bottom). Bij vergroten van form, wordt control gestretched. Als je meerdere controls docked aan dezelfde rand, moet VB.NET beslissen waar te splitsen. Voorrang wordt gegeven aan besturingselement in omgekeerde z-order. De control met grootste z-order, zal eerste control zijn tegen de rand. Als je de volgorde wenst te switchen selecteer dan bring to back. Als je een rand wenst tussen de docked controls en de rand stel je property DockPadding van formulier in. Je kan de padding instellen voor de 4 randen (links, rechts, onder, boven) Unanchored controls bewegen relatief tov huidige positie op form, anchored bewegen zodat hun positie tov de randen niet wijzigt. Je hebt ook nog een splitter control : form opsplitsen in delen. Controls worden dan gedocked of geanchored in 1 van die delen. (Je moet je splitters eigenlijk docken bvb 1 links en 1 rechts) Visual Basic.NET

15 9.4 Control Properties en layout
Location: specifieert de coordinaten van de linkerbovenhoek(afstand linkerkant object, afstand bovenkant object) van de control t.o.v. diens container MinimumSize, MaximumSize : minimale en maximale grootte van form Size : grootte : totale breedte/hoogte van control (size type) TabIndex : de plaats van de control in de tabvolgorde van alle controls binnen een container. Kan je instellen via View > Tab Order en dan in de juiste volgorde de controls aan te klikken TabStop : specifieert of de control de focus kan krijgen via de TAB-toets Text : de tekst bij een control TextAlign : alignering tekst op control (keuze uit 3 horiz. en 3 verticale posities) Visible : specifieert of control zichtbaar is Het object Control is de bron van veel eigenschappen die de ontwikkelaar ter beschikking staan heeft via de afgeleide controls. In VB.NET is het mogelijk dat 2 controls dezelfde tab order hebben. Dan gebruikt .NET de z-order. De control met de hoogste z-order zal eerst de focus krijgen. Visual Basic.NET

16 9.4 Control Properties en layout
Automatisch resizen en positioneren van controls Anchor : zorgt ervoor dat de control op een vaste afstand blijft van 1 of meerdere zijden van de container. Specifieert welke zijde van de control gebonden zijn aan de zijden van diens container Dock : specifieert tegen welke zijde van de container een control wordt gedokt. DockPadding (containers) : ruimte tussen rand en docked controls. Het object Control is de bron van veel eigenschappen die de ontwikkelaar ter beschikking staan heeft via de afgeleide controls. Anchor : Als je een control anchored left-right of top-bottom : Knop blijft op dzelfde afstand van bvb left en right, wat betekent dat de knop geresize zal moeten worden. Als jE bvb top-left : dan blijft de afstand top-left behouden, grootte van knop ook. Als je enkel top doet : behoudt hij bij resizen van formulier de afstand tot de top, de grootte van de knop blijft behouden en er wordt proportioneel berekend wat afstand tot links en rechts is. Opm. Pas anchoring aan pas als je volledig formulier getekend hebt. Want als je bij design bvb formulier vergroot dan worden de anchoring regels al toegepast, en niets is vervelender dan bij vergroeten van formulier dat dan de grootte van alle controls wordt aangepast. Docking : plakken van een control aan 1 van de randen van formulier. specifieert tegen welke zijde van de container een control wordt gedokt. Wanneer de eigenschap is ingesteld, wordt het aanpassen van de afmetingen van de control automatisch afgehandeld. ‘Dockable’ controls vereisen programmacode die de vensterbeweging narekent in samenhang met de instelling van deze eigenschap. Een goed vb van een docked control is bvb een menubar(docked top) en een statusbar(docked bottom). Bij vergroten van form, wordt control gestretched. Als je meerdere controls docked aan dezelfde rand, moet VB.NET beslissen waar te splitsen. Voorrang wordt gegeven aan besturingselement in omgekeerde z-order. De control met grootste z-order, zal eerste control zijn tegen de rand. Als je de volgorde wenst te switchen selecteer dan bring to back. Als je een rand wenst tussen de docked controls en de rand stel je property DockPadding van formulier in. Je kan de padding instellen voor de 4 randen (links, rechts, onder, boven) Unanchored controls bewegen relatief tov huidige positie op form, anchored bewegen zodat hun positie tov de randen niet wijzigt. Je hebt ook nog een splitter control : form opsplitsen in delen. Controls worden dan gedocked of geanchored in 1 van die delen. (Je moet je splitters eigenlijk docken bvb 1 links en 1 rechts) Visual Basic.NET

17 9.4 Control Properties en layout
Methodes Focus : geeft de focus aan control Hide : maakt control onzichtbaar (zet visible op false) Show : maakt control zichtbaar (zet visible op true) Events (lost)Focus events gebeuren in volgende volgorde Enter : als control de focus krijgt Leave : als je control verlaat Validating : als control valideert Validated : als validatie beëindigd is Opm : als CausesValidation property false dan bestaan Validating en Validated event niet Het object Control is de bron van veel eigenschappen die de ontwikkelaar ter beschikking staan heeft via de afgeleide controls. Andere methodes Scale : schaalt de control en diens children met de opgegeven factor (vb factor 2 verdubbelt de afmetingen van control en children) The Enter and Leave events are suppressed by the Form class. The equivalent events in the Form class are the Activated and Deactivate events. The Enter and Leave events are hierarchical and will cascade up and down the parent chain until the appropriate control is reached. For example, assume you have a Form with two GroupBox controls, and each GroupBox control has one TextBox control. When the caret is moved from one TextBox to the other, the Leave event is raised for the TextBox and GroupBox, and the Enter event is raised for the other GroupBox and TextBox. Note   The GotFocus and LostFocus events are low-level focus events that are tied to the WM_KILLFOCUS and WM_SETFOCUS Windows messages. Typically, the GotFocus and LostFocus events are only used when updating UICues. The Enter and Leave events should be used for all controls except the Form class, which uses the Activated and Deactivate events. For more information about the GotFocus and LostFocus events, see the WM_SETFOCUS and WM_KILLFOCUS topics in the Keyboard Input Reference section of the Platform SDK Documentation in the MSDN Library. CAUTION   Do not attempt to set focus from within the LostFocus event handler. Doing so can cause your application or the operating system to stop responding. For more information about the LostFocus event, see the WM_KILLFOCUS topic in the Keyboard Input Reference section, and the Message Deadlocks topic in the Messages and Message Queues section of the Platform SDK Documentation in the MSDN Library. Visual Basic.NET

18 9.5 Labels, Textboxes, Buttons
Gebruik : weergeven van read-only tekst. Aanpassen tekst enkel via code at runtime Erft van klasse Control Properties : Text : inhoud van label Borderstyle : bepaalt de randstijl van label. Fixed3D geeft een verzonken uiterlijk Autosize : bepaalt of de afmetingen van de label automatisch worden aangepast om alle inhoud weer te geven. Wordwrap bestaat niet meer. Autosize : When this property is set to true, the control's height and width are automatically adjusted to display the entire contents of the control. This property is typically set to true when you use a Label control to display various lengths of text, such as the status of an application process. You can also use this property when the application will display text in various languages, and the size of the text may increase or decrease based on the language settings in Windows. Visual Basic.NET

19 9.5 Labels, Textboxes, Buttons
Gebruik : tekstinvoer + weergave van tekst op het scherm Erft van klasse TextBoxBase Properties : Text : inhoud van textbox. AcceptsReturn : Specifieert of drukken van de enter-toets een nieuwe lijn aanmaakt in een multiregel tekstvak of dat de standaardknop van de container geactiveerd wordt. PassWordChar : specifieert het teken dat moet worden gebruikt voor het maskeren van het wachtwoord Scrollbars : Specifieert welke schuifbalken er moeten worden weergegeven in de control Events TextChanged : wanneer de tekst in control is aangepast RichTextBox : geformatteerde tekst Als je een textbox wenst te accessen via een accesskay dan moet je een & toevoegen aan de label die tekstvak voorafgaat in de taborder. Labels kunnen geen focus krijgen , en geven dus onmiddellijk de focus aan de volgende control in de tab order. Visual Basic.NET

20 9.5 Labels, Textboxes, Buttons
TextBoxBase klasse Gebruik : biedt de basisfunctionaliteit van controls waarin sprake is van tekstinvoer. Klasse hierarchie : erft van de klasse Control Properties : MaxLength : het maximimum aantal tekens dat control kan bevatten MultiLine : specifieert of de control meer dan 1 regel tekst accepteert ReadOnly : specifieert of de tekst in tekstcontrol te bewerken is. Indien True heeft textbox een grijze achtergrond SelectedText : specifieert de geselecteerde tekst SelectionLength : het aantal geselecteerde tekens in de control SelectionStart : het beginpunt van de geselecteerde tekens in control WordWrap : Specifieert of de control automatisch woorden naar het begin van de volgende regel verplaatst als ze niet meer op de regel passen. (Enkel als Multiline = True) Visual Basic.NET

21 9.5 Labels, Textboxes, Buttons
Voorbeeld : creatie multiline textbox Private Sub CreateMyMultilineTextBox() Dim textBox1 As New TextBox() textBox1.Multiline = True textBox1.ScrollBars = ScrollBars.Vertical textBox1.AcceptsReturn = True textBox1.AcceptsTab = True textBox1.WordWrap = True textBox1.Text = "Welcome!" End Sub Voorbeeld : selecteren van de tekst in tekstvak Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter TextBox1.SelectionStart = 0 TextBox1.SelectionLength = TextBox1.Text.Length ' Create an instance of a TextBox control. ' Set the Multiline property to true. ' Add vertical scroll bars to the TextBox control. ' Allow the RETURN key to be entered in the TextBox control. ' Allow the TAB key to be entered in the TextBox control. ' Set WordWrap to True to allow text to wrap to the next line ' Set the default text of the control. Selecteren van tekst in textvak kan ook via textbox1.selectall Visual Basic.NET

22 9.5 Labels, Textboxes, Buttons
Methodes AppendText : plakt de meegegeven tekst achter de bestaande tekst in de control Clear : wist alle tekst uit de control Copy : kopieert de geselecteerde tekst in de control naar het klembord Cut : kopieert de geselecteerde tekst in de control naar het klembord en wist de geselecteerde tekst Paste : vervangt de selectie in de control door de inhoud van het klembord Select : Selecteren van tekst ScrollToCaret : verplaatst de inhoud van de control zodanig dat de invoegpositie zichtbaar wordt SelectAll : selecteert alle tekst in de control If txtNumbers.Text.Length > 0 then if txtNumbers.Text Like”[!0-9]” then e.cancel txtNumbers.Select(0,txtNumbers.Text.Length) End if Visual Basic.NET

23 9.5 Labels, Textboxes, Buttons
Gebruik : uitvoeren van taken bij het klikken Erft van klasse ButtonBase Klasse ButtonBase Erft van klasse Control Properties : Text : tekst op knop. ALT-toets : & voor letter plaatsen. &Print -> Alt+P, op knop verschijnt Print & als tekst : && Events : Click : activeren van knop. Visual Basic.NET

24 9.6 Groupboxes en Panels Groupboxes
Gebruik : rangschikken van control binnen een kader. Vb groeperen van elkaar wederzijds uitsluitende radiobuttons. Als je een groupbox beweegt, bewegen de controls in de groupbox mee. Toont een caption, bevat geen scrollbars Erft van klasse Control Properties Controls : lijst van de controls die de control bevat Text : tekst verschijnt in linkerbovenhoek van het kader. Code Behind Me.GroupBox1.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label1, Me.Button1}) In de gegenereerde code van de form designer staat er een lijn AddRange ... : creatie van een Windows.forms.Control array. De methode Controls.add voegt 1 control toe aan de control array Voor het formulier gebeurt dit ook : voorbeeld Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.GroupBox1, Me.lblEarningResult, Me.btnCalculate, Me.txtHours, Me.txtWage, Me.lblHours, Me.lblWage, Me.lblEarning}) Visual Basic.NET

25 9.6 Groupboxes en Panels Panel
Gebruik : Idem groupbox, maar heeft geen caption, kan wel scrollbars hebben Erft van klasse ScrollableControl Properties AutoScroll : Al dan niet automatisch tonen van scrollbars als panel te klein. BorderStyle : Stelt de randstijl in van de control. Fixed3D heeft een verzonken indruk. Controls : lijst van de controls die de control bevat Als een panel geresized wordt en niet langer meer al zijn controls kan tonen dan verschijnen er scrollbars. Heel bruikbaar als container van controls of voor grouperen van controls zodat je ze samen kan bewegen of hidden zetten. Wordt veel gebruikt in combinatie met dçocking en splitter. Visual Basic.NET

26 Addendum : Splitter Gebruik : indelen van form in secties. Hierdoor kan je de afmetingen van gedockte controls aanpassen. Erft van klasse Control Voorbeeld Plaats Panel op form. Dock = Left Plaats Splitter op Form (dockt automatisch). Backcolor = black Plaats knop in panel. Anchor = Top, Left, Right Plaats nog een panel op form. Dock = Fill Voeg knop toe op rechter panel Visual Basic.NET

27 9.7 Checkboxes en radiobuttons
Gebruik : Aanduiden van ja/nee of aan/uit. Selectie van meerdere opties uit een groep. Erft van ButtonBase klasse Properties : Appearance : weergeven als knop of als selectievakje Checked : specifieert of vakje al dan niet geselecteerd is (false of true) Checkstate : de status van het vakje CheckState.Checked : geselecteerd CheckState.Unchecked : niet geselecteerd CheckState.Indeterminate : niet beschikbaar (vinkje op grijze achtergrond) Text : tekst naast checkbox Checkstate is een enumeratietype Visual Basic.NET

28 9.7 Checkboxes en radiobuttons
Events Click : aan/uitvinken checkbox CheckedChanged : treedt op wanneer de waarde van de eigenschap Checked verandert CheckStateChanged : treedt op wanneer de waarde van de eigenschap CheckState verandert Voorbeeld : tekst naast checkbox wijzigt bij een klik Private Sub CheckBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.Click If CheckBox1.Checked = True Then CheckBox1.Text = "Checked“ Else CheckBox1.Text = "Unchecked“ End If End Sub Font klasse bevat constructor new met 3 parameters Naam size Style : is member van fontstyle enumeratie; die fonts bevat zoals regular, bold, italic, underline,.... De Font objects style property is readonly. En wordt ingesteld bij creatie van Font. Styles worden gecombineerd via bitwise operators (manipulatie op bit niveau (reeks van 0 en 1). Fontstyle is een System.FlagAttribute. Dit betekent dat door combinatie van verschillende stijlelementen een uniek nummer gecreerd wordt. Combinatie kan via de OR of XOR operator. OR betekent als 1 van de bits = 1, dan resultaatbit = 1. XOR betekent als beide verschillend dan resultaat 1. Veronderstel BOLD wordt voorgesteld door 01, Italic door 10. Adhv OR : 01 OR 10 => 11 betekent Bold en Italic. Dit is bealngrijk voor creatie van stijlcombinaties zolang we geen style moeten undo XOR : 01 XOR 10 => 11(bold en italic) Maar als nu 11(bold en italic) XOR 01 (Bold) => 10 (Italic). lblOutput.Font.Bold = Not lblOutput.Font.Bold kan je niet gebruiken want bold is een readonly property. Visual Basic.NET

29 9.7 Checkboxes en radiobuttons
Gebruik : lijst van keuzemogelijkheden die elkaar wederzijds uitsluiten. Met de selectie van een keuzerondje in de groep worden automatisch alle andere gedeselecteerd. Worden gegroepeerd in een container : form, groupbox of panel Erft van klasse ButtonBase Properties : Checked : specifieert of de control geselecteerd is Text : tekst naast keuzerondje Methode PerformClick : simuleert een klik op de control Events Click : indien radiobutton wordt aangevinkt CheckedChanged : wanneer de waarde Checked wordt gewijzigd When a RadioButton control is clicked, its Checked property is set to true and the Click event handler is called. The CheckedChanged event is raised when the value of the Checked property changes.(dus ook wanneer hij wordt uitgezet <-> clcik : enkel als aangevinkt wordt). If the AutoCheck property is set to true (the default), when the radio button is selected all others in the group are automatically cleared. This property is usually only set to false when validation code is used to make sure the radio button selected is an allowable option. The text displayed within the control is set with the Text property, which can contain access key shortcuts. An access key allows a user to "click" the control by pressing the ALT key with the access key PerformClick : simuleert een klik op de control, alsof de gebruiker het gedaan heeft Visual Basic.NET

30 9.8 PictureBoxes Gebruik : weergeven van afbeeldingen (Bitmap, gif, jpeg, icon, metafile,…) Erft van klasse Control Properties Borderstyle : specifieert de randstijl Image : specifieert de afbeelding in de control (klasse Image) SizeMode : specifieert hoe de afbeelding wordt weergegeven. Autosize : Grootte picturebox past zich aan de de grootte beeldje Normal : plaatst beeld in linker bovenhoek. Beeld wordt afgekapt als te groot. StretchImage : Image past zich aan de grootte van picturebox CenterImage : plaatst beeld in het midden. Beeld wordt afgekapt als te groot. Event : Click : klikken van beeldje Visual Basic.NET

31 9.9 Mouse-Event handling Mouse Events
MouseDown : treedt op wanneer de muisknop wordt ingedrukt terwijl de muisaanwijzer boven de control is MouseEnter : treedt op wanneer de muisaanwijzer de control binnengaat MouseHover : treedt op wanneer de muisaanwijzer boven de control hangt MouseLeave: treedt op wanneer de muisaanwijzer de control verlaat MouseMove: treedt op wanneer de muisaanwijzer binnen de control beweegt MouseUp: treedt op wanneer de muisaanwijzer wordt losgelaten terwijl de muisaanwijzer boven de control is MouseWheel : treedt op wanneer aan het muiswiel wordt gedraaid als de control de focus heeft Visual Basic.NET

32 9.9 Mouse-Event handling MouseEventArgs Properties Button Clicks X Y
Ingedrukt muisknop (right, left,middle) Clicks Aantal mouse clicks X X-coordinaat van event, binnen de control Y Y-coordinaat van event, binnen de control Visual Basic.NET

33 9.10 Keyboard-Event Handling
Keyboard events Delegate KeyEventHandler, event argument : KeyEventArgs KeyDown : treedt op wanneer een toets wordt ingedrukt als de control de focus heeft. Retourneert of Alt, Shift, Control toets ingedrukt KeyUp : treedt op wanneer een toets wordt losgelaten als de control de focus heeft. Retourneert of Alt, Shift, Control toets ingedrukt Delegate KeyPressEventHandler, event argument : KeyPressEventArgs KeyPress : treedt op wanneer er op een toets wordt gedrukt terwijl de control de focus heeft. Kan de waarde retourneren van ingedrukt ASCII karakter Visual Basic.NET

34 9.10 Keyboard-Event Handling
KeyPressEventArgs Properties KeyChar : retourneert ASCII waarde toets Handled : duidt aan of KeyPress event is afgehandeld KeyEventArgs Properties Alt : duidt aan of ALT-toets ingedrukt Control : duidt aan of Control-toets ingedrukt Shift : duidt aan of Shift-toets ingedrukt Voorbeeld Private Sub button1_KeyPress(ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles button1.KeyPress If (Control.ModifierKeys And Keys.Shift) = Keys.Shift Then MessageBox.Show("Pressed " & Keys.Shift) End If End Sub Keys : enumeration type Visual Basic.NET

35 Validatie input gebruikers
Validatie op veld niveau Gebruik van properties Validatie op formulier niveau Gebruik van Error Provider Visual Basic.NET

36 Validatie input gebruikers
Validatie op veld niveau TextChanged event Trigger : gebruiker brengt wijziging aan inhoud van control Gebruik : actie ondernemen bij wijzigen van input Voorbeeld : Private Sub txtProductcode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtProductcode.TextChanged If txtProductcode.Text <> "" Then btnOK.Enabled = True Else btnOK.Enabled = False End If End Sub Validatie op veldniveau : validatie van data ingegeven in een individueel veld. Typisch (maar niet altijd) gebeurt veld validatie zonder te kijken naar de inhoud van andere velden op het formulier. Textchanged : bij tekstbox en listbox Visual Basic.NET

37 Validatie input gebruikers
Keypress event : Trigger : gebruiker typt ascii character in control. Na KeyDown en voor KeyUp Gebruik : beperken van de character input bij ingave converteren van character input bij ingave door aanpassen waarde parameter KeyAscii Werkt niet met speciale functies : DEL, functietoetsen, ... Voorbeeld : beperking invoer in tekstbox tot cijfers,niet-ASCII characters Private Sub txtProductcode_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtProductcode.KeyPress If e.KeyChar = ControlChars.Back Then 'Exit subroutine if backspace e.Handled = False ElseIf Chr(Convert.ToInt32(e.KeyChar)) < "0" OrElse Chr(Convert.ToInt32(e.KeyChar)) > "9" Then e.Handled = True 'Set character to null if out of range Microsoft.VisualBasic.Beep() End If End Sub Als de gebruiker "A" intikt, wodrt het keypress event gefired en heeft keyascii parameter de waarde 65. (is ascii waarde voor hoofdletter A) In de code kan je keyascii waarde aanpassen door er een nieuwe waarde aan toe te kennen. Het systeem zal dan deze nieuwe waarde zien als de warade die de gebruiker heeft ingegeven. Als je de waarde van keyAscii wijzigt in 0, dan zal het systeem geen keystroke zien en dus niets weergeven. Voor het testen : - gebruik chr functie om ascii waarde om te zetten in character waarde - manipuleer en evalueer de waarde - gebruik de Asc functie om die character waarde terug te vertalen naar de keyascci waarde? - Ken de niewe waarde toe aan de keyasscii parameter Bvb gebruiken om alle characters in hoofdletters om te zetten Private sub txtPassword_KeyPress(KeyAscii as integer) keyChar = chr(KeyAscii) keyChar = Ucase(keyChar) keyAscii = asc(keyChar) End Sub Public Class myKeyPressClass Private Shared keyPressCount As Long = 0 Private Shared backspacePressed As Long = 0 Private Shared returnPressed As Long = 0 Private Shared escPressed As Long = 0 Private textBox1 As TextBox Public Sub myKeyCounter(sender As Object, ex As KeyPressEventArgs) Select Case ex.KeyChar ' Counts the backspaces. Case ControlChars.Back backspacePressed = backspacePressed + 1 ' Counts the ENTER keys. Case ControlChars.Lf returnPressed = returnPressed + 1 ' Counts the ESC keys. Case Convert.ToChar(27) escPressed = escPressed + 1 ' Counts all other keys. Case Else keyPressCount = keyPressCount + 1 End Select textBox1.Text = backspacePressed & " backspaces pressed" & _ ControlChars.Lf & ControlChars.Cr & escPressed & _ " escapes pressed" & ControlChars.CrLf & returnPressed & _ " returns pressed" & ControlChars.CrLf & keyPressCount & _ " other keys pressed" & ControlChars.CrLf ex.Handled = True End Sub 'myKeyCounter End Class 'myKeyPressClass Visual Basic.NET

38 Validatie input gebruikers
Validating event : laat toe adhv code de inhoud van een tekstvak te controleren. Wordt getriggered wanneer je veld verlaat en CausesValidation Property = True e.Cancel=True zorgt ervoor dat element de focus blijft behouden Voorbeeld : Private Sub txtProductcode_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtProductcode.Validating If txtProductcode.Text = "" OrElse Not IsNumeric(txtProductcode.Text) _ OrElse txtProductcode.Text.Length <> 7 Then MessageBox.Show("productcode must be 7 positions and numeric") e.Cancel = True End If End Sub Validating event : getriggered wanneer control validatie start. Moet de code voor validatie inhoud control bevatten Validated event : getriggered wanneer validatie van control beëindigd is CausesValidation Property : Visual Basic.NET

39 Validatie input gebruikers
Gebruik van textbox properties om data input te beperken MaxLength : maximaal aantal characters die de gebruiker kan ingeven Locked : True : gebruiker kan niet langer input textbox wijzigen. Hij kan wel scrollen in textbox en textbox focus geven Visual Basic.NET

40 Validatie input gebruikers
Validatie op formulier niveau Private Sub btnOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOK.Click If txtProductcode.Text = "" OrElse Not IsNumeric(txtProductcode.Text) _ OrElse txtProductcode.Text.Length <> 7 Then MessageBox.Show("productcode must be 7 positions and numeric") txtProductcode.Focus() End If End Sub Visual Basic.NET

41 Validatie input gebruikers
Gebruik van Error Provider Toont ! Icoontje naast foutieve input Voorbeeld Private Sub txtProductcode_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtProductcode.Validating If txtProductcode.Text = "" OrElse Not IsNumeric(txtProductcode.Text) _ OrElse txtProductcode.Text.Length <> 7 Then ErrorProviderProduct.SetError(txtProductcode, "productcode must be 7 positions and numeric") e.Cancel = True Else ErrorProviderProduct.SetError(txtProductcode, "") End If End Sub Visual Basic.NET

42 Addendum : creatie van controls at runtime
Gebruik van control in form bestaat uit 4 stappen Declaratie reference type variabele Creatie object Instellen properties Toevoegen aan Controls collectie Voorbeeld Friend WithEvents ButtonDisplay As System.Windows.Forms.Button Private Sub AddNewControls() ButtonDisplay = New System.Windows.Forms.Button() With buttondisplay .text = "&display" .location = New System.Drawing.Point(100, 332) End With Me.Controls.Add(Me.ButtonDisplay) End Sub Wat gebeurt er reeds in de Form designer generated code 1. Declaratie van een reference type variabele Friend WithEvents txtProductcode As System.Windows.Forms.TextBox 2. Creatie van object Me.txtProductcode = New System.Windows.Forms.TextBox() 3. Instellen property values Me.txtProductcode.Location = New System.Drawing.Point(128, 32) Me.txtProductcode.Name = "txtProductcode" Me.txtProductcode.Size = New System.Drawing.Size(136, 20) Me.txtProductcode.TabIndex = 0 Me.txtProductcode.Text = "“ 4. Toevoegen aan de controls collectie Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnOK, Me.Label1, Me.txtProductcode}) Visual Basic.NET

43 Addendum : starten, stoppen applicatie
Starten van applicatie Instellen van startup object in de project properties Beëindigen van applicatie Application.Exit() Voorbeeld Private Sub frmMain_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing If MessageBox.Show("Are you sure?", "GUI", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then Else e.Cancel = True End If End Sub Visual Basic.NET

44 Addendum : overzicht Windows Form controls
Visual Basic.NET

45 Addendum : overzicht Windows Form controls
Visual Basic.NET

46 Alle icoontjes Visual Basic.NET

47 9.7 Checkboxes en radiobuttons
Demo radiobuttons Private Sub radQuestion_CheckedChanged(ByVal sender _ As System.Object, ByVal e As System.EventArgs) _ Handles radQuestion.CheckedChanged iconType = MessageBoxIcon.Question End Sub ' radQuestion_CheckedChanged Sub radYesNoCancel_CheckedChanged(ByVal sender _ Handles radYesNoCancel.CheckedChanged buttonType = MessageBoxButtons.YesNoCancel End Sub ' radYesNoCancel_CheckedChanged Visual Basic.NET

48 2 ' Using CheckBoxes to toggle italic and bold styles. 3
1 CheckBoxTest.vb 2 ' Using CheckBoxes to toggle italic and bold styles. 3 4 Public Class FrmCheckBox Inherits System.Windows.Forms.Form 6 ' Visual Studio .NET IDE generated code 8 ' use Xor to toggle italic, keep other styles same Private Sub chkItalic_CheckedChanged _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles chkItalic.CheckedChanged 13 lblOutput.Font = New Font(lblOutput.Font.Name, _ lblOutput.Font.Size, lblOutput.Font.Style _ Xor FontStyle.Italic) End Sub ' chkItalic_CheckedChanged 18 ' use Xor to toggle bold, keep other styles same Private Sub chkBold_CheckedChanged _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles chkBold.CheckedChanged 23 lblOutput.Font = New Font(lblOutput.Font.Name, _ lblOutput.Font.Size, lblOutput.Font.Style _ Xor FontStyle.Bold) End Sub ' chkBold_CheckedChanged 28 29 End Class ' FrmCheckBox Fig 14.24 Aanpassen van font obv font property. De fontconstructor heeft 3 parameters Font Naam Font size Font style : maakt deel uit van de FontStyle Enumeration : Regular, Bold, Italic,... De style property is readonly en wordt ingesteld bij de creatie van een font object. Styles kunnen bitwise gecombineerd worden – operators die manipulatie van bits doen. Alles in de computer wordt voorgesteld door nul en ééntjes. De FCL documentatie zegt dat FontStyle een System.FlagAttribute is, wat betekent dat de fontstyle bitvalues geselecteerd zodat we meerdere fontstyles kunnen combineren. Zie boek Deitel voor vervolg Visual Basic.NET

49 Validatie input gebruikers
Microsoft Masked Edit Control Toevoegen aan toolbox : Project > Components > Microsoft Masked Edit Control Gebruik : Beperken/formatteren van user input Properties Mask : definiëren van formaat van input. Beperkt ook aantal characters frmMain.mskAccountNbr.Mask = "###-########-##" Text property : bevat de data die gebruiker heeft ingegeven, inclusief mask Als gebruiker rekeningnummer ingeeft, wordt geretourneerd ClipText property : bevat de data die gebruiker heeft ingegeven, exclusief mask To clear the Text property when you have a mask defined, you first need to set the Mask property to an empty string, and then the Text property to an empty string: MaskedEdit1.Mask = "" MaskedEdit1.Text = "" When you define an input mask, the Masked Edit control behaves differently from the standard text box. The insertion point automatically skips over literals as you enter data or move the insertion point. When you insert or delete a character, all nonliteral characters to the right of the insertion point are shifted, as necessary. If shifting these characters leads to a validation error, the insertion or deletion is prevented, and a ValidationError event is triggered. Suppose the Mask property is defined as "?###", and the current value of the Text property is "A12." If you attempt to insert the letter "B" to the left of the letter "A," the "A" would shift to the right. Since the second value of the input mask requires a number, the letter "A" would cause the control to generate a ValidationError event. The Masked Edit control also validates the values of the Text property at run time. If you set the Text property so that it conflicts with the input mask, the control generates a run-time error. You may select text in the same way as for a standard text box control. When selected text is deleted, the control attempts to shift the remaining characters to the right of the selection. However, any remaining character that might cause a validation error during this shift is deleted, and no ValidationError event is generated. Visual Basic.NET

50 Validatie input gebruikers
ValidationError Trigger : inputbox ontvangt een ongeldige input van gebruiker, of gebruiker typt niet alle vereiste characters in 2 parameters Invalidtext : ongeldige string StartPosition : positie ongeldige string Voorbeeld Sub mskAccountNbr_ValidationError (InvalidText As String, _ StartPosition As Integer) If StartPosition = mskAccountNbr.MaxLength Then Msgbox "Limit 13 digits" Else Msgbox "Digits Only" End If End Sub InvalidText is the value of the Text property, including the invalid character. This means that any placeholders and literal characters used in the input mask are included in InvalidText. StartPosition is the position in InvalidText where the error occurred (the first invalid character). Visual Basic.NET

51 Validatie input gebruikers
Keyup/down event : Trigger : activiteit op toetsenbord Gebruik : Actie ondernemen bij selectie van functietoetsen Actie ondernemen bij selectie van shift, alt, ctrl toets Voorbeeld : Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) If KeyCode = vbKeyF1 Then MsgBox "You pressed F1!" End If End Sub Note   If the KeyPreview property is set to True, a form receives these events before controls on the form receive the events. Use the KeyPreview property to create global keyboard-handling routines. Keycode : A key code, such as vbKeyF1 (the F1 key) or vbKeyHome (the HOME key). To specify key codes, use the constants in the Visual Basic (VB) object library in the Object Browser. Shift : An integer that corresponds to the state of the SHIFT, CTRL, and ALT keys at the time of the event. The shift argument is a bit field with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2 ). These bits correspond to the values 1, 2, and 4, respectively. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys are pressed. For example, if both CTRL and ALT are pressed, the value of shift is 6. KeyDown and KeyUp interpret the uppercase and lowercase of each character by means of two arguments: keycode, which indicates the physical key (thus returning A and a as the same key) and shift, which indicates the state of shift+key and therefore returns either A or a.Je krijgt vbKeyA terug en dan moet je maar testen o If you need to test for the shift argument, you can use the shift constants which define the bits within the argument. The constants have the following values: ConstantValue SHIFT 1 vbshiftMask,CTRL 2 vbAltMask,ALT This example demonstrates a generic keyboard handler that responds to the F2 key and to all the associated ALT, SHIFT, and CTRL key combinations. The key constants are listed in the Visual Basic (VB) object library in the Object Browser. To try this example, paste the code into the Declarations section of a form that contains a TextBox control, and then press F5 and press F2 with various combinations of the ALT, SHIFT, and CTRL keys. Private Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer) Dim ShiftDown, AltDown, CtrlDown, Txt ShiftDown = (Shift And vbShiftMask) > 0 AltDown = (Shift And vbAltMask) > 0 CtrlDown = (Shift And vbCtrlMask) > 0 If KeyCode = vbKeyF2 Then ' Display key combinations. If ShiftDown And CtrlDown And AltDown Then Txt = "SHIFT+CTRL+ALT+F2." ElseIf ShiftDown And AltDown Then Txt = "SHIFT+ALT+F2." ElseIf ShiftDown And CtrlDown Then Txt = "SHIFT+CTRL+F2." ElseIf CtrlDown And AltDown Then Txt = "CTRL+ALT+F2." ElseIf ShiftDown Then Txt = "SHIFT+F2." ElseIf CtrlDown Then Txt = "CTRL+F2." ElseIf AltDown Then Txt = "ALT+F2." ElseIf SHIFT = 0 Then Txt = "F2." End If Text1.Text = "You pressed " & Txt End If End Sub Visual Basic.NET

52 Addendum : doorlopen van controls
Sub ShowType(ByVal Ctrl As Object) 'Use the TypeName function to display the class name as text. MsgBox(TypeName(Ctrl)) 'Use the TypeOf function to determine the object's type. If TypeOf Ctrl Is Button Then MsgBox("The control is a button.") ElseIf TypeOf Ctrl Is CheckBox Then MsgBox("The control is a check box.") Else MsgBox("The object is some other type of control.") End If End Sub Visual Basic.NET

53 Select case(ctype(sender, button).name
Case “buttonFirrst” ...end select Visual Basic.NET

54 Addendum : casting and typecontrol
Dim el as Control For Each el In Me.Controls If TypeOf (el) Is Label Then el.BackColor = System.Drawing.Color.LightGray End If Next Ipv TypeOf mag je ook gebruiken : if el Is Label Casting : Dim newLabel as Label newLabel=ctype(el,Label) Visual Basic.NET


Download ppt "Hoofdstuk 9 - Grafische User Interface : Deel 1"

Verwante presentaties


Ads door Google