
上QQ阅读APP看书,第一时间看更新
How to do it...
- Open Visual Studio 2017.
- Now open the solution from the previous recipe. Click File | Open | Project/Solution, or press Ctrl + Shift + O, and select the Chapter1.Library solution.
- Now click on the Chapter1.Library solution label. Click File | Add | New Project....
- In the Add New Project template dialog box, expand the Visual C# node in the left-hand pane.
- Select Windows Classic Desktop and select Windows Forms App (.NET Framework) in the right template pane:

- Now, in the Name: textbox, type a name for the new project. Let's type Chapter1.Library.HelloWindowsForms and leave the Location: textbox as it is and the defaults as well. Click OK to create the new project.

- The new project will be added to the Solution Explorer and it should look like this:

- Now let's do some cleaning of the names. Change Form1.cs to MainForm.cs. Remember, giving a meaningful name to your files is very important and a very good practice.
- Select the Form in the MainForm [Design] tab and go to the Properties window (or press F4). Now change the Text property to Hello World.
- Let's add some UI components to the form. Go to the tool box window (or press Ctrl + Alt + X ) and drag and drop a Label, a TextBox, and a Button to the form. Arrange them as per the following screenshot:

- Let's change some properties of the components we just dropped on the form. Go to the Properties window and change the defaults to the following:

After the changes, the Windows form designer should look like this:

- Let's add our library to the Windows Forms project. To do this, expand References under the Chaper1.Library.HelloWindowsForms project. Right-click on the References label and select Add Reference....
- Under the Reference Manager dialog box, click on the Projects label in the left-hand pane. In the middle pane, check the Chapter1.Library.HelloLib project:

- Click OK.
- Now double-click on the Say Hello button to open the code window.
- In the code window, scroll to the top and type the following code, at the end of the very last line of using directive:
using Chapter1.Library.HelloLib;
- Now scroll down to the HelloButton_Click method. In between the curly brackets, type the following code:
var helloMessage = new HelloWorld();
var yourName = NameTextBox.Text;
MessageBox.Show(helloMessage.SayHello(yourName));
- Time to test our classic Windows application with the class library created in the previous recipe. Hit F5 to debug the code. Now you should see the Windows form created.
- Type your name in the text box and hit the Say Hello button. A message box will appear with a message from the class library:

- Congratulations!!! You have just used a class library from a classic Windows application.