Microsoft visual c# pdf




















If you expand the References folder, you will see the default set of references that Visual Studio adds to your project. These assemblies provide access to many of the commonly used features of the.

You will learn about many of these assemblies as you progress through the exercises in this book. It is optional, and it might not always be present. You can specify settings that your application uses at run time to modify its behavior, such as the version of the. NET Framework to use to run the application. You will learn more about this file in later chapters of this book. You will write your code for the console application in this file.

It also contains some code that Visual Studio provides automatically, which you will examine shortly. Writing your first program The Program. In C , all executable code must be defined within a method, and all methods must belong to a class or a struct.

This method should be defined in the manner specified in the Program class as a static method; otherwise, the. NET Framework might not recognize it as the starting point for your application when you run it.

Important C is a case-sensitive language. You must spell Main with an uppercase M. Write the code by using Microsoft IntelliSense 1. In the Code and Text Editor window displaying the Program. On the new line, type the word Console; this is the name of another class provided by the assemblies referenced by your application.

It provides methods for displaying messages in the console window and reading input from the keyboard. As you type the letter C at the start of the word Console, an IntelliSense list appears.

This list contains all of the C keywords and data types that are valid in this context. You can either continue typing or scroll through the list and double-click the Console item with the mouse. Alternatively, after you have typed Cons, the IntelliSense list automatically homes in on the Console item, and you can press the Tab or Enter key to select it. Type a period immediately following Console. Another IntelliSense list appears, displaying the methods, properties, and fields of the Console class.

Scroll down through the list, select WriteLine, and then press Enter. Alternatively, you can continue typing the characters W, r, i, t, e, L until WriteLine is selected, and then press Enter. The IntelliSense list closes, and the word WriteLine is added to the source file. Type and another IntelliSense tip will appear. This tip displays the parameters that the WriteLine method can take.

In fact, WriteLine is an overloaded method, meaning that the Console class contains more than one method named WriteLine—it provides 19 different versions of this method. You can use each version of the WriteLine method to output different types of data. Chapter 3 describes overloaded methods in more detail. WriteLine "Hello World! IntelliSense icons When you type a period after the name of a class, IntelliSense displays the name of every member of that class. To the left of each member name is an icon that depicts the type of member.

These are comments, which are ignored by the compiler but are very useful for developers because they help document what a program is actually doing. Take, for instance, the following example: Click here to view code image Console. You are actively encouraged to document your code with as many meaningful comments as necessary. Build and run the console application 1.

On the Build menu, click Build Solution. This action compiles the C code, resulting in a program that you can run. The Output window appears below the Code and Text Editor window.

Tip If the Output window does not appear, click Output on the View menu to display it. The following image shows what happens if you forget to type the closing quotation marks after the text Hello World in the WriteLine statement.

Notice that a single mistake can sometimes cause multiple compiler errors. Tip To go directly to the line that caused the error, you can doubleclick an item in the Error List window. You should also notice that Visual Studio displays a wavy red line under any lines of code that will not compile when you enter them.

If you have followed the previous instructions carefully, there should be no errors or warnings, and the program should build successfully. Tip There is no need to save the file explicitly before building because the Build Solution command automatically saves it. An asterisk after the file name in the tab above the Code and Text Editor window indicates that the file has been changed since it was last saved. On the Debug menu, click Start Without Debugging. A command window opens, and the program runs.

If you run the program by using the Start Debugging command on the Debug menu, the application runs, but the command window closes immediately without waiting for you to press a key. The command window closes, and you return to the Visual Studio programming environment.

Be aware that you might need to click the double-arrow button on the right edge of the Solution Explorer toolbar to make this button appear. Entries named bin and obj appear above the Program. Visual Studio creates these folders when you build your application; they contain the executable version of the program together with some other files used to build and debug the application.

In Solution Explorer, expand the bin entry. Another folder named Debug appears. Note You might also see a folder named Release. In Solution Explorer, expand the Debug folder. Several more items appear, including a file named TestHello.

This is the compiled program, which is the file that runs when you click Start Without Debugging on the Debug menu. The other files contain information that is used by Visual Studio if you run your program in debug mode when you click Start Debugging on the Debug menu.

Using namespaces The example you have seen so far is a very small program. However, small programs can soon grow into much bigger programs. As a program grows, two issues arise. First, it is harder to understand and maintain big programs than it is to understand and maintain smaller ones. Second, more code usually means more classes, with more methods, requiring you to keep track of more names. As the number of names increases, so does the likelihood of the project build failing because two or more names clash.

