Academic Tutorials



English | French | Portugese | German | Italian
Home Advertise Payments Recommended Websites Interview Questions FAQs
News Source Codes E-Books Downloads Jobs Web Hosting
Chats

VC++
VC++ Introduction
VC++ What's New
VC++ Supported Platforms
Visual C++ Settings
VC++ Breaking Changes
Visual C++ Walkthroughs
Visual C++ Editions
VC++ Project Templates
Visual C++ Guided Tour
VC++ Creating Command-Line Applications
VC++ Windows Applications
VC++ Reusable Code
VC++ Porting
VC++ Unix Users
VC++ Upgrade Wizard
VC++ Migration Primer
VC++ Managed Types
VC++ Member Declarations
VC++ Conversion Operators
VC++ Interface Member
VC++ Value Types
VC++ Boxed Value
VC++ General Language
VC++ Common Programming
VC++ Database Support
VC++ MFC Database Classes
VC++ Record
VC++ Record View
VC++ OLE DB Programming

HTML Tutorials
HTML Tutorial
XHTML Tutorial
CSS Tutorial
TCP/IP Tutorial
CSS 1.0
CSS 2.0
HLML
XML Tutorials
XML Tutorial
XSL Tutorial
XSLT Tutorial
DTD Tutorial
Schema Tutorial
XForms Tutorial
XSL-FO Tutorial
XML DOM Tutorial
XLink Tutorial
XQuery Tutorial
XPath Tutorial
XPointer Tutorial
RDF Tutorial
SOAP Tutorial
WSDL Tutorial
RSS Tutorial
WAP Tutorial
Web Services Tutorial
Browser Scripting
JavaScript Tutorial
VBScript Tutorial
DHTML Tutorial
HTML DOM Tutorial
WMLScript Tutorial
E4X Tutorial
Server Scripting
ASP Tutorial
PERL Tutorial
SQL Tutorial
ADO Tutorial
CVS
Python
Apple Script
PL/SQL Tutorial
SQL Server
PHP
.NET (dotnet)
Microsoft.Net
ASP.Net
.Net Mobile
C# : C Sharp
ADO.NET
VB.NET
VC++
Multimedia
SVG Tutorial
Flash Tutorial
Media Tutorial
SMIL Tutorial
Photoshop Tutorial
Gimp Tutorial
Matlab
Gnuplot Programming
GIF Animation Tutorial
Scientific Visualization Tutorial
Graphics
Web Building
Web Browsers
Web Hosting
W3C Tutorial
Web Building
Web Quality
Web Semantic
Web Careers
Weblogic Tutorial
SEO
Web Site Hosting
Domain Name
Java Tutorials
Java Tutorial
JSP Tutorial
Servlets Tutorial
Struts Tutorial
EJB Tutorial
JMS Tutorial
JMX Tutorial
Eclipse
J2ME
JBOSS
Programming Langauges
C Tutorial
C++ Tutorial
Visual Basic Tutorial
Data Structures Using C
Cobol
Assembly Language
Mainframe
Forth Programming
Lisp Programming
Pascal
Delphi
Fortran
OOPs
Data Warehousing
CGI Programming
Emacs Tutorial
Gnome
ILU
Soft Skills
Communication Skills
Time Management
Project Management
Team Work
Leadership Skills
Corporate Communication
Negotiation Skills
Database Tutorials
Oracle
MySQL
Operating System
BSD
Symbian
Unix
Internet
IP-Masquerading
IPC
MIDI
Software Testing
Testing
Firewalls
SAP Module
ERP
ABAP
Business Warehousing
SAP Basis
Material Management
Sales & Distribution
Human Resource
Netweaver
Customer Relationship Management
Production and Planning
Networking Programming
Corba Tutorial
Networking Tutorial
Microsoft Office
Microsoft Word
Microsoft Outlook
Microsoft PowerPoint
Microsoft Publisher
Microsoft Excel
Microsoft Front Page
Microsoft InfoPath
Microsoft Access
Accounting
Financial Accounting
Managerial Accounting
Network Sites


Creating Windows Applications (C++)


Previoushome Next






Creating Windows Applications (C++)
A D V E R T I S E M E N T
Now that we've learned about the Visual Studio IDE and command-line applications, we will learn how to create Windows applications. With Visual C++, you can create Windows applications by using many different technologies, such as the Windows API (also known as the Win32 API) and the .NET Framework.

