Home > Articles

  • Print
  • + Share This
This chapter is from the book

Building a Managed .NET Framework Application

Switching gears to the .NET Framework and building the same type of application as a managed C++ application is a bit different, as you will see. The first step is the same: Select to build a new project from the main menu, only this time select Managed C++ Application as the type and name the application HelloNET.

Notice that you don't receive any wizard to ask what settings you would like to have in your application, as you did with the MFC application. The C++ .NET applications are generated with a script that builds a basic application framework that is a console "Hello World" application. One difference between Visual C++ .NET and the other .NET languages is that there is no form editor for Visual C++ .NET to edit Windows Forms, the basis of building user interfaces in .NET. Although it may seem daunting at first having to hand-code the user interface, you'll find that working with the .NET Framework Forms classes is rather intuitive.

Tip

If you want to learn C# also, you can actually use a dummy application in C# that does provide the Windows Form editor to build your forms and then port the code into VC++ .NET. You have to know how to do the porting, but it isn't that difficult with a little practice—and it saves time on designing your forms.

The next step is to declare a class that represents the form for the application. Select Project, Add Class from the main menu. In the list of available templates in the dialog that is displayed, select the Generic C++ Class template and click the Open button. Name the class CHelloNETForm and specify the base class Form, the .NET Framework's class found in the System::Windows::Forms namespace, which provides the Windows Form functionality. You may get an error message explaining that Visual Studio .NET cannot find the Form base class. Click Yes to continue adding the class. Performing the previous steps sets up a new file and skeleton code for your class. The next steps will transform your generic class into a managed C++ .NET class.

Click the Class View tab next to the Solution Explorer tab on the right side of the IDE window. Expand the project tree and locate the Classes item and expand that also. You should now see your CHelloNETForm class. Right-click the class and select Add, Add Variable from the context menu. You will now be presented with the Add Variable dialog. Set the access to protected, the variable type to Button*, and the variable name to m_pbtnMessage. Then click Finish. Add another Button* variable named m_pbtnDone and a Label* variable named m_pstMessage.

The variables you just added are .NET Framework classes within the Forms namespace. Controls, however, need to have a container object to hold them. Add another variable of type System::ComponentModel::Container* with the name m_pComponents and the same protected access level.

Now that you've added the member variables, its time to add some member functions. Right-click the CHelloNETForm class again, but this time select Add, Add Function. Enter void as the return type, InitForm as the function name, and an access level of protected. Click Finish to close the dialog.

The last step to finish the design of the class is to add the necessary elements that are not supported by wizards within the IDE. Using Listing 3.1 as a guide, add the appropriate using statements and add the __gc keyword immediately preceding the class keyword. This indicates to the compiler that the class is managed by the .NET Framework and its memory manager.

When you are finished, you're HelloNETForm.h file should look similar to Listing 3.1.

Listing 3.1 Transforming a Generic C++ class into Managed Code

 1: #pragma once
 2:
 3: #using <mscorlib.dll>
 4:
 5: #using <System.DLL>
 6: #using <System.Drawing.DLL>
 7: #using <System.Windows.Forms.DLL>
 8:
 9: using namespace System;
10: using namespace System::Windows::Forms;
11:
12: __gc class CHelloNETForm : public Form
13: {
14: public:
15:  CHelloNETForm(void);
16:  ~CHelloNETForm(void);
17: protected:
18:  Button* m_pbtnMessage;
19:  Button* m_pbtnDone;
20:  Label*  m_pstMessage;
21:  System::ComponentModel::Container* m_pComponents;
22:  void InitForm();
23: };

Now it's time to fill in the functions you just created. Refer to Listing 3.2 as you read through this section. To begin with, try and compile your project. One thing you'll notice is that the compiler complains that NULL is undefined. One great addition to Visual C++ .NET is that when you're adding member variables to a class like we did earlier, the generated code also includes class initializers for these variables. In this case, because we declared pointers, the generated code set these variables to NULL. However, it didn't add the appropriate #include statement. To fix this problem, include the header file stdlib.h at the top of the HelloNETForm.cpp file. Your program should now compile with zero errors and zero warnings.

Begin by filling in the constructor code. Because the member variables you added are simply pointers, you need to create the objects before you can use them. Therefore, create the form control container member variable (m_pComponents) by using the C++ keyword new. The remaining line in the constructor calls the InitForm function.

In the InitForm() function, create the three controls, one by one, and set the properties appropriately. After all the controls are created, they are added to the form with the Form::Controls->Add() method. The order in which the controls are added has an effect on the tab order if the tab order isn't specified for the controls. In this case, it is specified and therefore doesn't matter.

Listing 3.2 Creating the Form

 1: #include "stdafx.h"
 2: #include "hellonetform.h"
 3: #include <stdlib.h>
 4:
 5: #using <mscorlib.dll>
 6: CHelloNETForm::CHelloNETForm(void)
 7: : m_pbtnMessage(NULL)
 8: , m_pbtnDone(NULL)
 9: , m_pstMessage(NULL)