For example, you might try to create two classes with the same name. The situation becomes more complicated when a program references assemblies written by other developers who have also used a variety of names.

In the past, programmers tried to solve the name-clashing problem by prefixing names with some sort of qualifier or set of qualifiers. Names become longer, you spend less time writing software and more time typing there is a difference , and you spend too much time reading and rereading incomprehensibly long names.

Namespaces help solve this problem by creating a container for items such as classes. Two classes with the same name will not be confused with each other if they live in different namespaces.

Greeting in your programs. If another developer also creates a Greeting class in a different namespace, such as NewNamespace, and you install the assembly that contains this class on your computer, your programs will still work as expected because they are using your TestHello.

Greeting class. It is good practice to define all your classes in namespaces, and the Visual Studio environment follows this recommendation by using the name of your project as the top-level namespace.

NET Framework class library also adheres to this recommendation; every class in the. NET Framework lives within a namespace. For example, the Console class lives within the System namespace.

This means that its full name is actually System. Of course, if you had to write the full name of a class every time you used it, the situation would be no better than prefixing qualifiers or even just naming the class with some globally unique name such as SystemConsole. Fortunately, you can solve this problem with a using directive in your programs. Generic; using System. Linq; using System.

Text; using System. Tasks; These lines are using directives. A using directive brings a namespace into scope. In the subsequent code in the same file, you no longer need to explicitly qualify objects with the namespace to which they belong. The five namespaces shown contain classes that are used so often that Visual Studio automatically adds these using directives every time you create a new project. You can add more using directives to the top of a source file if you need to reference other namespaces.

Note You might notice that some of the using directives appear grayed-out. These directives correspond to namespaces that are not currently used by your application.

However, if you require items that are held in these namespaces later, you will have to add the using directives back in again. The following exercise demonstrates the concept of namespaces in more depth. Try longhand names 1. The build fails, and the Error List window displays the following error message: Click here to view code image The name 'Console' does not exist in the current context.

In the Error List window, double-click the error message. The identifier that caused the error is highlighted in the Program. The project should build successfully this time. Run the application to be sure that it still works by clicking Start Without Debugging on the Debug menu. Namespaces and assemblies A using directive simply brings the items in a namespace into scope and frees you from having to fully qualify the names of classes in your code.

Classes are compiled into assemblies. An assembly is a file that usually has the. An assembly can contain many classes. The classes that the. NET Framework class library includes, such as System. Console, are provided in assemblies that are installed on your computer together with Visual Studio. You will find that the. NET Framework class library contains thousands of classes. If they were all held in the same assembly, the assembly would be huge and difficult to maintain.

If Microsoft were to update a single method in a single class, it would have to distribute the entire class library to all developers! For this reason, the. NET Framework class library is split into a number of assemblies, partitioned by the functions that they perform or the technology that they implement. Console, and other assemblies contain classes for manipulating databases, accessing web services, building GUIs, and so on.

If you want to make use of a class in an assembly, you must add a reference to that assembly to your project. You can then add using directives to your code that bring the items in namespaces in that assembly into scope.

You should note that there is not necessarily a equivalence between an assembly and a namespace: A single assembly can contain classes defined in many namespaces, and a single namespace can span multiple assemblies.

For example, the classes and items in the System namespace are actually implemented by several assemblies, including mscorlib. This all sounds very confusing at first, but you will soon get used to it. When you use Visual Studio to create an application, the template you select automatically includes references to the appropriate assemblies.

You will see that a console application automatically contains references to assemblies called Microsoft. CSharp, System, System. Core, System. Data, System. DataSetExtensions, System. Http, System. Xml, and System. You might be surprised to see that mscorlib.

The reason for this is that all. NET Framework applications must use this assembly because it contains fundamental runtime functionality. The References folder lists only the optional assemblies; you can add or remove assemblies from this folder as necessary.

To add references for additional assemblies to a project, right-click the References folder and then click Add Reference. You will perform this task in later exercises. You can remove an assembly by right-clicking the assembly in the References folder and then clicking Remove. Creating a graphical application So far, you have used Visual Studio to create and run a basic console application.

The Visual Studio programming environment also contains everything you need to create graphical applications for Windows These templates are referred to as Universal Windows Platform UWP apps because they enable you to create apps that function on any device that runs Windows, such as desktop computers, tablets, and phones. You can design the user interface UI of a Windows application interactively.

Visual Studio provides you with two views of a graphical application: the design view and the code view. You use the Code and Text Editor window to modify and maintain the code and program logic for a graphical application, and you use the Design View window to lay out your UI. You can switch between the two views whenever you want. This program displays a simple form containing a text box where you can enter your name and a button that when clicked displays a personalized greeting in a message box.