In this section, we will create two simple Windows applications by using the Win32 API and the .NET Framework. We will also create a Windows Forms Control by using the .NET Framework, and finally we will create a simple game by using DirectX.




Prerequisites

These topics assume that you understand the fundamentals of the C++ language.




In This Section
  • Creating Win32 Applications (C++)
  • Creating a Windows Forms Application By Using the .NET Framework (C++)
  • Creating a Windows Forms Control (C++)
  • Creating a Game Using DirectX (C++)
Creating Win32 Applications (C++)
The Win32 API (also known as the Windows API) is a C-based framework for creating Windows applications, and has been around since Windows 1.0. Extensive documentation for this API can be found at Windows API.

In this procedure, we create a simple Win32 application that displays "Hello, World!" to a window. The procedure steps are identical for all Win32 applications. After you complete this procedure, you can use the code that you created here as a skeleton to create any other Win32 application.




Prerequisites

This topic assumes that you understand the fundamentals of the C++ language.

For a video demonstration, see Video How to: Creating Win32 Applications (C++).

To create a new Win32 project

  1. On the File menu, click New, and then click Project....
  2. In the Project Types pane, select Win32 in the Visual C++ node, and then select Win32 Project in the Templates pane.

    Type a name for the project, such as win32app. You can accept the default location, type a location, or browse to a directory where you want to save the project.

  3. On the Win32 Application Wizard, select Next.
  4. On the Win32 Application Wizard, under Application type select Windows application. Under Additional options select Empty project. Leave the remaining options as they are. Click Finish to create the project.
  5. Add a C++ file to the project by selecting Add New Item... from the Project menu. In the Add New Item dialog box, select C++ File (.cpp). Type a name for the file, such as GT_HelloWorldWin32.cpp, and click Add.

To start a Win32 applications

  1. As you know, every C and C++ application must have a main function. This function is the starting point for the application. Similarly, in a Win32 application, every application must have a WinMain function. The syntax for WinMain is as follows:
    Copy Code
    int WINAPI WinMain(HINSTANCE hInstance,
                       HINSTANCE hPrevInstance,
                       LPSTR lpCmdLine,
                       int nCmdShow);

    For an explanation of the parameters and return value of this function, see WinMain Function.

  2. In addition to WinMain, each Win32 application must also have a second function which is usually called WndProc, which stands for window procedure. The syntax for WndProc is as follows:
    Copy Code
    LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

    The purpose of this function is to handle any messages that your application receives from the operating system. When does your application receive messages from the operating system? All the time! For example, imagine that we have created a dialog box that has an OK button. When the user clicks that button, the operating system sends our application a message, which lets us know that a user pressed this button. The WndProc function is responsible for responding to that event. In our example, the appropriate response might be to close the dialog box.

    For more information, see Window Procedures.

