How to create window in c
How to create window in c
Creating a Window
Window Classes
A window class defines a set of behaviors that several windows might have in common. For example, in a group of buttons, each button has a similar behavior when the user clicks the button. Of course, buttons are not completely identical; each button displays its own text string and has its own screen coordinates. Data that is unique for each window is called instance data.
Every window must be associated with a window class, even if your program only ever creates one instance of that class. It is important to understand that a window class is not a «class» in the C++ sense. Rather, it is a data structure used internally by the operating system. Window classes are registered with the system at run time. To register a new window class, start by filling in a WNDCLASS structure:
You must set the following structure members:
Class names are local to the current process, so the name only needs to be unique within the process. However, the standard Windows controls also have classes. If you use any of those controls, you must pick class names that do not conflict with the control class names. For example, the window class for the button control is named «Button».
The WNDCLASS structure has other members not shown here. You can set them to zero, as shown in this example, or fill them in. The WNDCLASS documentation describes the structure in detail.
Next, pass the address of the WNDCLASS structure to the RegisterClass function. This function registers the window class with the operating system.
Creating the Window
To create a new instance of a window, call the CreateWindowEx function:
You can read detailed parameter descriptions in the documentation for the CreateWindowEx function, but here is a quick summary:
CreateWindowEx returns a handle to the new window, or zero if the function fails. To show the window—that is, make the window visible —pass the window handle to the ShowWindow function:
The hwnd parameter is the window handle returned by CreateWindowEx. The nCmdShow parameter can be used to minimize or maximize a window. The operating system passes this value to the program through the wWinMain function.
Here is the complete code to create the window. Remember that WindowProc is still just a forward declaration of a function.
Congratulations, you’ve created a window! Right now, the window does not contain any content or interact with the user. In a real GUI application, the window would respond to events from the user and the operating system. The next section describes how window messages provide this sort of interactivity.
Создание окна
Классы окон
Класс окна определяет набор поведений, которые могут быть общими для нескольких окон. Например, в группе кнопок каждая кнопка имеет аналогичное поведение, когда пользователь нажимает кнопку. Конечно, кнопки не полностью идентичны; каждая кнопка отображает собственную текстовую строку и имеет собственные координаты экрана. Данные, уникальные для каждого окна, называются данными экземпляра.
Каждое окно должно быть связано с классом окна, даже если программа только когда-либо создает один экземпляр этого класса. Важно понимать, что класс окна не является «классом» в смысле C++. Скорее, это структура данных, используемая внутренне операционной системой. Классы окон регистрируются в системе во время выполнения. Чтобы зарегистрировать новый класс окна, начните с заполнения структуры WNDCLASS :
Необходимо задать следующие элементы структуры:
Имена классов являются локальными для текущего процесса, поэтому имя должно быть уникальным только в процессе. Однако стандартные элементы управления Windows также имеют классы. Если вы используете любой из этих элементов управления, необходимо выбрать имена классов, которые не конфликтуют с именами классов элементов управления. Например, класс окна для элемента управления «Кнопка» называется «Button».
Структура WNDCLASS содержит другие элементы, не показанные здесь. Их можно задать равным нулю, как показано в этом примере, или заполнить их. В документации WNDCLASS подробно описывается структура.
Создание окна
Чтобы создать новый экземпляр окна, вызовите функцию CreateWindowEx :
Функция CreateWindowEx возвращает дескриптор в новое окно или ноль, если функция завершается ошибкой. Чтобы отобразить окно( то есть сделать окно видимым, передайте дескриптор окна в функцию ShowWindow :
Ниже приведен полный код для создания окна. Помните, что WindowProc это по-прежнему просто прямое объявление функции.
Поздравляем, вы создали окно! Сейчас окно не содержит содержимого или не взаимодействует с пользователем. В реальном приложении графического пользовательского интерфейса окно будет реагировать на события от пользователя и операционной системы. В следующем разделе описывается, как сообщения окна обеспечивают такой интерактивный вид.
theForger’s Win32 API Programming Tutorial
A Simple Window
Sometimes people come on IRC and ask «How do I make a window?». Well it’s not entirely that simple I’m afraid. It’s not difficult once you know what you’re doing but there are quite a few things you need to do to get a window to show up; And they’re more than can be simply explained over a chat room, or a quick note.
I always liked to do things first and learn them later. so here is the code to a simple window which will be explained shortly. For most part this is the simplest windows program you can write that actually creates a functional window, a mere 70 or so lines. If you got the first example to compile then this one should work with no problems.
Step 1: Registering the Window Class
A Window Class has NOTHING to do with C++ classes. The variable above stores the name of our window class, we will use it shortly to register our window class with the system.
We then call RegisterClassEx() and check for failure, if it fails we pop up a message which says so and abort the program by returning from the WinMain() function.
Step 2: Creating the Window
Once the class is registered, we can create a window with it. You should look up the paramters for CreateWindowEx() (as you should ALWAYS do when using a new API call), but I’ll explain them briefly here.
The first parameter ( WS_EX_CLIENTEDGE ) is the extended windows style, in this case I have set it to give it a sunken inner border around the window. Set it to 0 if you’d like to see the difference. Also play with other values to see what they do.
The parameter we have as WS_OVERLAPPEDWINDOW is the Window Style parameter. There are quite a few of these and you should look them up and experiment to find out what they do. These will be covered more later.
The next four parameters ( CW_USEDEFAULT, CW_USEDEFAULT, 320, 240 ) are the X and Y co-ordinates for the top left corner of your window, and the width and height of the window. I’ve set the X and Y values to CW_USEDEFAULT to let windows choose where on the screen to put the window. Remeber that the left of the screen is an X value of zero and it increases to the right; The top of the screen is a Y value of zero which increases towards the bottom. The units are pixels, which is the smallest unit a screen can display at a given resolution.
Number one cause of people not knowing what the heck is wrong with their programs is probably that they didn’t check the return values of their calls to see if they failed or not. CreateWindow() will fail at some point even if you’re an experianced coder, simply because there are lots of mistakes that are easy to make. Untill you learn how to quickly identify those mistakes, at least give yourself the chance of figuring out where things go wrong, and Always check return values!
After we’ve created the window and checked to make sure we have a valid handle we show the window, using the last parameter in WinMain() and then update it to ensure that it has properly redrawn itself on the screen.
The nCmdShow parameter is optional, you could simply pass in SW_SHOWNORMAL all the time and be done with it. However using the parameter passed into WinMain() gives whoever is running your program to specify whether or not they want your window to start off visible, maximized, minimized, etc. You will find options for these in the properties of windows shortcuts, and this parameter is how the choice is carried out.
Step 3: The Message Loop
This is the heart of the whole program, pretty much everything that your program does passes through this point of control.
TranslateMessage() does some additional processing on keyboard events like generating WM_CHAR messages to go along with WM_KEYDOWN messages. Finally DispatchMessage() sends the message out to the window that the message was sent to. This could be our main window or it could be another one, or a control, and in some cases a window that was created behind the scenes by the sytem or another program. This isn’t something you need to worry about because all we are concerned with is that we get the message and send it out, the system takes care of the rest making sure it gets to the proper window.
Step 4: the Window Procedure
The window procedure is called for each message, the HWND parameter is the handle of your window, the one that the message applies to. This is important since you might have two or more windows of the same class and they will use the same window procedure ( WndProc() ). The difference is that the parameter hwnd will be different depending on which window it is. For example when we get the WM_CLOSE message we destroy the window. Since we use the window handle that we received as the first paramter, any other windows will not be affected, only the one that the message was intended for.
WM_CLOSE is sent when the user presses the Close Button or types Alt-F4. This will cause the window to be destroyed by default, but I like to handle it explicitly, since this is the perfect spot to do cleanup checks, or ask the user to save files etc. before exiting the program.
Windows Programming/Window Creation
On the Windows operating system, most user-interfacable objects are known as «windows». Each window is associated with a particular class, and once the class is registered with the system, windows of that class can be created.
Contents
WNDCLASS [ edit | edit source ]
To register a windows class, you need to fill out the data fields in a WNDCLASS structure, and you need to pass this structure to the system. First, however, you need to provide your class with a name, so that Windows (the system) can identify it. It is customary to define the window class name as a global variable:
You can name it anything you want to name it, this is just an example.
After you have the class name, you can start filling out the WNDCLASS structure. WNDCLASS is defined as such:
For more information on this structure, see this Microsoft Developer’s Network article.
Notice the last data field is a pointer to a string named «lpszClassName»? This is where you point to your class name that you’ve just defined. The field named «hInstance» is where you supply the instance handle for your program. We will break the rest of the fields up into a few different categories.
The HANDLEs [ edit | edit source ]
There are a number of different data types in the WNDCLASS structure that begin with the letter «h». As we remember from our discussion of Hungarian notation, if a variable starts with an «h», the variable itself holds a HANDLE object.
HICON hIcon This is a handle to the icon that your program will use, as located in the top left, and in the taskbar. We will discuss icons more later. However, in our example below, we will use a default value for this item. HCURSOR hCursor This is a handle to the standard mouse pointer that your window will use. In our example, we will use a default value for this also. HBRUSH hbrBackground This is a handle to a brush (a brush is essentially a color) for the background of your window. Here is a list of the default colors supplied by Windows (these colors will change depending on what ‘theme’ is active on your computer):
Because of a software issue, a value of 1 must be added to any of these values to make them a valid brush.
Another value that is worth mentioning in here is the «lpszMenuName» variable. lpszMenuName points to a string that holds the name of the program menu bar. If your program does not have a menu, you may set this to NULL.
Extra Fields [ edit | edit source ]
There are 2 «extra» data members in the WNDCLASS structure that allow the programmer to specify how much additional space (in bytes) to allocate to the class (cbClsExtra) and to allocate to each specific window instance (cbWndExtra). In case you are wondering, the prefix «cb» stands for «count of bytes».
If you don’t know how to use these members, or if you don’t want to use them, you may leave both of these as 0. We will discuss these members in more detail later.
Window Fields [ edit | edit source ]
There are 2 fields in the WNDCLASS that deal specifically with how the window will operate. The first is the «style» field, which is essentially a set of bitflags that will determine some actions that the system can take on the class. These flags can be bit-wise OR’d (using the | operator) to combine more then one into the style field. The MSDN WNDCLASS documentation has more information.
The next (and arguably most important) member of the WNDCLASS is the lpfnWndProc member. This member points to a WNDPROC function that will control the window, and will handle all of the window’s messages.
Registering the WNDCLASS [ edit | edit source ]
After the fields of the WNDCLASS structure have been initialized, you need to register your class with the system. This can be done by passing a pointer to the WNDCLASS structure to the RegisterClass function. If the RegisterClass function returns a zero value, the registration has failed, and your system has failed to register a new window class.
Creating Windows [ edit | edit source ]
Windows are generally created using the «CreateWindow» function, although there are a few other functions that are useful as well. Once a WNDCLASS has been registered, you can tell the system to make a window from that class by passing the class name (remember that global string we defined?) to the CreateWindow function.
(See this MSDN article for more information.)
The first parameter, «lpClassName» is the string associated with our window class. The «lpWindowName» parameter is the title that will be displayed in the titlebar of our window (if the window has a titlebar).
«dwStyle» is a field that contains a number of bit-wise OR’d flags, that will control window creation.
Window Dimensions [ edit | edit source ]
The «x» and «y» parameters specify the coordinates of the upper-left corner of your window, on the screen. If x and y are both zero, the window will appear in the upper-left corner of your screen. «nWidth» and «nHeight» specify the width and height of your window, in pixels, respectively.
The HANDLEs [ edit | edit source ]
There are 3 HANDLE values that need to be passed to CreateWindow: hWndParent, hMenu, and hInstance. hwndParent is a handle to the parent window. If your window doesn’t have a parent, or if you don’t want your windows to be related to each other, you can set this to NULL. hMenu is a handle to a menu, and hInstance is a handle to your programs instance value.
Passing Values to the New Window [ edit | edit source ]
To pass a value to the new window, you may pass a generic, LPVOID pointer (a 32-bit value) in the lpParam value of CreateWindow. Generally, it is a better idea to pass parameters via this method than to make all your variables global. If you have more than 1 parameter to pass to the new window, you should put all of your values into a struct, and pass a pointer to that struct to the window. We will discuss this in more detail later.
An Example [ edit | edit source ]
Finally, we are going to display a simple example of this process. This program will display a simple window on the screen, but the window won’t do anything. This program is a bare-bones program, and it encompasses most of the framework necessary to make any Windows program do anything. Beyond this, it is easy to add more functionality to a program.
-EX members [ edit | edit source ]
The Win32 API gains more functionality with each generation, although Microsoft faithfully maintains the API to be almost completely backwards-compatible with older versions of windows. To add more functionally, therefore, Microsoft needed to add new functions and new structures, to make use of new features. An extended version of the WNDCLASS structure is known as the «WNDCLASSEX» structure, which has more fields, and allows for more options. To register a WNDCLASSEX structure, you must use the RegisterClassEx function instead.
Also, there is a version of the CreateWindow function with extended functionality: CreateWindowEx. To learn more about these extensions, you can do a search on MSDN.
Dialog Boxes [ edit | edit source ]
Dialog Boxes are special types of windows that get created and managed differently from other windows. To create a dialog box, we will use the CreateDialog, DialogBox, or DialogBoxParam functions. We will discuss these all later. It is possible to create a dialog box by defining a WNDCLASS and calling CreateWindow, but Windows already has all the definitions stored internally, and provides a number of easy tools to work with. For the full discussion, see: Dialog Boxes.
Default Window Classes [ edit | edit source ]
There are a number of window classes that are already defined and stored in the Windows system. These classes include things like buttons and edit boxes, that would take far too much work to define manually. Here is a list of some of the pre-made window types:
BUTTON A BUTTON window can encompass everything from a push button to a check box and a radio button. The «title» of a button window is the text that is displayed on a button. SCROLLBAR SCROLLBAR windows are slider controls that are frequently used on the edge of a larger window to control scrolling. SCROLLBAR types can also be used as slider controls. MDICLIENT This client type enables Multiple Document Interface (MDI) applications. We will discuss MDI applications in a later chapter. STATIC STATIC windows are simple text displays. STATIC windows rarely accept user input. However, a STATIC window can be modified to look like a hyperlink, if necessary. LISTBOX, COMBOBOX LISTBOX windows are drop-down list boxes, that can be populated with a number of different choices that the user can select. A COMBOBOX window is like a LISTBOX, but it can contain complex items. EDIT, RichEdit EDIT windows allow text input with a cursor. Basic EDIT windows also allow for copy+paste operations, although you need to supply the code to handle those options yourself. RichEdit controls allow for text editing and formatting. Consider an EDIT control being in Notepad.exe, and a RichEdit control being in WordPad.exe.
Menus [ edit | edit source ]
There are a number of different menus that can be included in a window or a dialog box. One of the most common (and most important) is the drop-down menu bar that is displayed across the top of a window of a dialog box. Also, many programs offer menus that appear when the mouse is right-clicked on the window. The bar across the top of the window is known as the «Menu Bar», and we will discuss that first. For some information about creating a menu in a resource script, see The Resource Script Reference Page, in the appendix to this book.
Menu Bar: From Resource Script [ edit | edit source ]
The easiest and most straightforward method to create a menu is in a resource script. Let’s say that we want to make a menu with some common headings in it: «File», «Edit», «View», and «Help». These are common menu items that most programs have, and that most users are familiar with.
We create an item in our resource script to define these menu items. We will denote our resource through a numerical identifier, «IDM_MY_MENU»:
The keyword POPUP denotes a menu that opens when you click on it. However, let’s say that we don’t want the «Help» menu item to pop up, but instead we want to click on the word «Help», and immediately open the help window. We can change it as such:
The MENUITEM designator shows that when we click on «Help», another menu won’t open, and a command will be sent to the program.
Now, we don’t want to have empty menus, so we will fill in some common commands in the «File» and «Edit» menus, using the same MENUITEM keyword as we used above:
Now, in the «View» category, we want to have yet another popup menu, that says «Toolbars». When we put the mouse on the «Toolbars» command, a submenu will open to the right, with all our selections on it:
This is reasonably easy, to start with, except that now we need to provide a method for interfacing our menu with our program. To do this, we must assign every MENUITEM with a command identifier, that we can define in a headerfile. It is customary to name these command resources with an «IDC_» prefix, followed by a short text saying what it is. For instance, for the «File > Open» command, we will use an id called «IDC_FILE_OPEN». We will define all these ID tags in a resource header script later. Here is our menu with all the ID’s in place:
When we click on one of these entries in our window, the message loop will receive a WM_COMMAND message, with the identifier in the WPARAM parameter.
We will define all our identifiers in a header file to be numerical values in an arbitrary range that does not overlap with the command identifiers of our other input sources (accelerator tables, push-buttons, etc):
And we will then include this resource header both into our main program code file, and our resource script. When we want to load a menu into our program, we need to create a handle to a menu, or an HMENU. HMENU data items are identical in size and shape to other handle types, except they are used specifically for pointing to menus.
When we start our program, usually in the WinMain function, we will obtain a handle to this menu using an HMENU data item, with the LoadMenu function:
We will discuss how to use this handle to make the menu appear in another section, below.
Menu Bar: From API Calls [ edit | edit source ]
Menu Bar: Loading a Menu [ edit | edit source ]
To associate a menu with a window class, we need to include the name of the menu into the WNDCLASS structure. Remember the WNDCLASS structure:
It has a data field called «lpszMenuName». This is where we will include the ID of our menu:
Remember, we need to use the MAKEINTRESOURCE keyword to convert the numerical identifier (IDM_MY_MENU) into an appropriate string pointer.
Next, after we have associated the menu with the window class, we need to obtain our handle to the menu:
And once we have the HMENU handle to the menu, we can supply it to our CreateWindow function, so that the menu is created when the window is created:
We pass our HMENU handle to the hMenu parameter of the CreateWindow function call. Here is a simple example:
As a quick refresher, notice that we are using default values for all the position and size attributes. We are defining the new window to be a WS_OVERLAPPEDWINDOW, which is a common, ordinary window type. Also the title bar of the window will say «Menu Test Window!». We also need to pass in the HINSTANCE parameter as well, which is the second-to-last parameter.
Walkthrough: Create a traditional Windows Desktop application (C++)
This walkthrough shows how to create a traditional Windows desktop application in Visual Studio. The example application you’ll create uses the Windows API to display «Hello, Windows desktop!» in a window. You can use the code that you develop in this walkthrough as a pattern to create other Windows desktop applications.
For the sake of brevity, some code statements are omitted in the text. The Build the code section at the end of this document shows the complete code.
Prerequisites
A computer that runs Microsoft Windows 7 or later versions. We recommend Windows 10 or later for the best development experience.
A copy of Visual Studio. For information on how to download and install Visual Studio, see Install Visual Studio. When you run the installer, make sure that the Desktop development with C++ workload is checked. Don’t worry if you didn’t install this workload when you installed Visual Studio. You can run the installer again and install it now.
An understanding of the basics of using the Visual Studio IDE. If you’ve used Windows desktop apps before, you can probably keep up. For an introduction, see Visual Studio IDE feature tour.
An understanding of enough of the fundamentals of the C++ language to follow along. Don’t worry, we don’t do anything too complicated.
Create a Windows desktop project
Follow these steps to create your first Windows desktop project. As you go, you’ll enter the code for a working Windows desktop application. To see the documentation for your preferred version of Visual Studio, use the Version selector control. It’s found at the top of the table of contents on this page.
To create a Windows desktop project in Visual Studio
From the main menu, choose File > New > Project to open the Create a New Project dialog box.
At the top of the dialog, set Language to C++, set Platform to Windows, and set Project type to Desktop.
From the filtered list of project types, choose Windows Desktop Wizard then choose Next. In the next page, enter a name for the project, for example, DesktopApp.
Choose the Create button to create the project.
The Windows Desktop Project dialog now appears. Under Application type, select Desktop application (.exe). Under Additional options, select Empty project. Choose OK to create the project.
In Solution Explorer, right-click the DesktopApp project, choose Add, and then choose New Item.
In the Add New Item dialog box, select C++ File (.cpp). In the Name box, type a name for the file, for example, HelloWindowsDesktop.cpp. Choose Add.
Visual C plus plus selected and the C plus plus File option highlighted.» data-linktype=»relative-path»>
Your project is now created and your source file is opened in the editor. To continue, skip ahead to Create the code.
To create a Windows desktop project in Visual Studio 2017
On the File menu, choose New and then choose Project.
In the New Project dialog box, in the left pane, expand Installed > Visual C++, then select Windows Desktop. In the middle pane, select Windows Desktop Wizard.
In the Name box, type a name for the project, for example, DesktopApp. Choose OK.
Visual C plus plus > Windows Desktop selected, the Windows Desktop Wizard option highlighted, and DesktopApp typed in the Name text box.» title=»Name the DesktopApp project» data-linktype=»relative-path»>
In the Windows Desktop Project dialog, under Application type, select Windows application (.exe). Under Additional options, select Empty project. Make sure Precompiled Header isn’t selected. Choose OK to create the project.
In Solution Explorer, right-click the DesktopApp project, choose Add, and then choose New Item.
In the Add New Item dialog box, select C++ File (.cpp). In the Name box, type a name for the file, for example, HelloWindowsDesktop.cpp. Choose Add.
Your project is now created and your source file is opened in the editor. To continue, skip ahead to Create the code.
To create a Windows desktop project in Visual Studio 2015
On the File menu, choose New and then choose Project.
In the New Project dialog box, in the left pane, expand Installed > Templates > Visual C++, and then select Win32. In the middle pane, select Win32 Project.
In the Name box, type a name for the project, for example, DesktopApp. Choose OK.
Templates > Visual C plus plus > Win32 selected, the Win32 Project option highlighted, and DesktopApp typed in the Name text box.» title=»Name the DesktopApp project» data-linktype=»relative-path»>
On the Overview page of the Win32 Application Wizard, choose Next.
On the Application Settings page, under Application type, select Windows application. Under Additional options, uncheck Precompiled header, then select Empty project. Choose Finish to create the project.
In Solution Explorer, right-click the DesktopApp project, choose Add, and then choose New Item.
In the Add New Item dialog box, select C++ File (.cpp). In the Name box, type a name for the file, for example, HelloWindowsDesktop.cpp. Choose Add.
Your project is now created and your source file is opened in the editor.
Create the code
Next, you’ll learn how to create the code for a Windows desktop application in Visual Studio.
To start a Windows desktop application
Just as every C application and C++ application must have a main function as its starting point, every Windows desktop application must have a WinMain function. WinMain has the following syntax.
For information about the parameters and return value of this function, see WinMain entry point.
In this function, you write code to handle messages that the application receives from Windows when events occur. For example, if a user chooses an OK button in your application, Windows will send a message to you and you can write code inside your WndProc function that does whatever work is appropriate. It’s called handling an event. You only handle the events that are relevant for your application.
For more information, see Window Procedures.
To add functionality to the WinMain function
In the WinMain function, you populate a structure of type WNDCLASSEX. The structure contains information about the window: the application icon, the background color of the window, the name to display in the title bar, among other things. Importantly, it contains a function pointer to your window procedure. The following example shows a typical WNDCLASSEX structure.
For information about the fields of the structure above, see WNDCLASSEX.
Register the WNDCLASSEX with Windows so that it knows about your window and how to send messages to it. Use the RegisterClassEx function and pass the window class structure as an argument. The _T macro is used because we use the TCHAR type.
Now you can create a window. Use the CreateWindowEx function.
At this point, the window has been created, but we still need to tell Windows to make it visible. That’s what this code does:
The displayed window doesn’t have much content because you haven’t yet implemented the WndProc function. In other words, the application isn’t yet handling the messages that Windows is now sending to it.
To handle the messages, we first add a message loop to listen for the messages that Windows sends. When the application receives a message, this loop dispatches it to your WndProc function to be handled. The message loop resembles the following code.
For more information about the structures and functions in the message loop, see MSG, GetMessage, TranslateMessage, and DispatchMessage.
At this point, the WinMain function should resemble the following code.
To add functionality to the WndProc function
To enable the WndProc function to handle the messages that the application receives, implement a switch statement.
One important message to handle is the WM_PAINT message. The application receives the WM_PAINT message when part of its displayed window must be updated. The event can occur when a user moves a window in front of your window, then moves it away again. Your application doesn’t know when these events occur. Only Windows knows, so it notifies your app with a WM_PAINT message. When the window is first displayed, all of it must be updated.
To handle a WM_PAINT message, first call BeginPaint, then handle all the logic to lay out the text, buttons, and other controls in the window, and then call EndPaint. For the application, the logic between the beginning call and the ending call displays the string «Hello, Windows desktop!» in the window. In the following code, the TextOut function is used to display the string.
HDC in the code is a handle to a device context, which is used to draw in the window’s client area. Use the BeginPaint and EndPaint functions to prepare for and complete the drawing in the client area. BeginPaint returns a handle to the display device context used for drawing in the client area; EndPaint ends the paint request and releases the device context.
An application typically handles many other messages. For example, WM_CREATE when a window is first created, and WM_DESTROY when the window is closed. The following code shows a basic but complete WndProc function.
Build the code
As promised, here’s the complete code for the working application.
To build this example
Delete any code you’ve entered in HelloWindowsDesktop.cpp in the editor. Copy this example code and then paste it into HelloWindowsDesktop.cpp:
On the Build menu, choose Build Solution. The results of the compilation should appear in the Output window in Visual Studio.
To run the application, press F5. A window that contains the text «Hello, Windows desktop!» should appear in the upper-left corner of the display.
Congratulations! You’ve completed this walkthrough and built a traditional Windows desktop application.