If you want more information about the specifics of writing UWP apps, the final few chapters in Part IV of this book provide more detail and guidance. Create a graphical application in Visual Studio 1. Start Visual Studio if it is not already running. In the left pane, expand the Installed node if it is not already expanded , expand Visual C , and then click Windows Universal.

In the middle pane, click the Blank App Universal Windows icon. In the Name box, type Hello. At this point, you will be prompted with a dialog box asking you to specify on which builds of Windows 10 your application is going to run. Later builds of Windows 10 have more and newer features available. Microsoft recommends that you always select the latest build of Windows 10 as the target version, but if you are developing enterprise applications that also need to run on older versions then select the oldest version of Windows 10 that users are using as the minimum version.

However, do not automatically select the oldest version of Windows 10 as this might restrict some of the functionality available to your application: If this is the first time that you have created a UWP application, you might also be prompted to enable developer mode for Windows 10, and the Windows 10 settings screen will appear. Select Developer Mode. A dialog box will appear confirming that this is what you want to do, as it bypasses some of the security features of WindowsClick Yes.

Windows will download and install the Developer Mode package, which provides additional features for debugging UWP applications: 9. Note External apps that are not downloaded from the Windows Store could potentially expose personal data and pose other security risks, but it is necessary to enable Developer Mode if you are building and testing your own custom applications. Return to Visual Studio. After the app has been created, look in the Solution Explorer pane.

Although it is called Blank App, this template actually provides a number of files and contains some code. For example, if you expand the MainPage. This file is where you add the initial code for the application. In Solution Explorer, double-click MainPage.

This file contains the layout of the UI. You will learn more about XAML as you progress through the exercises in this book. At the top is a graphical view depicting the screen of, by default, a Surface Book. The lower pane contains a description of the contents of this screen using XAML. In the next exercise, you will use the Design View window to lay out the UI for the application, and you will examine the XAML code that this layout generates.

Note Before going further, it is worth explaining some terminology. In traditional Windows applications, the UI consists of one or more windows, but in a Universal Windows Platform app, the corresponding items are referred to as pages.

For the sake of clarity, I will simply refer to both items by using the blanket term form. In the following exercises, you will use the Design View window to add three controls to the form displayed by your application. You will also examine some of the C code automatically generated by Visual Studio to implement these controls. Create the user interface 1. Click the Toolbox tab that appears in the margin to the left of the form in the Design View window.

The Toolbox appears and displays the various components and controls that you can place on a form. This section displays a list of controls that most graphical applications use.

If you accidentally place the wrong control on a form, you can easily remove it by clicking the item on the form and then pressing Delete. A TextBlock control is added to the form you will move it to its correct location in a moment , and the Toolbox disappears from view. Tip If you want the Toolbox to remain visible but not hide any part of the form, at the right end of the Toolbox title bar, click the Auto Hide button it looks like a pin.

The Toolbox is docked on the left side of the Visual Studio window, and the Design View window shrinks to accommodate it. You might lose a lot of space if you have a lowresolution screen. Clicking the Auto Hide button once more causes the Toolbox to disappear again. The TextBlock control on the form is probably not exactly where you want it.

You can click and drag the controls you have added to a form to reposition them. Using this technique, move the TextBlock control so that it is positioned toward the upper-left corner of the form. The exact placement is not critical for this application. Notice that you might need to click away from the control and then click it again before you can move it in the Design View window.

The XAML description of the form in the lower pane now includes the TextBlock control, together with properties such as its location on the form, governed by the Margin property, the default text displayed by this control in the Text property, the alignment of text displayed by this control as specified by the HorizontalAlignment and VerticalAlignment properties, and whether text should wrap if it exceeds the width of the control.

Your XAML code for the TextBlock will look similar to this your values for the Margin property might be slightly different, depending on where you positioned the TextBlock control on the form : Click here to view code image The XAML pane and the Design View window have a two-way relationship with each other. For example, you can change the location of the TextBlock control by modifying the values in the Margin property. On the View menu, click Properties Window it is the last item in the menu.

If it was not already displayed, the Properties window appears at the lower right of the screen, under the Solution Explorer pane. You can specify the properties of controls by using the XAML pane under the Design View window, but the Properties window provides a more convenient way for you to modify the properties for items on a form, as well as other items in a project.

The Properties window is context sensitive in that it displays the properties for the currently selected item. If you click the form displayed in the Design View window outside the TextBlock control , you can see that the Properties window displays the properties for a Grid element. All forms contain a Grid element that controls the layout of displayed items; for example, you can define tabular layouts by adding rows and columns to the Grid. In the Design View window, click the TextBlock control.