To add functionality to WinMain

  1. First, create inside the WinMain function a window class structure of type WNDCLASSEX. This structure contains information about your window, such as the application's icon, the background color of the window, the name to display in the title bar, the name of the window procedure function, and so on. A typical WNDCLASSEX structure follows:
    Copy Code
        WNDCLASSEX wcex;
    
        wcex.cbSize = sizeof(WNDCLASSEX);
        wcex.style          = CS_HREDRAW | CS_VREDRAW;
        wcex.lpfnWndProc    = WndProc;
        wcex.cbClsExtra     = 0;
        wcex.cbWndExtra     = 0;
        wcex.hInstance      = hInstance;
        wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
        wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
        wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
        wcex.lpszMenuName   = NULL;
        wcex.lpszClassName  = szWindowClass;
        wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

    For an explanation of the fields of this structure, see WNDCLASSEX.

  2. Now that you have created your window class, you must register it. Use the RegisterClassEx function, and pass the window class structure as an argument:
    Copy Code
        if (!RegisterClassEx(&wcex))
        {
            MessageBox(NULL,
                _T("Call to RegisterClassEx failed!"),
                _T("Win32 Guided Tour"),
                NULL);
    
            return 1;
        }
  3. Now that you have registered your class, it is time to create a window. Use the CreateWindow function as follows:
    Copy Code
    static TCHAR szWindowClass[] = _T("win32app");
    static TCHAR szTitle[] = _T("Win32 Guided Tour Application");
    // The parameters to CreateWindow explained:
    // szWindowClass: the name of the application
    // szTitle: the text that appears in the title bar
    // WS_OVERLAPPEDWINDOW: the type of window to create
    // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
    // 500, 100: initial size (width, length)
    // NULL: the parent of this window
    // NULL: this application dows not have a menu bar
    // hInstance: the first parameter from WinMain
    // NULL: not used in this application
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        500, 100,
        NULL,
        NULL,
        hInstance,
        NULL
    );
    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Win32 Guided Tour"),
            NULL);
    
        return 1;
    }

    This function returns an HWND, which is a handle to a window. For more information, see Windows Data Types.

  4. Now that we have created the window, we can display it to the screen using the following code:
    Copy Code
    // The parameters to ShowWindow explained:
    // hWnd: the value returned from CreateWindow
    // nCmdShow: the fourth parameter from WinMain
    ShowWindow(hWnd,
        nCmdShow);
    UpdateWindow(hWnd);

    So far, this window will not display much, because we have not yet implemented the WndProc function.

  5. The final step of WinMain is the message loop. The purpose of this loop is to listen for messages that the operating system sends. When the application receives a message, the message is dispatched to the WndProc function to handle it. The message loop resembles this:
    Copy Code
        MSG msg;
        while (GetMessage(&msg, NULL, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    
        return (int) msg.wParam;

    For more information about the structures and functions that is used in the message loop, see MSG, GetMessage, TranslateMessage, and DispatchMessage.

  6. The steps that you have just completed are common to most Win32 applications. At this point, your WinMain function should resemble this:
    Copy Code
    int WINAPI WinMain(HINSTANCE hInstance,
                       HINSTANCE hPrevInstance,
                       LPSTR lpCmdLine,
                       int nCmdShow)
    {
        WNDCLASSEX wcex;
    
        wcex.cbSize = sizeof(WNDCLASSEX);
        wcex.style          = CS_HREDRAW | CS_VREDRAW;
        wcex.lpfnWndProc    = WndProc;
        wcex.cbClsExtra     = 0;
        wcex.cbWndExtra     = 0;
        wcex.hInstance      = hInstance;
        wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
        wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
        wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
        wcex.lpszMenuName   = NULL;
        wcex.lpszClassName  = szWindowClass;
        wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    
        if (!RegisterClassEx(&wcex))
        {
            MessageBox(NULL,
                _T("Call to RegisterClassEx failed!"),
                _T("Win32 Guided Tour"),
                NULL);
    
            return 1;
        }
    
        hInst = hInstance; // Store instance handle in our global variable
    
        // The parameters to CreateWindow explained:
        // szWindowClass: the name of the application
        // szTitle: the text that appears in the title bar
        // WS_OVERLAPPEDWINDOW: the type of window to create
        // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
        // 500, 100: initial size (width, length)
        // NULL: the parent of this window
        // NULL: this application dows not have a menu bar
        // hInstance: the first parameter from WinMain
        // NULL: not used in this application
        HWND hWnd = CreateWindow(
            szWindowClass,
            szTitle,
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT,
            500, 100,
            NULL,
            NULL,
            hInstance,
            NULL
        );
    
        if (!hWnd)
        {
            MessageBox(NULL,
                _T("Call to CreateWindow failed!"),
                _T("Win32 Guided Tour"),
                NULL);
    
            return 1;
        }
    
        // The parameters to ShowWindow explained:
        // hWnd: the value returned from CreateWindow
        // nCmdShow: the fourth parameter from WinMain
        ShowWindow(hWnd,
            nCmdShow);
        UpdateWindow(hWnd);
    
        // Main message loop:
        MSG msg;
        while (GetMessage(&msg, NULL, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    
        return (int) msg.wParam;
    }

To add functionality to WndProc

  1. The purpose of the WndProc function is to handle messages that your application receives. You usually implement this by using a switch function.

    The first message we will handle is the WM_PAINT message. Your application receives this message when a portion of your application's window must be updated. When a window is first created, the whole window must be updated, and this message is passed to indicate this.

    The first thing that you should do when you handle a WM_PAINT message is call BeginPaint, and the last thing that you should do is call EndPaint. In between these two function calls you handle all the logic to lay out the text, buttons, and other controls for your window. For this application, we display the string "Hello, World!" inside the window. To display text, use the TextOut function, as shown here:

    Copy Code
    PAINTSTRUCT ps;
    HDC hdc;
    TCHAR greeting[] = _T("Hello, World!");
    
    switch (message)
    {
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
    
        // Here your application is laid out.
        // For this introduction, we just print out "Hello, World!"
        // in the top left corner.
        TextOut(hdc,
            5, 5,
            greeting, _tcslen(greeting));
        // End application-specific layout section.
    
        EndPaint(hWnd, &ps);
        break;
    }
  2. Your application will typically handle many other messages, such as WM_CREATE and WM_DESTROY. A simple but complete WndProc function follows:
    Copy Code
    LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
        PAINTSTRUCT ps;
        HDC hdc;
        TCHAR greeting[] = _T("Hello, World!");
    
        switch (message)
        {
        case WM_PAINT:
            hdc = BeginPaint(hWnd, &ps);
    
            // Here your application is laid out.
            // For this introduction, we just print out "Hello, World!"
            // in the top left corner.
            TextOut(hdc,
                5, 5,
                greeting, _tcslen(greeting));
            // End application specific layout section.
    
            EndPaint(hWnd, &ps);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
            break;
        }
    
        return 0;
    }



Example

Description

After you completed all the steps, your code should resemble the following. To build the application, select Build Solution from the Build menu. If your application compiles without any errors, you can run the application by pressing F5. A simple window with the text "Hello, World!" will be displayed on the screen near the upper-left corner.

Code

Copy Code
// GT_HelloWorldWin32.cpp
// compile with: /D_UNICODE /DUNICODE /DWIN32 /D_WINDOWS /c

#include 
#include 
#include 
#include 

// Global variables

// The main window class name.
static TCHAR szWindowClass[] = _T("win32app");

// The string that appears in the application's title bar.
static TCHAR szTitle[] = _T("Win32 Guided Tour Application");

HINSTANCE hInst;

// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Win32 Guided Tour"),
            NULL);

        return 1;
    }

    hInst = hInstance; // Store instance handle in our global variable

    // The parameters to CreateWindow explained:
    // szWindowClass: the name of the application
    // szTitle: the text that appears in the title bar
    // WS_OVERLAPPEDWINDOW: the type of window to create
    // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
    // 500, 100: initial size (width, length)
    // NULL: the parent of this window
    // NULL: this application dows not have a menu bar
    // hInstance: the first parameter from WinMain
    // NULL: not used in this application
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        500, 100,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Win32 Guided Tour"),
            NULL);

        return 1;
    }

    // The parameters to ShowWindow explained:
    // hWnd: the value returned from CreateWindow
    // nCmdShow: the fourth parameter from WinMain
    ShowWindow(hWnd,
        nCmdShow);
    UpdateWindow(hWnd);

    // Main message loop:
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int) msg.wParam;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;
    TCHAR greeting[] = _T("Hello, World!");

    switch (message)
    {
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);

        // Here your application is laid out.
        // For this introduction, we just print out "Hello, World!"
        // in the top left corner.
        TextOut(hdc,
            5, 5,
            greeting, _tcslen(greeting));
        // End application-specific layout section.

        EndPaint(hWnd, &ps);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }

    return 0;
}
Creating a Windows Forms Application By Using the .NET Framework (C++)
In .NET development, a Windows GUI application is called a Windows Forms (or Winforms) application. Developing a Windows Forms project with Visual C++ is generally the same as with any other .NET language, such as Visual Basic or C#.

