400 likes | 413 Views
Learn to create interactive desktop applications using Windows Forms in C# with this comprehensive guide. Understand event-driven programming, handling events, working with delegates, and designing user interfaces. Explore registering event handlers, setting control properties, and utilizing Visual Studio efficiently. Enhance your skills in building Windows Forms applications step by step.
E N D
Windows Desktop Applications Windows Forms Windows Forms
Windows Desktop Applications • Windows Desktop Applications are implemented in C# using WindowsForms • There are .NET classes that represent windows, buttons, textboxes, menus, listboxes, and so forth • With experience, they are very easy to use: • Drag and Drop from the “toolbox” • Setproperties • Handleevents Windows Forms
Event Driven Programming • Console applications are essentially sequential code executed in the order specified by Main and whatever it calls • Windows programs are event-driven • Main instantiates a main window • Subsequently, the order of code execution is primarily determined by events, many of which are triggered from outside the code • User clicks a mouse • User presses a key, producing keystroke • User scrolls • Timer expires • I/O operation concludes • And so forth Windows Forms
Events • During the execution of a Windows program, thousands of events typically occur • Every time the mouse is moved by one pixel over the window, a MouseMove event occurs, for example • Each time an event related to the program occurs, the programisnotified by the system. It may • Take some action • Ignoretheevent and let Windowsdeal with it • Windowsignoresmostevents but not all • It typically doesn’t ignore a CTRL-ALT-DELETEevent, for example Windows Forms
Dealing with Events • Programs typically ignore most events • The events to which a program responds and the action it takes give the program its behavior • The program may provide oneor more methods that execute actions to “do something” in response to the event • Such a method is called an eventhandler • An event handler is a method with a signature similar to this private void HandlerName (Object sender, EventArgs e) Windows Forms
Delegates • While it is not necessary to understand delegates to understand event-drivenprogramming, the term delegate occurs frequently in the literature • The delegate is a type that defines a signature, that is, the return value type and parameter list types for a method • You can use the delegate type to declare a variable that can refer to anymethod with the samesignature as the delegate • As indicated on the previous slide an EventHandler delegate has the signature: public delegate void EventHandler(Object sender, EventArgs e); • Any method with the same signature can serve as anEventHandler Windows Forms
Event Handlers • Registering an event-handler in C# is analogous to Adding a Listener in Java • Event handlers are “registered” for events to be handled this.Load += new System.EventHandler (Form_Load); • Visual Studio generates the code to register most event handlers so that the programmer need not do so in most cases Delegate Event Handler method name which must have same signature as the EventHandlerdelegate Load is the event name Windows Forms
Windows Form Application Create a Windows Forms Application … … with an appropriate name Windows Forms
Results The Window Driver Program Rename the Form class Visual Editor for the Form – Form can be resized, etc. Rename Driver Windows Forms
Main Program No changes or additions to Main program are required for simple Windows Form applications Windows Forms
Design and Code Views Code View Windows derived from Form class like Java GUI window derived from JFrame Easily switch between the views Design View Windows Forms
Design View and Toolbox • Controls in the Toolbox are represented by .NETclasses • Dragginganddropping a control onto the formcreates an objectoftheclass in the code • The control may be placed at a desired location on the form and sized to suit your needs Standard controls can be placed on a form Windows Forms
Each Form has Two Code Files Windows Forms
Each Form Has 3 Files These represent the C# code, the designer code file, and the visual components of the form In you plan to copy a form and paste it into another project, be sure to copy all 3 of the files Windows Forms
Designer.cs • The designer code file contains VS-generated code that defines the controls dropped on the form and their properties, including their event handler registrations Note the generated code for registering this event handler Windows Forms
Properties of Controls • Each control has an extensive list of properties that allows the designer/programmer to manage many of the features of the control such as • Colors • Fonts • Size • Style • Objectname • Caption (Text) • Many more Windows Forms
Setting Properties of Controls • Properties can be set or retrieved • At design time in the DesignView • Changes show up both in the visual editor and in the code files • Changes in the visual editor change the properties and change the code • Changes in the code may change the properties andthe visual appearance in the editor (depending on whether the code is “definition” code or to be executed at run time) • At runtime – via programcode Windows Forms
Design Time: Setting Properties of Controls Object name in code Button caption Background color of Button Text Alignment Font Color Is button visible? Font Windows Forms
Editing Properties: Example Windows Forms
Properties in Code • After changing the properties, VS has added code to the Designerfile to make the changes Windows Forms
Making Simultaneous Changes to Multiple Controls Drag a rectangle around desired controls Change properties that are in common to the selected controls Can see the results All included controls are selected The one with white handles is the “master” Windows Forms
Controls Toolbar Send to Front or Back Windows Forms
Align and Size Controls • With all buttons selected, use the toolbar to align and resize them appropriately • The entireformalso has propertiesto set Made same size, aligned vertically, centered horizontally Windows Forms
Form Properties Windows Forms
Form Properties Designate a button to be activated by pressing the <ENTER> key Designate a button to be activated by pressing the <ESC> key Windows Forms
Form Properties Specify where window appears on screen Center the window on the screen Neither maximized nor minimized originally Windows Forms
Complete Form with More Controls Textboxes – all set to right-aligned text because they are for numeric input; last is read-only Align groups of controls to make the form look professional Label controls Windows Forms
Tab Order • For controls such as TextBoxes and Buttons that can have the keyboardfocus, there is a taborder than one can set to control the orderinwhichthecontrolsreceivefocus as the tabkey is pressed repeatedly Windows Forms
Tab Order • Click in the order you want focus to move. The Label for a TextBox should be clickedjustbefore the TextBox Not clicked since focus cannot be on a read-only control Windows Forms
Tab Order • Run the application and this window will appear Cursor is here, right-justified initially 2 If tab is pressed multiple times focus will move in the order of the numbers 3 4 5 Windows Forms
Current Status • At this point, the program runs successfully but does very little • We can see the form • We can type into the two input textboxes • We can click buttons • Nothing happens if we do these things • This is all of the “code behind” the form at this point Windows Forms
Handling Some Events • Three primary events we need to handle are the click events for the 3buttons • In the Design View, we doubleclick each button • A skeleton of the Event Handler for each button is written in the “code behind” .cs file • Each Event Handler is registered in the designer.cs file Windows Forms
Event Handler Skeletons 3 event handler skeletons added Event Handler registered Windows Forms
Add Event Handler Code • For the Quit button, we want to exittheprogram • For the Clear button, we want to make the text boxes empty and set the focus to the first text box • Run the program and observe how the Quit and Clear buttons work Windows Forms
The Calculate Button Handler • When Calculate is pressed, we want to get the points and hours values from the form and divide to calculate GPA Convert to decimal if possible Calculate GPA Else, show error message, reset form, and exit If OK so far, display result Windows Forms
Errors • The TryParse method takes care of some of the input errors a user may make • Empty input fields • Non-numeric input • It does not handle others such as • Entering 0 for the number of Hours Earned (divide by 0 error) • Producing a GPA of 57.2 or other invalidvalue • We must add code to handle the other anomalies Windows Forms
Edited Handler Windows Forms
Other Events • One may wish to display a “Goodbye” message when the application ends • Can be done in the btnQuit_Click handler for that approach to quitting the application but there are … • Other ways to quit • Red X • System Menu Close • Alt-F4 • Use FormClosing event to catch them all at once Windows Forms
Closing Event • In the DesignView, click on the lightningbolt in Properties to get a list of all Events for the form • Double-Click FormClosing Events Windows Forms
Load Event • Just before the window becomes visible for the first time, the Load event is recognized • It gives the programmer a chance to do some things at run time just before the window is shown • For example, we might want to do something like: • Display date and time • Display info about the application such as title, author, version, etc. • Give initial values to some controls Set window caption Get current date and format it for display as “Thursday, June 5, 2014” Windows Forms