The Properties window displays the properties for the TextBlock control again. In the Properties window, expand the Text property of the TextBlock control. Change the FontSize property to 20 pt and then press Enter. This is an approximate conversion of the font size from points to pixels 3 points is assumed to be roughly 4 pixels, although a precise conversion would depend on your screen size and resolution.

Any changes that you make using the Properties window are automatically reflected in the XAML definitions, and vice versa. The font size of the text for the TextBlock control in the Design View window and the Properties window changes. In the Properties window, examine the other properties of the TextBlock control. Feel free to experiment by changing them to see their effects. Notice that as you change the values of properties, these properties are added to the definition of the TextBlock control in the XAML pane.

Each control that you add to a form has a default set of property values, and these values are not displayed in the XAML pane unless you change them. You can do this either by editing the Text element in the XAML pane or by changing the value in the Properties window this property is located in the Common section in the Properties window. Notice that the text displayed in the TextBlock control in the Design View window changes. Click the form in the Design View window, and then display the Toolbox again.

In the Toolbox, click and drag the TextBox control onto the form. Move the TextBox control so that it is directly below the TextBlock control. Tip When you drag a control on a form, alignment indicators appear automatically. These give you a quick visual cue to ensure that controls are lined up neatly. You can also manually edit the Margin property in the XAML pane to set the left-hand margin to the same value of that for the TextBlock control.

In the Design View window, place the mouse over the right edge of the TextBox control. The mouse pointer should change to a double-headed arrow, indicating that you can resize the control. Drag the right edge of the TextBox control until it is aligned with the right edge of the TextBlock control above.

Display the Toolbox again, and then click and drag a Button control onto the form. Place the Button control to the right of the TextBox control on the form so that the bottom of the button is aligned horizontally with the bottom of the text box. Verify that the caption of the Button control on the form changes to display the text OK. The form should now look similar to the following figure: Note The drop-down menu in the upper-left corner of the Design View window enables you to view how your form will render on different screen sizes and resolutions.

In this example, the default view of a To the right of the drop-down menu, two buttons enable you to switch between portrait view and landscape view. The projects used in subsequent chapters will use a On the Build menu, click Build Solution, and then verify that the project builds successfully.

Ensure that the Debug Target drop-down list is set to Local Machine as shown below. It might default to Device and attempt to connect to a Windows phone device, and the build will probably fail. Then, on the Debug menu, click Start Debugging. The application should run and display your form.

The form looks like this: Note When you run a Universal Windows Platform app in debug mode, a debug toolbar appears near the top of the form. You can use this toolbar to track how the user is navigating through the form and monitor how the contents of the controls on the form change. You can ignore this menu for now; click the double bar at the bottom of the toolbar to minimize it. In the text box, you can overtype the existing text with your name, and then click OK, but nothing happens yet.

You need to add some code to indicate what should happen when the user clicks the OK button, which is what you will do next. Return to Visual Studio On the Debug menu, click Stop Debugging. Note You can also click the Close button the X in the upper-right corner of the form to close the form, stop debugging, and return to Visual Studio.

You have managed to create a graphical application without writing a single line of C code. It does not do much yet you will have to write some code soon , but Visual Studio actually generates a lot of code for you that handles routine tasks that all graphical applications must perform, such as starting up and displaying a window. Before adding your own code to the application, it helps to have an understanding of what Visual Studio has produced for you. The following section describes these automatically generated artifacts.

The file MainPage. The following code for the form is displayed in the Code and Text Editor window: Click here to view code image using System; using System. IO; using System. WindowsRuntime; using Windows. Foundation; using Windows.

Collections; using Windows. Xaml; using Windows. Controls; using Windows. Primitives; using Windows. Data; using Windows. Input; using Windows. Media; using Windows. There is a little bit of code for the MainPage class known as a constructor that calls a method named InitializeComponent.

A constructor is a special method with the same name as the class. It runs when an instance of the class is created and can contain code to initialize the instance.

You will learn about constructors in Chapter 7. The class actually contains a lot more code than the few lines shown in the MainPage. This hidden code performs operations such as creating and displaying the form and creating and positioning the various controls on the form. At this point, you might be wondering where the Main method is and how the form gets displayed when the application runs. Remember that in a console application Main defines the point at which the program starts.