Windows Forms applications in Visual C++ use the .NET Framework classes and other .NET features with the new Visual C++ syntax. For more information, see Language Features for Targeting the CLR.

In this procedure, you create a Windows Forms application by using several standard controls from the Toolbox. In the finished application, a user can select a date, and a text label shows the date that the user chose.




Prerequisites

This topic assumes that you understand the fundamentals of the C++ language.

For a video demonstration, see Video How to: Creating a Windows Forms Application By Using the .NET Framework (C++).

To create a new Windows Forms project

  1. On the File menu, click New, and then click Project….
  2. In the Project Types pane, select CLR in the Visual C++ node, and then select Windows Forms Application in the Templates pane.

    Type a name for the project, such as winformsapp. You can accept the default location, type a location, or browse to a directory where you want to save the project.

  3. The Windows Forms Designer opens, displaying Form1 of the project that you created, as shown here:

To add controls to a form

  1. If you cannot see the Toolbox window, click Toolbox on the View menu.
  2. Place three controls from the Toolbox on the Form1 design surface:
    1. Drag a Label control to near the top-left corner of Form1.
    2. Drag a DateTimePicker control just under the Label control.
    3. Drag a Button control to the bottom of the form near the center.

    Your form should resemble this:

To set properties of forms and controls

  1. Select the form by clicking an empty area on its surface.
  2. If you cannot see the Properties window, click Properties on the View menu (or press F4).

    You may want to close the Toolbox for more room.

  3. Set the form's Text property (shown in the form Title Bar) by clicking to the right of the Text property in the Properties Window and typing:

    Date Chooser

  4. Select the label by clicking it and set its Text property to

    Choose a date:.

  5. Select the button by clicking it and set its Text property to

    OK.

    The form should resemble this:




Writing Event Handler Code

In this section, you write the code to run when these events occur:

  • A Click event on the Button control.
  • A ValueChanged event on the DateTimePicker control.

To write code to handle events

  1. Double-click the button to add a button click event handler (the default event for a button is a Click event).

    This action generates an empty event handler method in the code view of the form displayed in a tabbed page in the editing area.

  2. Move the cursor to after the opening brace of the button1_Click method, press Enter, and type the following code to run when that event occurs:

    Application::Exit();

    IntelliSense displays a list of valid possible choices after you type the scope resolution operator (::). You can select a choice from the list and press Tab, double-click it, or continue typing.

  3. Return to the Design view by clicking the Form1.h [Design] tab in the editing area or on the View menu, and click Designer.
  4. Click the DateTimePicker control.
  5. To add a ValueChanged event handler for the DateTimePicker control, click the lightning bolt icon in the Properties window to display events for that control.
  6. Double-click the ValueChanged event to generate an empty event handler in the Code view.
    Note:
    ValueChanged is the default event for the DateTimePicker control. Therefore you could also double-click the DateTimePicker control to generate an empty event handler.
  7. Move the cursor to after the opening brace of the dateTimePicker1_ValueChanged method, press Enter, and then type the following code to run when the event occurs:

    label1->Text=String::Format("New date: {0}", dateTimePicker1->Text);

    When a user of the application selects a new date, the Text property of the label is set to the literal string "New date:" with the Text property of the DateTimePicker appended to that string.

    Visual Studio provides several features that simplify typing code:

    • When you type an arrow operator (->), IntelliSense displays valid choices that you can select from the list.
    • When you type an opening parenthesis for a method, a tooltip window shows valid arguments for each overload of that method. To view the different overloads, use the UP or DOWN arrow keys.
    • Auto-completion can finish typing a variable name or member from what you have typed. For example, if you type String::Fo and press Ctrl-Spacebar or Tab, Visual Studio will complete typing String::Format for you.

To build and run the program

  1. From the Build menu, click Build Solution.

    If there are any errors, click the Go to Next Message button in the Output window. The error message text appears in the status bar. You can double-click any error to go to the line with that error in the source code.

  2. From the Debug menu, click Run without Debugging. The application that you built is displayed.
  3. Test the application by clicking the down arrow on the DateTimePicker and selecting a date. The label text changes to show the date that you selected, as shown here:

  4. You can add more features to this application, such as menus, other forms, and Help files. Do not be afraid to experiment.
Creating a Windows Forms Control (C++)
Windows Forms controls are components that can be added to Windows Forms applications (GUI applications that target the common language runtime). Windows Forms applications in Visual C++ use .NET Framework classes and other .NET features with the new Visual C++ syntax.

In this procedure, you create a Windows Forms control that displays a number. This number increments each time that a user clicks the label in an application. You will also create a Windows Forms application project to test the control.

This walkthrough covers the following:

  • Creating a New Project.
  • Designing the Control.
  • Adding a Custom Property to the Control.
  • Adding a Project to Test the Control.
  • Placing the Control in an Application.
  • Running the Application.



Prerequisites

This topic assumes that you understand the fundamentals of the C++ language.

For a video demonstration, see Video How to: Creating a Windows Forms Control (C++).




Create a New Project

The Windows Forms Control project template that you use in this section creates a user control, which is a composite control that contains other controls.

Alternatively, you can create a Windows Forms control by deriving a class directly from the Control class (your code is responsible for drawing the control) or the Component class (a control that has no UI).

