C# Programming Tutorials: Beginners 05 Windows Forms and Event Handlers

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] for the next few videos we're going to go into windows forms applications so you've seen the console application and that's a plain black screen and you can't really do much other than read than write to the console now a modern application I would use WPF so use this thing here you wouldn't tend to use Windows forms applications anymore the quiet outdated but for beginners and simplicity it really is the best place to start because WPF applications are a lot more coding when it comes to creating the UI whereas windows forms you can just drag-and-drop and visually see things easier now WPF does have tools like that but again it's a lot more complicated than just a windows forms application so we're going to create a windows forms application but I would not use this once you've learned WPF in future videos but it's a nice way to get some you know visual UI like a window like this we can start creating we want to cover things like event handlers so we're going to start by the simplest thing I could think of that was good enough to be interesting and a little bit challenging as a basic calculator so we've got the calculator like this seven times nine equals and you can see the result and you can see what you're typing up here minus five plus eight and the results are working out as you're going times five equals this now we've got things like pi and all these extra functions and memories and we go to the side you've got programmer ones that show different styles we're not going to go into that depth because it's more about learning the code so much as making the application and future we might go ahead and create a full calculator but for now we just want to make you know form with some buttons so you can learn what happens when you click them and some text entry so instead of this individual box here and all these number and having to click instead of type I mean you'll know you can type on the keyboard in the new ones but still visually seen just a text box like this to type in what you want we're going to do that so I will have start by just creating this application first so go to new project and templates Visual Studio C sharp windows form application or let's just call this basic calculator and press Enter and similar to the console application um this has we right click open folder you can see you've got your been an object follower to the temporary ones you've got the project with the assembly info like before you can now Steve also got these extra things resources and settings again because this is only a temporary thing we're not going to go in-depth into Windows forms applications I'm not going to bother explaining you know in depth about these extra files because we're not going to use them we're going to get into WPF we've also got this app config which you can see over there your solution and project file and your code files and then this is a new type of code file that you haven't seen before it's a c-sharp file and then this design which is effectively this visual window you see in here so structure wise it's very similar the app config you've seen before and again it just tells you what framework to use so the only real difference is we've got a settings file which we're not going to use anyway and a resources which we're also not going to use the the very old and outdated so just ignore these two additions you don't need to know about them and now there's one new addition here which we'll go into in a second let's take a look at the program you can see again it's very similar to a console except now we've got this thing sta thread which I believe stands for single threaded application again it's a sorry single threaded apartment there's been a long while since I've done windows forms I wouldn't worry too much again about all this just think of this is the main where the program comes into just like the console application and instead of doing like console dot readline and blah blah blah instead we run this application which then runs this form and then this call to application run doesn't return until the form here has been closed with that you know the X button at the top so very similar to a console application it will come into here and it will run to here and then it will close but the difference is now instead of a console application appearing and closing we spin up this new form again don't worry about these two with they're not going to be used when you come to WPF so let's just take a look at what this looks like first let's press f5 you can see there's our nice little form already so we're going to form with a name form one we've got the little buttons that expand and minimize and close and then you see when I've closed the form the application stopped running I just make this text a little larger so you can also put a breakpoint by just clicking on the right hand side and pressing f5 to run again and you'll see it steps into here press f10 f10 and when you hit f10 here it's going to spin up the form and it hasn't come back yet as soon as we close and then comes out of here so that's the real basic quick overview of the program where it starts and how it runs so now let's go into this windows form you can see you can expand here and you can see the CS file and also the designer file now this designer file is auto-generated an exe is as Windows forms designer generated code so this is code and you don't need to visually use this you can completely construct in here which is just not recommended because this file like says auto-generated but just ignore this designer file for the most part but you can have a browse and see what's going on in there as you're creating things and see what's happening and see how it's done bring general you just looked at the CS file this is your main code file for the forum you'll notice double-clicking actually opens this visual designer as well so there's a few things you can do to get to the code-behind class the actual you know the code of the form you can either right click over here and view code and that will open up this form you can be in this visual designer and just press f7 and I'll take you to it as well so I start with this form let's just drag it larger so click the handle here drag it larger let's press f5 let's see that that's visually gone large you can see the difference and now let's change this title so you just click you can see this white dots around the form here that's the selected object so right now the only thing in our form is the form itself so we've got the form selected you can see down the bottom right the properties you can see form one here and there's a drop down for every part of the form and right now there's only the form so with form 1 selected you go to the properties window you can see here text and form 1 and that means this title at the top of the form so let's just click here and type basic calculator and press ENTER and you can see up here now the names changed so that's the start we've got the tile so now we want to create some buttons to do things so as I mentioned if we spin up the original calculator we're not going to bother with all these buttons well to be honest we can umm we might do yeah let's do these but you won't need them because instead of this box here that you can't click in we're going to have an actual text box you can type in and change values - and then you know press Enter or click equals to get the result so let's make the we'll make this section in fact it will be will be this whole section here this gray section so let's just copy this section as well as adding a text box at the top so start with the textbook so to add that click toolbox let's just pin this because we're going to be using it for a while all windows forms when we get everything and these are all the visual components you can use so you want a text box click and drag and let go you can see we've got a little text box here then you hover to the right and you can change the size so let's make it nice and large and then if we run that we press f5 so you can see we got a little text box and we can type away what you'll notice is if we change the size of the form then this text box doesn't resize so let's fix that quickly and they are with anchor points so if you click you notice the and trail a little grey dots all around the box that's what you've got selected so when you select the main form it's around the form when you select the text box it goes around the text box also in the bottom right it changes from the form one to the text box one now also this name this text box one and this form one is the name that you access this text box within your code so when we come to get this information or want to show it or do anything with it we access this text box with this name and if you go to the properties and you scroll down you can see here name with parentheses around so similar to variables let's give this a new name so let's call this user input text and press ENTER so it's a little bit more descriptive now thinking on this we also need a result so we're going to add a label also let's first do this anchor point I was talking about so you can see here and cut in the layout and it's anchored to the top left so it means it's going to the top and the left are going to stay based on the relative position of the parent which is the form so we also add that right by clicking here and now you can even do it visually in the designer you can see the size has changed with the form and that's what we want let's also make a label now for the result so when you've worked out to calculation you want to see what the result was so find a label here drag and drop click and drag and you can see it sort of snaps to these blue lines these are sort of auto aligning based on some default sizes and you can see also this label you can't resize by default there's no drug and that's because a label by default us I believe it's an auto size again I haven't done this in years so you'll have to bear with me let's see if we can find it there we go Auto sighs let's change this to false and now you can see we've got the dots all around so we can now click and drag and let's resize this to the edge and let's also and create the same as the text box the label we want to call [Music] calculation results text and for the default value instead of saying label 1 here let's put please enter an equation and press Enter or equals so now we've got this will be changed to the actual result when we've entered something so now we've got effectively this top bar now we need all these buttons and these are all going to be buttons because they're that's what they do you click them and they're going to do something so we need one two three four one two three four five so we need four by five now you can do I believe tables a table layout panel and there we go and we click and drag and that's position to the edges let's anchor this will also anchor this to the bottom so as well as the right we'll do the bottom and what that means is when we expand downwards this table will now fill up all the remaining bottom now we need four across five down so click this little arrow at the top right add column add column that's four columns add rows we've got two three four four five and now I've got to remember how we do anything with these columns it's been that long edit rows and columns there we go so columns we've got 50% 50% now you can do I believe if we do auto size on all of them they're going to equally size as my guess see if that's true and not so much okay so we've got four let's do a percentage of 25 so there we've got four columns and now let's do the rows as well so and it rose and then we've got five so on 20% for these again don't worry too much about remembering or understanding how to do these this is this is a one-time use this is just a quick way to get some UI when you come to do some UI for real project she will use WPF and then we'll go a lot more into detail about how all the UI is constructed this is just really to get you going to you know visually create this and and do more on learning the event analyze and things like that not so much learning this UI so we know that this grid ready to accept the buttons so let's label this table first so you can see it selected here and we've got table layout panel one so let's just call this something like button panel so buttons panel I'll do and this is all just so when you're in code you don't see all these random names it's more descriptive so it always helps to to name everything so let's click button in the toolbar drag and drop and you can see we've dropped it inside of the first row in the first column and by default a button is a druggable size which we don't want we want this to to really fill this space so for that I believe there's something called a dock I'm not mistaken but it arranged it alphabetically instead there we go dock so I think we can do a dock fill by clicking the center and there we go this is now filled that whole area and call button 1 which is the name at the top so let's call this take a look at this calculator see e button so see button and then the text inside we want to say see II means you've got c/e let's press f5 to run visualize this and you can see I can see that for one the labels slightly too high because we've gone over the bottom of the text box but you can see this is important this is a you know a clickable button and it's also a quarter the width of at the screen because everything resizes and you can see when we get to a certain size like I'd say here things are going to be too small to fit so visually you can you can place it next to it and see that the minimum size you probably want to calculate to be is here so let's try and remember that position there and then go into here and sort of we can't change you while it's running click stop and let's drag it to let's say about here and you can see that's also off so we want to I'd say there's about the smallest you want to allow this window to go so you see the size here 506 by five to two let's change that to 500 by 520 and that's still fine so let's now use this as like a minimum size so with the form one selected again I think this never go minimum size let's type 505 20s but out if I could actually drag it out I condor drug it out I lent it maximum sized that's why glad to put it in the right place minimum size now let's drag this back out let's fix this label so let's just move it down you can use the arrow keys so I'm pressing down on the arrow key and you can see it move down out of the way and then it should resize that just underneath press f5 again now you still see it's overlapping okay sir move down quite a bit and let's check it's actually moving there we go so we're finally out of the way and this is to deal with this is a high-resolution screen and you can see how the text is slightly blurry that's Windows 10 attempting to auto scale up a non scalable form so an old windows form so the positioning isn't exactly as you see it in the design but again ignore that for now it's not about windows forms so much about just getting this thing built so we can start doing some functions with it so now you've made this one button and you can just basically do exactly the same for the rest of all of these buttons and you want to give them a name of the title so what they're doing so CEC then we'll have we don't really need this one but we might as well put it in and we'll just call that back that's to delete a character so as you're typing it deletes one of the things you've typed and then divided times minus plus equals we can call that dot or period and call that sign or plus or minus that basically toggles between whether they're the values are plus or a minus again that's not so much useful in ours because we're going to be typing so in fact let's leave that one out and leave it as a blank and all the others are numbers so just give them names and always through this I'll just fast-forward the video so you don't have to watch me doing this but in essence you click the button you drag you drop you go over to the right side properties you change the dock to fill you change the text to the visible text of a button and then you change the name to a descriptive name and then go ahead and repeat this for every button so you can see how I'm really quickly adding these all's I've done is clicked on one button press control-c and I click inside the the cell of the table and press control V to paste and click again and paste so this is a quick way to get the buttons in I'll then go back and change all the names so there you can see we've got all the buttons added and we drop down this box you can see all the names see button ze doll for delete or back or jvo and divided dart or period 8 equals oops as a mistake equals wants to be equals button 5 button that's the form for bottom - 9 1 + 7 6 3 times or multiply - user important zero so everything's been labeled and named and created so let's press f5 and take a look so here's our little basic calculator with the buttons that we can click to do things the texts telling us what to do when the box low going to actually enter our equation to work out and then you can expand and go down to the minimum size and it's still a fact that's a nice size to start at let's resize our form to the smallest size there we go now when you run this program you'll be expected to let's say we did 4 + 5 you'd expect to press ENTER and to get you know the result that would be a natural response that you'd expect got a little bit of a spacing going on here I'm just see if that changes with the minimum size ah yeah so when you make it minimum you get a weird space in so let's just leave it at that size for now yeah so see you type 4 + 5 new press Enter you'd expect that to give you your result so to correct that it's going to be the same thing as when you press the equals button that's going to be the thing that does the calculation and you can see here the intellitrace is sort of given as a some visual output of what we're doing which is quite cool so let's first make this equals a default button which means when the forms focused in your press ENTER it should press that button so if we click this equals button and then we scroll down I believe Dioner sorry it's the form I believe you click the form and you scroll down and you should have you got a cancel button it's remembering what it's called it except button yeah there we go so except unlike the default button of your when you press the Enter I believe the cancel button is when you press the escape so we can also link the C II which should just clear the current text which again in our program the C really is the same as C because we're doing the whole calculation in one it's not like we've got an ongoing calculation so saying that let's delete the C so let's select the form now let's change this accept button to be our equals button now you can see it's gone blue which is like a sign that it's a default button so let's first see if this works with having a textbox test and then you can see now when we press ENTER for one over here it showed that we've pressed enter and two we don't get that annoying Windows beep so we now know it's effectively pressing this button when we press ENTER which is what we want after we don't do anything yet so you can't really see anything visual and then also want the C to be pressed on we press escape so escape now we we just get the beeping noise so let's close select the form go to the properties and the cancel button change that to the C ebon run the program with f5 type some text press escape you can see there over here it's saying we press C and we also don't get that annoying beep so now when we press escape we're effectively clicking this when we press Enter or effective looks like in the equals so now when we link actions into these they will you know be useful so let's start by creating an event handler so now we've got the form visually made we want to actually do things so they would simply thing to do is this C button which will is clear this textbox so it will get rid of any input so there's multiple ways you can add event handlers but an event handler is something that responds to an event it handles the event hence the name so the event being you've clicked this button and then the handler being effectively a function and method just a special type of method so you can see down the properties you've got this events arrow or lightning bolt you click this and you can see a load of events that are specific to a Windows forms button and you can action any of these events so visible change tabindex changed size changed all these are events the default event for a button as a click you can see this drop down here this is a drop down of all functions that it can find inside this forms code in order to do something when you click the bottom so a really quick way of doing this is you can just double click this button or you can double click inside the click event here so let's just double click here and you can see it's gone it's basically jumped into the code behind of the class so if we went back to the class and press f7 it's jump to the code behind which is just this file this form 1 dot CS you can see their form on dot cs and it's then created this private function for us it's private function returns nothing it's called C button underscore click and it's got two parameters one's an object so we can be anything sender and the second is event augs which is for handling you know the event that happens some information about the click event in this case and then this is now the function that will run when we click the button so let's just make a message box pop-up so if you type each box dot she'll need to do hi press f5 to run and when we click the C button our code now runs because it is hi box there's no tie or we just literally pass the string just to show that something was happening we should also be able to test that here we press escape on the keyboard we get the same thing so this function is now being wrong we've we've linked in this button click to this function so how did that happen we double clicked here to add this and it automatically did it for us so let's just delete this from the list here and now that's gone away nothing will happen you can see in the drop down it's automatically found that this is a function in the form in the forms class that's able to accept a click it's the same type that the click expects so it can assign it as reassigned let's just take a look at what that does and what that means when this happens and then we'll do it manually so I mentioned this designer class here which is auto-generated so you open this file you can already see it's added all these private variables and these are all the things we dragged and dropped onto there the visual designer so that has all the buttons reality there's the label the input text the table layout panel so it's created private variables and then we go into this region you can see initialize component which if we go to the form 1 dot C S Class you can see the constructor when it's created call the initialize component and that function is inside this auto-generated class so when when form 1 is created in the program here when we do new form this first goes into the constructor which then call the initialize which goes into here which then effectively creates instant eights all of these variables so we create instances of the text boxes the labels the buttons and then remember this is all auto-generated code this is what Visual Studio has done for us when we visually created the form it's then taken the buttons panel which is the panel where all the buttons are and suspended layout so that the window doesn't keep redrawing itself as it's being created then it suspends the hole forms layout as well so these two things just stop the form from drawing then it goes ahead and creates all the properties and possessions everything to the exact place that we visually designed and it does the anchor points and all you can flick through this yourself in and see again I won't go through explaining this because you won't need to use Windows forms you'll be doing WPF it's nice to see where everything is and what's happening if you you interested so let's go to this C button here and you can see now here the single-line c button click and if you hover over or better yet we just delete and press dot type click because it's a lightning bolt which means it's an event and well isn't it bent handle in this case you can see it occurs when the control is clicked and the way you work with event handlers you don't assign them directly you can but you don't usually do a plus equals which if you recall when you're adding values together it means that click equals click plus this event handler so you're combining two event handlers into one and this works because you know event handlers are a special thing they can be there's a single property if you will we press f12 on click you can see the type of property it's a public so we can access it and then it's got this additional thing an event before the variable type so the types an event handler which if we press f12 on that you can also see is this thing called a delegate which we'll get into in future videos but in essence it's it's a function that has two properties and object in an event args which you'll remember is in our function C click Seaborn click so what happens is when a property or variable is of type event you can use this syntax of plus equals and basically it means you could just say multiple functions can run when this button is clicked so if we added an extra function if we go into the form really quick and just copy and paste this function give it another name click one hye-won we go back into the code we copy and paste and we do click plus equals this function click plus equals this function so now this is added two functions to the single event of click we press f5 to run and we click this button let's see we get hi we click OK and we get hi 1 we you can do this entire thing yourself in code if you want to instead so if we deleted that line from the auto-generated file and we run the code you can see now nothing happens and then inside of our constructor this is our normal class not the auto-generated class we can just go after the initialized components and put that code ourself and then if we run we will now get the message box appearing so you can hook in the events yourself if you don't want to use there the visual designer but to be honest there's no real reason it's just nice to see how it's constructed that when you open this and you double click this doll that's created the function for us then in the design it's added this click event handler so it just does that for us it saves us some work so that's fine and the seee you can see the see doesn't have it here because this this properties pane is populated based on this auto-generated file it doesn't take into account what we do in our own code file so because we added it after here it's not recognized in the design that's let's just delete our code and let's let the designer do it automatically for us so click see it already exists let's just click the drop-down and select seee so now to add event handlers so functions that will run when we click these buttons all we have to do is go through and double click each button and you can see we get the function you and there we go as all the functions ready to do things with so before we go start organizing this class again let's add the XML comment three forward slashes and basic calculator I'm going to be a little bit lazy on the comment descriptions you know how to do comments now and when it comes to your application you can make these a lot more descriptive I'll make them descriptive enough that they useful but you know we're not going to go super descriptive because it will just waste time on the videos this is the constructor so we want a region with hash region let's call it constructor go to the end point end region there because this is the start and finish of their constructor give the constructor a comment as well because it's a public function anything public should really have the exportable comments the three forward slashes one will just say default constructor collapse that to get it out the way and now these are a load of functions so we could group these all into one big region just called public functions and but let's be a little bit more definitive so we have I'd say the plus the minus the times that divide the operators so let's group those so there's the divide start the region here operator functions divide x minus plus and equals is no really part of that and region and as the operator functions will comment these functions as we go now you've got the dot I'd class that's part of the numbers dot 0 1 2 3 4 5 6 7 8 9 these are all the numbers let's call it number functions or sorry methods is what we not functions remember when I talk about functions and these things I say the word function because that's just how they've been for so long but technically termed that we call them methods because again when we get further down line you'll see something called a function which is basically here a func as they call it shortcut capsulation method that has no parameters so because you know we call this a function then the definition of a foam-core a function here wouldn't make sense so we call it a method so got number methods and then they finish here and then finally we have the delete and the seee so let's pull these hair clearing from Android cleaving methods so we're keeping the class nice and organized so we're going to work our way through these functions and I'm going to split this video up to keep it nice and short so right now we've made a class we've made a windows form project we've got a form that we visually chopped a load of buttons and texts and labels on we've run the form and assigned the enter to the equals press and the escape to the C e which now runs a function so you can see something happening in the very next video we're going to start adding these functions one by one and and creating the actual function of the calculator so really all you've learned here is a very quick overview of constructing a UI so we haven't really gone into depth about how we've done that again because we will be learning WPF but if you've watched the video it really is as simple as opening the toolbox dragging and dropping components on and then taking a look at the properties which would go back to here and just having a play it's sort of self-explanatory just by trial and error and playing with things you really can't figure out the windows forms and then we've looked at events so actually how to do things here so in this case we just double-click C E and once there's already a function on the button if you double-click it will just jump you straight to that function as like a nice shortcut so if you want to go I want to press 9 I want to do something double-click I'll jump you to the function so a nice little shortcut and then we've had a quick look at the design the auto-generated file to show you what's going on and how those functions and events were added and how the whole form came together in the next video like I say we're going to go over adding functions to these buttons and passing the input clearing the output or things like that so stay tuned [Music]
Info
Channel: AngelSix
Views: 262,841
Rating: undefined out of 5
Keywords: c#, tutorial, free, programming, beginners, class, function, variables, hd, learn, windows forms, events, event handlers
Id: W6vJ_c9Mt6A
Channel Id: undefined
Length: 40min 0sec (2400 seconds)
Published: Fri Dec 23 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.