A graphical application is slightly different. In Solution Explorer, you should notice another source file called App. If you expand the node for this file, you will see another file called App. In a UWP app, the App. If you double-click App. ApplicationModel; using Windows. Activation; using Windows. InitializeComponent ; this. Navigate typeof MainPage , e. This method runs when the application starts and the code in this method causes the application to create a new Frame object, display the MainPage form in this frame, and then activate it.

Adding code to the graphical application Now that you know a little bit about the structure of a graphical application, the time has come to write some code to make your application actually do something. Write the code for the OK button 1. In the Design View window, open the MainPage. While still in the Design View window, click the OK button on the form to select it. In the Properties window, click the Event Handlers button for the selected element.

This button displays an icon that looks like a bolt of lightning, as demonstrated here: The Properties window displays a list of event names for the Button control. An event indicates a significant action that usually requires a response, and you can write your own code to perform this response. In the box adjacent to the Click event, type okClick, and then press Enter. The MainPage. Add the following using directive shown in bold to the list at the top of the file the ellipsis character […] indicates statements that have been omitted for brevity : Click here to view code image using System; Navigation; using Windows.

Popups; 6. Text ; msg. Again, do not worry too much about the syntax, just be sure that you copy the code exactly as shown; you will find out what these statements mean in the next few chapters. The second statement displays the MessageDialog, causing it to appear on the screen. The MessageDialog class is defined in the Windows. Popups namespace, which is why you added it in step 5.

Note You might notice that Visual Studio adds a wavy green line under the last line of code you typed. NET Framework provides. You can safely ignore this warning. Click the MainPage. In the lower pane displaying the XAML description of the form, examine the Button element, but be careful not to change anything.

Notice that it now contains an attribute named Click that refers to the okClick method. Click here to view code image 9. On the Debug menu, click Start Debugging.

When the form appears, in the text box, type your name over the existing text, and then click OK. A message dialog box appears displaying the following greeting: Click Close in the message box. Other types of graphical applications Apart from Universal Windows apps, Visual Studio also lets you create other types of graphical applications.

These applications are intended for specific environments and do not include the adaptability to enable them to run across multiple platforms unchanged. The other types of graphical applications available include: WPF App. It provides an extremely powerful framework based on vector graphics that enable the user interface to scale smoothly across different screen resolutions. Many of the key features of WPF are available in UWP applications, although WPF provides additional functionality that is only appropriate for applications running on powerful desktop machines.

Windows Forms App. This is an older graphical library that dates back to the origins of the. You can also find this template in the Class Desktop template list in Visual Studio As its name implies, the Windows Forms library is intended for building more classical forms-based applications using the Graphics Device Interface GDI libraries provided with Windows at that time.

While this framework is quick to use, it provides neither the functionality and scalability of WPF nor the portability of UWP. If you are building graphical applications, unless you have good reasons not to do so, I would suggest that you opt for the UWP template. Summary In this chapter, you saw how to use Visual Studio to create, build, and run applications.

You created a console application that displays its output in a console window, and you created a Universal Windows Platform application with a simple GUI.

If you want to continue to the next chapter, keep Visual Studio running and turn to Chapter 2. If you want to exit Visual Studio now, on the File menu, click Exit. If you see a Save dialog box, click Yes to save the project. In the left pane, expand Installed, and console application using Visual Studio Create a new Universal Windows app using Visual Studio Build the application Run the application in debug mode Run the application without debugging then click Visual C. In the middle pane, click Console Application.

In the Location box, specify a directory for the project files. Type a name for the project, and then click OK. In the middle pane, click Blank App Universal Windows. Use variables to store information. Work with primitive data types. Increment and decrement variables. This chapter introduces you to the elements of Microsoft Visual C syntax and semantics, including statements, keywords, and identifiers. Understanding statements A statement is a command that performs an action, such as calculating a value and storing the result or displaying a message to a user.

You combine statements to create methods. Main, which was introduced in the previous chapter, is an example of a method. Skip to content. DrawEllipse pen, e.

DrawRectangle pen, e. Left, e. Top , new Point e. Right, e. Download the example to see additional details. This entry was posted in drawing , graphics , printing and tagged C , C programming , drawing , example , example program , graphics , PDF , printing , Windows Forms programming.

Bookmark the permalink. September 4, at pm. RodStephens says:. September 5, at pm. SlowMo says:. October 27, at pm. EnableVisualStyles ; Application. SetCompatibleTextRenderingDefault false ; if argv. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

About eBook formats. Expand your expertiseand teach yourself the fundamentals of programming with the latest version of Visual C with Visual Studio. If you are an experienced software developer, you'll get all the guidance, exercises, and code you need to start building responsive, scalable, cloud-connected applications that can run almost anywhere.



0コメント

  • 1000 / 1000