To create a new Windows Forms control project

  1. From the File menu, click New, and then click Project….
  2. On the Project Types pane, select CLR in the Visual C++ node, and then select Windows Forms Control Library in the Visual Studio installed templates pane.

    Type a name for the project, such as clickcounter.

    Type a different name for the solution, such as controlandtestapp.

    You can accept the default location, type a location that you want, or browse to a directory where you want to save the project.

  3. The Windows Forms Designer opens and shows an area where you add the controls that you want to position on the control design surface.



Design the Control

In this step, you add a Label control to the control design surface. You then set some properties on the control itself and on the Label control it contains.

To set the properties of a user control

  1. If you cannot see the Properties window, from the View menu, click Properties Window.

    Click on the control to select it and set its properties as follows:

    • Set the Size property to 100, 100.
    • Set the BorderStyle to Fixed3D

      The label boundaries will be visible after you position the control in an application.

  2. If the Toolbox window is not visible, select Toolbox from the View menu.

    Drag a Label control from the Toolbox to the design surface and position it near the middle of the control.

    Set these properties for the label:

    • Set the BorderStyle to FixedSingle.
    • Set the Text to the digit 0 (zero).
    • Set the Autosize to False.
    • Set the Size to 30, 20.
    • Set the TextAlign to MiddleCenter.

    Leave the Name property (how you refer to it in code) unchanged as label1. The control should resemble the following:

  3. Add an event handler for the label Click event (the default event for a label) by double-clicking the label.
  4. The clickcounter.hfile is displayed in the editing area with an empty event handler method.
    Note:
    If you need more room, close the Toolbox or Properties window by clicking the appropriate Close box or by unpinning the window so that it auto-hides.
  5. Move the cursor to after the opening brace of the label1_Click method, press Enter, and type:
    Copy Code
    int temp = System::Int32::Parse(label1->Text);
    temp++;
    label1->Text = temp.ToString();

    IntelliSense displays a list of valid choices after you type a scope resolution operator (::), dot operator (.) or arrow operator (->). You can highlight an item and press Tab or Enter or double-click an item to insert that item into your code.

    Also, when you type an opening parenthesis for a method, Visual Studio displays valid argument types for each overload of the method.




Add a Custom Property to the Control

In this step, you define a custom property that determines whether the number that is displayed on the control increments when a user clicks the label or when a user clicks any location on the control.

To add a custom property to a control

  1. Place the cursor after the colon of the first public scope indicator at the top of the clickcounterControl.h file, press Enter, and then type the following:
    Copy Code
    property bool ClickAnywhere {
        bool get() {
            return (label1->Dock == DockStyle::Fill);
        }
        void set(bool val) {
            if (val) 
                label1->Dock = DockStyle::Fill;
            else 
                label1->Dock = DockStyle::None;
        }
    }

    When you set the ClickAnywhere property of the control to true, the Dock property of the label is set to DockStyle::Fill, and the label fills the whole control surface. A click anywhere on the control surface will then cause a label Click event, which increments the number on the label.

    When the ClickAnywhere property is false (the default), the Dock property of the label is set to DockStyle::None. The label does not fill the control, and a click on the control must be inside the label boundaries to cause a label Click event, which increments the number.

  2. Build the user control. On the Build menu, select Build Solution.

    If there are no errors, a Windows Forms control is generated with a file name of clickcounter.dll. You can locate this file in your project directory structure.




Add a Project to Test the Control

In this step, you create a Windows Forms application project in which you will position instances of the clickcounter control on a form.

Note:
You can write the Windows Forms application that you create to test the control with Visual C++ or another .NET language, such as C# or Visual Basic.

To create a Windows Forms application project

  • From the File menu, select New, and then click Project….

You can also add a project to the solution byright-clicking the controlandtestapp solutionin Solution Explorer, pointing to Add, andthen clicking New Project….

  1. In the Project Types pane, select CLR in the Visual C++ node, and then select Windows Forms Application in the Visual Studio installed templates pane.

    Type a name for the project, such as testapp.

    Be sure to select Add to Solution instead of accepting the default Create New Solution setting in the Solution drop-down list, and then click OK.

  2. The Windows Forms Designer for the new project opens, and shows a new form named Form1 as in this figure:

To add a control to the Toolbox

  1. Add a reference to the control. From the Project menu, select References or right-click the testapp project in Solution Explorer and click References.

    Click the Add New Reference button, click the Projects tab (you are adding a reference to another project in this solution), and then select the clickcounter project. Click OK two times.

  2. If you cannot see the Toolbox window, select Toolbox from the View menu.
  3. Right-click the Toolbox and click Choose Items.

    Click the Browse button and locate the clickcounter.dll file in your solution directory structure. Select it and click Open.

    The clickcounter control is shown in the.NET Framework Components list with a check mark. Click OK.

    The control appears in the Toolbox with the default "gear" icon.




Place the Control in an Application

In this step, you put two instances of the control on an application form and set their properties.

To put instances of a control on a form

  1. Drag two instances of the clickcounter control from the Toolbox. Place them on the form so that they do not overlap.

    If you want to make the form wider, click the form to select it and drag one of the selection handles outward.

  2. If you cannot see the Properties window, select Properties from the View menu.

    The ClickAnywhere property is in the Misc. section of the Property Window (if properties are organized by category).

  3. Click one instance of the clickcounter control on the form to select it, and then set its ClickAnywhere property to true.
  4. Leave the ClickAnywhere property of the other instance of the clickcounter control set to false (the default).
  5. Right-click the testapp project in Solution Explorer and select Set As StartUp Project.
  6. From the Build menu, select Rebuild Solution.

    You should see that the two projects built without errors.




Run the Application

In this step, you run the application, and click the controls to test them.

To test the application

  1. From the Debug menu, select Start Debugging.

    The form appears with the two instances of the control visible.

  2. Run the application and click both clickcounter controls:
    • Click the control with ClickAnywhere set to true.

      The number on the labelincrements when you click anywhere on the control.

    • Click the control with ClickAnywhere set to false.

      The number on the label increments only when you click within the visible boundary of the label. The following screenshot shows how the application might look after clicking on it a few times:

  1. Close the test application by clicking its Close box in the upper-right corner of the Form1 window.
Creating a Game Using DirectX (C++)
C++ is an excellent language for creating games because of its power and flexibility. By using Visual C++ and DirectX, you can write games in either native or managed code. This flexibility allows you to create your game on the platform that you are most comfortable with.

Creating a good game is a challenge that is outside the scope of this guided tour. If you are up to the challenge, check out the following links for information that will help you create your first game.




Prerequisites

This topic assumes that you understand the fundamentals of the C++ language.

Getting started with games programming

  1. To create games by using DirectX, you must install the DirectX SDK from the DirectX Developer Center. After you have installed the SDK, you will find several samples that will help you get started with DirectX programming.
  2. Check out the Visual C++ Express Edition Web page at MSDN for existing games that you can download, study, and modify however you want. From there, you can download games from Microsoft Research and you can even download the complete source to the popular game Quake II .NET.


Be the first one to comment on this page.




  VC++ eBooks

No eBooks on VC++ could be found as of now.

 
 VC++ FAQs
More Links » »
 
 VC++ Interview Questions
More Links » »
 
 VC++ Articles
More Links » »
 
 VC++ News
More Links » »
 
 VC++ Jobs
More Links » »

Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • co.mments
  • connotea
  • del.icio.us
  • De.lirio.us
  • digg
  • Fark
  • feedmelinks
  • Furl
  • LinkaGoGo
  • Ma.gnolia
  • NewsVine
  • Netvouz
  • RawSugar
  • Reddit
  • scuttle
  • Shadows
  • Simpy
  • Smarking
  • Spurl
  • TailRank
  • Wists
  • YahooMyWeb

Previoushome Next

Keywords: bsd programming language, bsd language programming tutorial pdf, history of bsd programming, basic bsd programming, bsd band satellite programming, syntax use in bsd programming, bsd programming software download, turbo bsd programming, bsd programming code, learn bsd programming