10: , m_pComponents(NULL)
11: {
12:  m_pComponents = new System::ComponentModel::Container();
13:
14:  // Initialize the Form
15:  InitForm();
16: }
17:
18: CHelloNETForm::~CHelloNETForm()
19: {
20: }
21:
22: void CHelloNETForm::InitForm()
23: {
24:
25:  // Allocate the controls
26:  m_pbtnMessage = new Button();
27:  m_pbtnDone  = new Button();
28:  m_pstMessage = new Label();
29:
30:  SuspendLayout();
31:
32:  // Initialize all control properties
33:  //
34:  // Message Button
35:  //
36:  m_pbtnMessage->Location = System::Drawing::Point(240, 8);
37:  m_pbtnMessage->Name = "Message";
38:  m_pbtnMessage->TabIndex = 0;
39:  m_pbtnMessage->Text = "Message";
40:  m_pbtnMessage->add_Click(
41:   new System::EventHandler( this, &CHelloNETForm::OnMessageClick ) );
42:
43:  //
44:  // Done Button
45:  //
46:  m_pbtnDone->Location = System::Drawing::Point(240, 40);
47:  m_pbtnDone->Name = "Done";
48:  m_pbtnDone->TabIndex = 1;
49:  m_pbtnDone->Text = "Done";
50:  m_pbtnDone->add_Click(
51   new System::EventHandler( this, &CHelloNETForm::OnDoneClick ) );
52:  //
53:  // Message Label
54:  //
55:  m_pstMessage->Location = System::Drawing::Point(8, 8);
56:  m_pstMessage->Name = "Label";
57:  m_pstMessage->Size = System::Drawing::Size(192, 40);
58:  m_pstMessage->TabIndex = 2;
59:  m_pstMessage->Text = "";
60:
61:  // Set form properties and add controls to form
62:  //
63:  // Form1
64:  //
65:  AutoScaleBaseSize = System::Drawing::Size(5, 13);
66:  ClientSize = System::Drawing::Size(322, 87);
67:  Controls->Add( m_pstMessage );
68:  Controls->Add( m_pbtnDone );
69:  Controls->Add( m_pbtnMessage );
70:
71:  FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedDialog;
72:  Name = "HelloNET";
73:  Text = "HelloNET";
74:
75:  ResumeLayout(false);
76: }

In order for your form to respond to user events, you'll need to capture the button click events. Events that were previously handled with the MFC message map are handled quite differently in the .NET Framework. Events are handled by delegates within your class. A delegate is quite similar to a C/C++ function pointer. You assign delegates to handle object events with the following statement:

m_pbtnMessage->add_Click(
   new System::EventHandler( this, &CHelloNETForm::OnMessageClick ) );

Every time the Message button is clicked, the CHelloNETForm::OnMessageClick() method is called. In your project, you will add two event handlers to the two buttons.

Event handlers must have a specific set of parameters, much in the same way they did for MFC message map handlers. For most events, pointers to a generic Object and an EventArgs object are passed as parameters. The generic Object pointer is a pointer to the object that caused the event, whereas the EventArgs object contains information specific to the event. Following the instructions given earlier, add two member functions. The first function is named OnMessageClick, and the second function is named OnDoneClick. Both functions have a void return type, protected access level, and two parameters: Object* source and EventArgs* e. Listing 3.3 shows the final version of the HelloNETForm.h file.

Listing 3.3 Adding Event Handler Declarations

 1: #pragma once
 2:
 3: #using <mscorlib.dll>
 4:
 5: #using <System.DLL>
 6: #using <System.Drawing.DLL>
 7: #using <System.Windows.Forms.DLL>
 8:
 9: using namespace System;
10: using namespace System::Windows::Forms;
11:
12: __gc class CHelloNETForm : public Form
13: {
14: public:
15:  CHelloNETForm(void);
16:  ~CHelloNETForm(void);
17: protected:
18:  Button* m_pbtnMessage;
19:  Button* m_pbtnDone;
20:  Label*  m_pstMessage;
21:  System::ComponentModel::Container* m_pComponents;
22:  void InitForm();
23:  void OnMessageClick( Object* source, EventArgs* e);
24:  void OnDoneClick( Object* source, EventArgs* e);
25: };

Now open the HelloNETForm.cpp file. The two functions you just added will be at the bottom of the file. In OnMessageClick, set the m_pstMessage Text property to "Hello from the .NET World." For the OnDoneClick function, call the function Close, which shuts down the application. The two functions should appear similar to the following:

1: void CHelloNETForm::OnMessageClick( Object* source, EventArgs* e )
 2: {
 3:  m_pstMessage->Text = "Hello from the .NET World.";
 4: }
 5:
 6: void CHelloNETForm::OnDoneClick( Object* source, EventArgs* e )
 7: {
 8:  Close();
 9: }

The final change to the application is to have the main() function create and run the new Windows Form class. Make the changes shown in the following code segment:

#include "helloNETform.h"
int _tmain(void)
{
  Application::Run(new CHelloNETForm());
  return 0;
}

With those final additions, the application is ready to compile and run. This is the same as with the MFC application. Simply press the F5 key or select the Debug, Start menu command. The resulting Visual C++ .NET application should have the same appearance as the MFC application created earlier.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020