HTML Quizzes
HTML Quiz
XHTML Quiz
CSS Quiz
TCP/IP Quiz
CSS 1.0 Quiz
CSS 2.0 Quiz
HLML Quiz
XML Quizzes
XML Quiz
XSL Quiz
XSLT Quiz
DTD Quiz
Schema Quiz
XForms Quiz
XSL-FO Quiz
XML DOM Quiz
XLink Quiz
XQuery Quiz
XPath Quiz
XPointer Quiz
RDF Quiz
SOAP Quiz
WSDL Quiz
RSS Quiz
WAP Quiz
Web Services Quiz
Browser Scripting Quizzes
JavaScript Quiz
VBScript Quiz
DHTML Quiz
HTML DOM Quiz
WMLScript Quiz
E4X Quiz
Server Scripting Quizzes
ASP Quiz
PERL Quiz
SQL Quiz
ADO Quiz
CVS Quiz
Python Quiz
Apple Script Quiz
PL/SQL Quiz
SQL Server Quiz
PHP Quiz
.NET (dotnet) Quizzes
Microsoft.Net Quiz
ASP.Net Quiz
.Net Mobile Quiz
C# : C Sharp Quiz
ADO.NET Quiz
VB.NET Quiz
VC++ Quiz
Multimedia Quizzes
SVG Quiz
Flash Quiz
Media Quiz
SMIL Quiz
Photoshop Quiz
Gimp Quiz
Matlab Quiz
Gnuplot Programming Quiz
GIF Animation Quiz
Scientific Visualization Quiz
Graphics Quiz
Web Building Quizzes
Web Browsers Quiz
Web Hosting Quiz
W3C Quiz
Web Building Quiz
Web Quality Quiz
Web Semantic Quiz
Web Careers Quiz
Weblogic Quiz
SEO Quiz
Web Site Hosting Quiz
Domain Name Quiz
Java Quizzes
Java Quiz
JSP Quiz
Servlets Quiz
Struts Quiz
EJB Quiz
JMS Quiz
JMX Quiz
Eclipse Quiz
J2ME Quiz
JBOSS Quiz
Programming Langauges Quizzes
C Quiz
C++ Quiz
Visual Basic Quiz
Data Structures Using C Quiz
Cobol Quiz
Assembly Language Quiz
Mainframe Quiz
Forth Programming Quiz
Lisp Programming Quiz
Pascal Quiz
Delphi Quiz
Fortran Quiz
OOPs Quiz
Data Warehousing Quiz
CGI Programming Quiz
Emacs Quiz
Gnome Quiz
ILU Quiz
Soft Skills Quizzes
Communication Skills Quiz
Time Management Quiz
Project Management Quiz
Team Work Quiz
Leadership Skills Quiz
Corporate Communication Quiz
Negotiation Skills Quiz
Database Quizzes
Oracle Quiz
MySQL Quiz
Operating System Quizzes
BSD Quiz
Symbian Quiz
Unix Quiz
Internet Quiz
IP-Masquerading Quiz
IPC Quiz
MIDI Quiz
Software Testing Quizzes
Testing Quiz
Firewalls Quiz
SAP Module Quizzes
ERP Quiz
ABAP Quiz
Business Warehousing Quiz
SAP Basis Quiz
Material Management Quiz
Sales & Distribution Quiz
Human Resource Quiz
Netweaver Quiz
Customer Relationship Management Quiz
Production and Planning Quiz
Networking Programming Quizzes
Corba Quiz
Networking Quiz
Microsoft Office Quizzes
Microsoft Word Quiz
Microsoft Outlook Quiz
Microsoft PowerPoint Quiz
Microsoft Publisher Quiz
Microsoft Excel Quiz
Microsoft Front Page Quiz
Microsoft InfoPath Quiz
Microsoft Access Quiz
Accounting Quizzes
Financial Accounting Quiz
Managerial Accounting Quiz
Testimonials | Contact Us | Link to Us | Site Map
Copyright ? 2008. Academic Tutorials.com. All rights reserved Privacy Policies | About Us
Our Portals : Academic Tutorials | Best eBooksworld | Beyond Stats | City Details | Interview Questions | Discussions World | Excellent Mobiles | Free Bangalore | Give Me The Code | Gog Logo | Indian Free Ads | Jobs Assist | New Interview Questions | One Stop FAQs | One Stop GATE | One Stop GRE | One Stop IAS | One Stop MBA | One Stop SAP | One Stop Testing | Webhosting in India | Dedicated Server in India | Sirf Dosti | Source Codes World | Tasty Food | Tech Archive | Testing Interview Questions | Tests World | The Galz | Top Masala | Vyom | Vyom eBooks | Vyom International | Vyom Links | Vyoms | Vyom World | Important Websites
Copyright ? 2003-2024 Vyom Technosoft Pvt. Ltd., All Rights Reserved.