INTRODUCTION
Hi all. At this time we will learn some Windows programming under C + + using the Win32 API.
This is a very little treated, so the documentation that exists in Spanish is very limited, and most are limited only to explain in a very abstract, so we can get a bit lost in trying to understand.
Before we start I must warn you needed an intermediate knowledge of C / C + + to understand 100%. Why? Simply because even though we see large numbers of lines and some rare and unknown words, it is still C + + language in no time. And follows the same structure as a console mode program, with minor differences that we will see throughout this tutorial.
Windows API
An API (Application Programming Interface) is a set of functions, libraries, methods and instructions, which provides a program to program on it. This time, the Windows operating system, like any good OS, you need to offer your developers all the necessary functions in order to make life easier when programming the software.Clear examples of the Windows API are events such as windows (close, minimize, maximize, restore), are functions that are already scheduled and the developer is only responsible for handling them.
WINDOWS PROGRAMMING BASICS
Elements of a Window
One of the most important of all Windows programs is that they are formed by windows (hence the name Windows). But not many know is that all program elements are windows, a command button is a window, a text box is also a window, a tag also, finally, all we see is made up of windows . Consider the basic elements of a program:
In the title bar can be seen, apart from the title of the application, its icon identification and preset buttons minimize, maximize / restore and close, which is implied by the window border.
Software Windows and OS
When you write a Windows program, it happens to be 'controlled' by the operating system. That is, our program does not deal directly with the hardware, and everything that makes the first pass program for the Windows kernel, and it will decide what to do.
To understand more easily, there are two ways to program for an operating system: User Mode and Kernel Mode. In the second mode is where you have access to hardware, which is write drivers for different devices to work properly.Programming in this way is a bit more complicated, since it also requires knowledge of languages and know the lowest level hardware structure in detail. The errors committed in this way can not manage the operating system, and sometimes have to stop everything and cause an exception to avoid damaging the computer, in the case of Windows, a blue screen shut down the system giving details of the error .
For this reason, there is a user-mode or protected mode, here as I mentioned before, is the operating system makes the decisions, and we'll schedule that is what we do. When an error occurs, the system simply informs us and close the conflicting program.
Windows and Events
Programming in Windows follows the methodology of event-driven programming, this means that when running a program, it waits for some event to occur and be able to decide what to do. Most of the source code of a Windows program is focused on processing these events, which can be triggered by the user, for the same program or by a third program.
Posts
A Windows event occurs for example, left clicking the mouse, pressing a certain key, or when a counter reaches zero. Windows records every event in a message, which is stored in a message queue to be processed by the function of our program will do it. A Windows message is like calling every event or action taken and has to be processed by the program, ie, when an message, the program executes the code associated with that message, and then returns control to the operating system, but the program remains active waiting for more messages, and will not end until you receive the message that needs to close.
WindowsProc function ()
Every Windows program, you need a specific function which will process the messages. This function is commonly called WindowsProc () and WndProc (), but does not require a specific name, and assigned through a pointer when it creates and registers the window, but you should follow the standard to identify this function quickly For a very comprehensive program.
Fortunately, there is no need to write code for all messages that can occur only for those actually going to need, ie if we do not need right here, it is necessary to handle the message, all messages are processed at the unfiltered end without running any code of conduct action.
Windows Data Types
To give us a little more programming, Windows defines some special data types used specifically for the API, these are:
The only words that may seem new in this table would be: driver and instance.
As mentioned in the table, a handle (handle) is not more than one in 32-bit integer. What is it used? To identify an object of all who reside in memory, ie, has been a unique number that distinguishes one object from another. These are assigned by the operating system for each new object created in memory.
For example, running the Windows calculator, the program opens and draw a window with many buttons and a label to display the digits. There, the main window of the calculator has its own handle, each also has his button and the label.This helps, for example, when programming, knowing that sent a message window, or to know which object or window, the system will return a result. We will see later with an example that it is clear the concept and utility managers.
What is an instance, we will see later in this example, but can be summarized as a program running and in memory. For example to open a program and view your screen, you have your instance, and left up to us whether they can create as many instances of the same program or just one at a time.
Standard notation in Windows programs.
In order to adjust to a good programming practice, you should use prefixes when creating variables, Microsoft recommends using Hungarian notation for the development of Windows programs, is a simple variable declaration, which consists of using a prefix followed by the name of the variable, highly recommended that is related to the use that you give it to the variable. This will make it easier to change the program in the future and a better understanding of the code for third party developers.
So we can easily create variable names, in order to identify
HANDLE hInstance;
DwIntensidad DWORD; [/ PHP]
STRUCTURE OF A WINDOWS PROGRAM
To write the smallest program based on the Windows API, you need two main functions:
Hi all. At this time we will learn some Windows programming under C + + using the Win32 API.
This is a very little treated, so the documentation that exists in Spanish is very limited, and most are limited only to explain in a very abstract, so we can get a bit lost in trying to understand.
Before we start I must warn you needed an intermediate knowledge of C / C + + to understand 100%. Why? Simply because even though we see large numbers of lines and some rare and unknown words, it is still C + + language in no time. And follows the same structure as a console mode program, with minor differences that we will see throughout this tutorial.
Windows API
An API (Application Programming Interface) is a set of functions, libraries, methods and instructions, which provides a program to program on it. This time, the Windows operating system, like any good OS, you need to offer your developers all the necessary functions in order to make life easier when programming the software.Clear examples of the Windows API are events such as windows (close, minimize, maximize, restore), are functions that are already scheduled and the developer is only responsible for handling them.
WINDOWS PROGRAMMING BASICS
Elements of a Window
One of the most important of all Windows programs is that they are formed by windows (hence the name Windows). But not many know is that all program elements are windows, a command button is a window, a text box is also a window, a tag also, finally, all we see is made up of windows . Consider the basic elements of a program:
In the title bar can be seen, apart from the title of the application, its icon identification and preset buttons minimize, maximize / restore and close, which is implied by the window border.
Software Windows and OS
When you write a Windows program, it happens to be 'controlled' by the operating system. That is, our program does not deal directly with the hardware, and everything that makes the first pass program for the Windows kernel, and it will decide what to do.
To understand more easily, there are two ways to program for an operating system: User Mode and Kernel Mode. In the second mode is where you have access to hardware, which is write drivers for different devices to work properly.Programming in this way is a bit more complicated, since it also requires knowledge of languages and know the lowest level hardware structure in detail. The errors committed in this way can not manage the operating system, and sometimes have to stop everything and cause an exception to avoid damaging the computer, in the case of Windows, a blue screen shut down the system giving details of the error .
For this reason, there is a user-mode or protected mode, here as I mentioned before, is the operating system makes the decisions, and we'll schedule that is what we do. When an error occurs, the system simply informs us and close the conflicting program.
Windows and Events
Programming in Windows follows the methodology of event-driven programming, this means that when running a program, it waits for some event to occur and be able to decide what to do. Most of the source code of a Windows program is focused on processing these events, which can be triggered by the user, for the same program or by a third program.
Posts
A Windows event occurs for example, left clicking the mouse, pressing a certain key, or when a counter reaches zero. Windows records every event in a message, which is stored in a message queue to be processed by the function of our program will do it. A Windows message is like calling every event or action taken and has to be processed by the program, ie, when an message, the program executes the code associated with that message, and then returns control to the operating system, but the program remains active waiting for more messages, and will not end until you receive the message that needs to close.
WindowsProc function ()
Every Windows program, you need a specific function which will process the messages. This function is commonly called WindowsProc () and WndProc (), but does not require a specific name, and assigned through a pointer when it creates and registers the window, but you should follow the standard to identify this function quickly For a very comprehensive program.
Fortunately, there is no need to write code for all messages that can occur only for those actually going to need, ie if we do not need right here, it is necessary to handle the message, all messages are processed at the unfiltered end without running any code of conduct action.
Windows Data Types
To give us a little more programming, Windows defines some special data types used specifically for the API, these are:
The only words that may seem new in this table would be: driver and instance.
As mentioned in the table, a handle (handle) is not more than one in 32-bit integer. What is it used? To identify an object of all who reside in memory, ie, has been a unique number that distinguishes one object from another. These are assigned by the operating system for each new object created in memory.
For example, running the Windows calculator, the program opens and draw a window with many buttons and a label to display the digits. There, the main window of the calculator has its own handle, each also has his button and the label.This helps, for example, when programming, knowing that sent a message window, or to know which object or window, the system will return a result. We will see later with an example that it is clear the concept and utility managers.
What is an instance, we will see later in this example, but can be summarized as a program running and in memory. For example to open a program and view your screen, you have your instance, and left up to us whether they can create as many instances of the same program or just one at a time.
Standard notation in Windows programs.
In order to adjust to a good programming practice, you should use prefixes when creating variables, Microsoft recommends using Hungarian notation for the development of Windows programs, is a simple variable declaration, which consists of using a prefix followed by the name of the variable, highly recommended that is related to the use that you give it to the variable. This will make it easier to change the program in the future and a better understanding of the code for third party developers.
So we can easily create variable names, in order to identify
HANDLE hInstance;
DwIntensidad DWORD; [/ PHP]
STRUCTURE OF A WINDOWS PROGRAM
To write the smallest program based on the Windows API, you need two main functions:
- WinMain () function begins main program which is the equivalent of main () in console mode programs. It is worth mentioning that the function must be called exactly that and can not bear another name, so if we are free to change the name of its parameters (but not their types).
- WindowsProc () function responsible for processing the messages, your name can be changed, but not recommended for easy identification. Depending on the messages, could become the biggest feature of the program.
The interesting thing is that despite the fact that with only these two functions can execute a program, they are not connected, ie, WinMain () call WindowsProc not send(). What really happens is that the create a window in WinMain (), one of the parameters of the function that creates it is to choose the function responsible for processing messages. Then the operating system is responsible for calling the function WindowsProc send () when necessary, one less worry ^ _ ^
Well, once you clear this, it's time to write the code and start practicing what they learned. But only one more thing ... as the compiler knows the new data types, and these function names are not in the standard ... Answer: windows.h
In the windows.h header file, other headers are declared important to run windows based programs, for example: winbase.h, winuser.h, wingdi.h, winerror.h among others, I have yet is necessary to know thoroughly. But that contain functions and WinMain () GetMessage () TranslateMessage () DispatchMessage () as I mentioned are indispensable to write our program.
Our first program WINDOWS
Now if, to implement what they learned. In theory we can use any compiler to generate 32-bit executables for Windows.But for convenience and easy to use the IDE Code:: Blocks , which incorporates the MinGW compiler, more than enough for this example.
This IDE has an assistant, who with a few clicks you can easily create a Win32 project, but as we will practice what you learn, the only way to learn is by doing it from 0. So we started. - Open code:: blocks
- We will create a new file from the menu File / New / File ...
- We chose C / C + + Source (File Source C / C + +) and then click Go ..
- In this case it is indifferent to choose C or C + +, but for compatibility with future changes and better support to the chosen standard C + +, click on next.
- Finally write a file name and select the save path, we will not add the file to a project as it will be the only source. Click Finish to finish the wizard and show us our area of work:
Typical WinMain function.
The WinMain function, unlike the main (), necessarily require four parameters, it is usually stated as follows:
Code
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
}
{
}
The WINAPI macro indicates that it is a windows function, this makes it somewhat special, and that's when the compiler realizes that we are generating an executable specifically for Windows GUI.
- hInstance is a handle to the instance of the program we are running. Each time you run an application, Windows creates an instance for it, and passes a handle to that instance to the application.
- hPrevInstance is a handle to previous instance of the same application. Because Windows is multitasking, there are various versions of the same application running several instances. In Windows 3.1, this parameter helped us to know if our application is already running, and so they could share common data to all instances.But that was before because in Win32 uses a separate segment for each instance and this parameter is always NULL, is only kept for compatibility reasons.
- lpCmdLine, this string contains the input arguments to the command line.
- nCmdShow, this parameter specifies how to display the window. For possible values see nCmdShow values. We recommend against using this parameter in the function ShowWindow the first time it is called.Instead SW_SHOWDEFAULT value should be used.
As I mentioned before, we can change the names of the parameters, but not the types, it is still preferable to leave it as is, and that's what I do.
The WinMain () function needs to do 4 things: - Specify to the operating system what kind of window is required
- Creating the window
- Initialize the window
- Manage messages (prepared WindowsProc message queue () will be processed and sent as they occur is waiting for a result)
STEP 1
The first step in creating a window, is to define and specify the type of window you need. This is simple. To do this, Windows defines a special type of structure (struct) called WNDCLASSEXcontains all the information to specify the parameters of a window, which from now on we will call window class (not to be confused with a class of C + +).
So we need to do is create a variable of typeWNDCLASSEX, and assign values to each of its members (like we're setting the properties of a form). After the allocation of values, we have to pass the operating system through a function that we will see, a Registrar's called a class. By the time it is registered, Windows can handle and we can assign to a window that will create in the next step.
Before writing the code that specifies and registers the window class you'll use, I will explain the structure WNDCLASSEX and its members, which is defined in the winuser.h file as follows:
Code
typedef struct _WNDCLASSEXA
{
UINT cbSize / / size of structure in bytes
UINT style; / / Window Style
LpfnWndProc WNDPROC / / Pointer to the function that processes messages
cbClsExtra int / / Specifies how many extra bytes to allocate following the structure of the class
cbWndExtra int / / Specifies how many extra bytes to allocate following the window instance
HINSTANCE hInstance, / / Instance of the window it belongs to this class
HICON hIcon / / window icon
HCursor HCURSOR / / will take the mouse cursor over the window
HbrBackground HBRUSH / / brushes that use the window
LpszMenuName LPCSTR / / Pointer to a zero-terminated string that specifies a resource name of the class menu
LpszClassName LPCSTR / / Pointer to the name of the class
HIconSm HICON / / small icon associated with the window
}
{
UINT cbSize / / size of structure in bytes
UINT style; / / Window Style
LpfnWndProc WNDPROC / / Pointer to the function that processes messages
cbClsExtra int / / Specifies how many extra bytes to allocate following the structure of the class
cbWndExtra int / / Specifies how many extra bytes to allocate following the window instance
HINSTANCE hInstance, / / Instance of the window it belongs to this class
HICON hIcon / / window icon
HCursor HCURSOR / / will take the mouse cursor over the window
HbrBackground HBRUSH / / brushes that use the window
LpszMenuName LPCSTR / / Pointer to a zero-terminated string that specifies a resource name of the class menu
LpszClassName LPCSTR / / Pointer to the name of the class
HIconSm HICON / / small icon associated with the window
}
Well, since you know how it is structured variable, proceed to create in our program and adjust all the members according to our needs. The following image shows how the code should be, then I'll explain:
Well, first of all, the error in line 10. As mentioned earlier, lpfnWndProc property is a pointer to the function that processes messages. This function isWindowsProc (), which I have not defined. To make this easier to understand, let's putWindowsProc function () before WinMain (),
The Win32 API specifies that the prototype of the function to process the messages is as follows:
Well, first of all, the error in line 10. As mentioned earlier, lpfnWndProc property is a pointer to the function that processes messages. This function isWindowsProc (), which I have not defined. To make this easier to understand, let's putWindowsProc function () before WinMain (),
The Win32 API specifies that the prototype of the function to process the messages is as follows:
Code:
LRESULT CALLBACK WindowsProc (HWND hwnd, UINT msg, wParam wParam, LPARAM lParam)
LRESULT type should be, because it returns the result of messages, which is more than a 32-bit long integer. Also, because it is a function pointer must be declared CALLBACK, as so specified by the standard win32 API.
The parameters passed are:
HWND hwnd: The handle of the window sending the message, once you finish processing the messages it receives, it returns control to the driver to continue on with it.
UINT msg: The message identifier is always a natural number unsigned (unsigned int), this makes it easier to process and message handling, which is why they are received through this parameter.
WPARAM wParam and LPARAM lParam: As there are several types of messages, these parameters help to process messages. Since some messages may contain an additional parameter to be procesadors. Can be eitherWORD (unsigned integer) to WPARAM or LONG(signed 32 bit integer) to LPARAM).
Fortunately, we do not have to worry about these parameters, as there is a function responsible for passing messages to Windows with everything you need to be processed, and it also expects and interprets the results of each message. This function is DispatchMessage (), which will see a little later.
For now, we have the program as follows:
Through this code we see some constants, such as CS_HREDRAW, CS_VREDRAW, IDI_APPLICATION, and COLOR_WINDOW IDI_ARROW
Just as 3 functions: LoadIcon (), LoadCursor () and RegisterClassEx ().
The constants you can get the style property are:
All 16-bit integers that can be combined with OR (|) to adjust the desired style.
Just as these, there are hundreds more constants declared in various header files using windows, it would be impossible to mention them all. It is also a great advantage in C + + and are declared, as for example in Visual Basic 6 we had to assign the constant value manually when needed to work with the Windows API. So explain the remaining 3 appeared so far:
IDI_APPLICATION = Constant indicating that use the standard Win32 application icon for the program
IDC_ARROW = Constant indicating that use the standard mouse cursor, ie the arrow is the default.
COLOR_WINDOW = constant whose value indicates the default color of the windows in Windows
LoadIcon functions () and LoadCursor (), used to load both the icon and cursor to the program.Both receive the same parameters that are(current instance, the resource name). In this case, obviously the current instance, since it is the only one, and use the predefined constants in Windows to the resource name, so the system identifies which icon and cursor should load without problem.
RegisterClassEx ()
This function registers a window class for subsequent use in calls to functions for creating windows, as CreateWindow (), which we will see later, it receives as a parameter the address of the structure of the class created.
STEP 2
Once Windows knows what kind of window to use, it is time to create the window.
First we have to declare a handle to the window, this should be a window HANDLE defined in the standard as HWND.
Then invoke the function CreateWindow (),which r e received 11 parameters and returns a HWND
The CreateWindow function () is Winuser.h definidia in its prototype is:
The parameters passed are:
HWND hwnd: The handle of the window sending the message, once you finish processing the messages it receives, it returns control to the driver to continue on with it.
UINT msg: The message identifier is always a natural number unsigned (unsigned int), this makes it easier to process and message handling, which is why they are received through this parameter.
WPARAM wParam and LPARAM lParam: As there are several types of messages, these parameters help to process messages. Since some messages may contain an additional parameter to be procesadors. Can be eitherWORD (unsigned integer) to WPARAM or LONG(signed 32 bit integer) to LPARAM).
Fortunately, we do not have to worry about these parameters, as there is a function responsible for passing messages to Windows with everything you need to be processed, and it also expects and interprets the results of each message. This function is DispatchMessage (), which will see a little later.
For now, we have the program as follows:
Through this code we see some constants, such as CS_HREDRAW, CS_VREDRAW, IDI_APPLICATION, and COLOR_WINDOW IDI_ARROW
Just as 3 functions: LoadIcon (), LoadCursor () and RegisterClassEx ().
The constants you can get the style property are:
All 16-bit integers that can be combined with OR (|) to adjust the desired style.
Just as these, there are hundreds more constants declared in various header files using windows, it would be impossible to mention them all. It is also a great advantage in C + + and are declared, as for example in Visual Basic 6 we had to assign the constant value manually when needed to work with the Windows API. So explain the remaining 3 appeared so far:
IDI_APPLICATION = Constant indicating that use the standard Win32 application icon for the program
IDC_ARROW = Constant indicating that use the standard mouse cursor, ie the arrow is the default.
COLOR_WINDOW = constant whose value indicates the default color of the windows in Windows
LoadIcon functions () and LoadCursor (), used to load both the icon and cursor to the program.Both receive the same parameters that are(current instance, the resource name). In this case, obviously the current instance, since it is the only one, and use the predefined constants in Windows to the resource name, so the system identifies which icon and cursor should load without problem.
RegisterClassEx ()
This function registers a window class for subsequent use in calls to functions for creating windows, as CreateWindow (), which we will see later, it receives as a parameter the address of the structure of the class created.
STEP 2
Once Windows knows what kind of window to use, it is time to create the window.
First we have to declare a handle to the window, this should be a window HANDLE defined in the standard as HWND.
Then invoke the function CreateWindow (),which r e received 11 parameters and returns a HWND
The CreateWindow function () is Winuser.h definidia in its prototype is:
Code
HWND CreateWindow (
LpClassName LPCTSTR, / / pointer to registered class name
LpWindowName LPCTSTR, / / pointer to window name
DWORD dwStyle, / / window style
int x, / / horizontal position of the window
int y, / / vertical position of the window
int nWidth, / / width of the window
int nHeight, / / window height
HWndParent HWND, / / handler of the parent window or owner
HMENU hMenu, / / Manager menu or child-window identifier
HANDLE hInstance, / / handle to application instance
LpParam LPVOID / / Pointer to data to create the window
);
LpClassName LPCTSTR, / / pointer to registered class name
LpWindowName LPCTSTR, / / pointer to window name
DWORD dwStyle, / / window style
int x, / / horizontal position of the window
int y, / / vertical position of the window
int nWidth, / / width of the window
int nHeight, / / window height
HWndParent HWND, / / handler of the parent window or owner
HMENU hMenu, / / Manager menu or child-window identifier
HANDLE hInstance, / / handle to application instance
LpParam LPVOID / / Pointer to data to create the window
);
After creating the window, you have to display it on screen, so use another API function, which is:ShowWindow (), it only takes two parameters, its definition is:
Code
BOOL ShowWindow (
HWND hwnd, / / Window Manager
int nCmdShow / / Window Mode
);
HWND hwnd, / / Window Manager
int nCmdShow / / Window Mode
);
Once you know the parameters, it is easy to fit into the program when creating the window. Let's create a simple window:
Here we must emphasize a very important parameter, was third. Indicates the window style that will, that is, if you can resize, move, if you have a title bar, borders, buttons to maximize, close and restore, etc. .... The following table lists the constants that can be treated in this parameter:
We can create and display many windows in our application we need, even, as mentioned at the outset, this method also create the buttons, text boxes, labels and other controls that can be used in our programs.
Now the next step is to initialize the window.
STEP 3
After calling the function ShowWindow () the window is displayed, yet has no content. So first, we need to enable the window so you can draw on it, ie, in the client area of the window.
UpdateWindow function () updates the client area of the specified window by sending a particular message (WM_PAINT) to this if the update region is not empty. The function sends the message directly to the window procedure of the specified window, avoiding the application queue. If the update region is empty, no message is sent.
This function is only needed as a parameter the handle to the window you need to update. Fully initialized leaving it to draw on it. So this step 3 only has a single line:
STEP 4
We arrived at the heart of the application. Now it control the message queue that receives the window, to be sent to the functionWindowsProc ().
The algorithm is very simple:
Here we must emphasize a very important parameter, was third. Indicates the window style that will, that is, if you can resize, move, if you have a title bar, borders, buttons to maximize, close and restore, etc. .... The following table lists the constants that can be treated in this parameter:

We can create and display many windows in our application we need, even, as mentioned at the outset, this method also create the buttons, text boxes, labels and other controls that can be used in our programs.
Now the next step is to initialize the window.
STEP 3
After calling the function ShowWindow () the window is displayed, yet has no content. So first, we need to enable the window so you can draw on it, ie, in the client area of the window.
UpdateWindow function () updates the client area of the specified window by sending a particular message (WM_PAINT) to this if the update region is not empty. The function sends the message directly to the window procedure of the specified window, avoiding the application queue. If the update region is empty, no message is sent.
This function is only needed as a parameter the handle to the window you need to update. Fully initialized leaving it to draw on it. So this step 3 only has a single line:
STEP 4
We arrived at the heart of the application. Now it control the message queue that receives the window, to be sent to the functionWindowsProc ().
The algorithm is very simple:
Code:
While the number of messages in the queue is greater than zero
Translate the message
Send the message to the function that processes
End as
Returns control to Windows
Translate the message
Send the message to the function that processes
End as
Returns control to Windows
GetMessage ()
Basically, the program must be aware of the messages you receive, so that the aging ofWindowsProc (), and it is responsible for processing the event associated with each message, it finishes, it returns control to the application, and remains waiting for more messages, so on to get the message that closes the program.
But how do we know if there are messages?. The API provides the function GetMessage ().
This function retrieves a message from the list of messages in the application and place it in the specified structure. The function will retrieve the messages in the specified range. But not retrieve messages from windows that belong to other processes or applications.
The prototype receives four parameters and returns a Boolean value:
Code
BOOL GetMessage (
LPMSG lpMsg, / / Pointer to the structure that contains the message
HWND hWnd, / / window handle, is invalid, you will receive messages from any window that belongs to the same application process.
WMsgFilterMin UINT / / First message
WMsgFilterMax UINT / / Last post
);
LPMSG lpMsg, / / Pointer to the structure that contains the message
HWND hWnd, / / window handle, is invalid, you will receive messages from any window that belongs to the same application process.
WMsgFilterMin UINT / / First message
WMsgFilterMax UINT / / Last post
);
Just need the code that goes inside the loop, which are a pair of functions that are responsible for translating the message, and send the message to WindowsProcfunction ().
TranslateMessage () and DispatchMessage ()
Both functions only as a parameter the memory address where the message.
The first is responsible for translating virtual key messages to character messages, ie messages translated the code to send the hardware to the Windows code that you can understand.
The second sends the message to the window procedure, which will be treated properly.
Structure of a message
We talked about the happy messages throughout this text, but what are they? They are a special type of variable windows specified by a structure as follows:
Code
MSG struct
{
HWND hwnd, / / handle of the window that sends the message
UINT message, / / ID of the message
WPARAM wParam, / / parameter of the message (32 bit unsigned)
LPARAM lParam / / message parameter (32 bits signed)
DWORD time; / / Time last message in the queue
POINT pt; / / Position the mouse
}
{
HWND hwnd, / / handle of the window that sends the message
UINT message, / / ID of the message
WPARAM wParam, / / parameter of the message (32 bit unsigned)
LPARAM lParam / / message parameter (32 bits signed)
DWORD time; / / Time last message in the queue
POINT pt; / / Position the mouse
}
No need to adjust all their property, simply assign the parameter only returned to the operating system, or some more in other more advanced types of messages.
The code in step 4, will be as follows:
Process messages
Now we create the window class, create a window, assign the class to the window, show the window on the screen and send messages to the function that processes them. But this function is empty, we just have to handle messages and run some code depending on the type of message it is.
DispatchMessage function () passes the message identifier WindowsProc ().
The process and try to decode the received messages is with the multiple selection statement switch () own C + +.
There are many different types of messages, usually identified with a prefix followed by an underscore and then a word in English that identifies the message action.
Prefixes can be:
Message BM_ a command button
Message CB_ a drop down list
Message CDM_ a common dialog box
DRV_ a message or Driver Driver
EM_ Message Text Box
ListBox LB_ Message
WM_ Message Window
Followed by words like
PAINT - Draw in the window
Destroy - Destroy the window
QUIT - to close the window paneling
LBUTTONDOWN - Occurs when you press the left mouse button
LLBUTTONUP - happens when you release the left mouse button
To continue our example, we will process only two messages that will occur.
WM_PAINT: initializing the window will occur
WM_DESTROY: It will happen when you close the window.
The function DefWindowProc () will process messages that do not use because even if we code for them, however they occur. Get the same parameters that WindowsProc (), until now we must look like:
Let's start processing the first message.WM_PAINT. This message occurs when you create the window, so we will see its execution immediately.
Come to 'paint' a message in the window. To do this we need some new functions and variables can be seen below. What I will do is place the code and then explain it:
First, create a device context, which is the drawable. Imagine it's like a sheet of paper pasted on the window.
After PAINTSTRUCT structure, which provides information from the window device context. Is necessary because it defines the area of memory needed to draw on the device context.
BeginPaint ()
This function takes two parameters, the identifier of the window, and the memory address of the PAINTSTRUCT. This returns an integer that is assigned as a handle to device context. With this we are now ready to start painting anything on the window.
Now, to define what is to be drawn, we will create a rectangle, which is nothing more than a simple estrcutrua that defines the exact part of the device context in which to draw.
GetClientRect ()
Retrieves the coordinates of the client area of the window. The client coordinates specify the upper left and lower right of the client area. Because client coordinates are relative to the upper left corner of the client area of the Venan, the coordinates of the upper left corner are (0.0).
The only two parameters passed are the handle of the window and the memory address of the rectangle.
DrawText ()
Now actually draw the text using DrawText (),pass the HDC used and the string to draw.The third parameter is the length of the string, but we have spent -1 because DrawText () is smart enough to realize what is the length of the text. In the fourth parameter passed thememory address where we are drawingrectangle
EndPaint ()
Marks the end of painting for a given window.The call to this function is required for each function call BeginPaint (), but only after the painting process is complete.
It receives as parameters the handle of the window and memorable address PAINTSTRUCTused.
Finally, to finish our window, we will process the WM_DESTROY message, which occurs when you close the window. In this case, we want to close the program finishes execution.
For that, we just need a function that provides the Windows API:
PostQuitMessage ()
Send a message WM_QUIT to the message queue, which is processed by DefWindowProc () to terminate the application. When you send a 0 parameter indicates that everything went well and indicate a successful program.
Following this return also a 0 to finish the program successfully.
Ready, we have our first window in C + + with the help of the Windows API. We can run smoothly and we salute our beautiful window to the world:
The entire program code would look like:
The code in step 4, will be as follows:
Process messages
Now we create the window class, create a window, assign the class to the window, show the window on the screen and send messages to the function that processes them. But this function is empty, we just have to handle messages and run some code depending on the type of message it is.
DispatchMessage function () passes the message identifier WindowsProc ().
The process and try to decode the received messages is with the multiple selection statement switch () own C + +.
There are many different types of messages, usually identified with a prefix followed by an underscore and then a word in English that identifies the message action.
Prefixes can be:
Message BM_ a command button
Message CB_ a drop down list
Message CDM_ a common dialog box
DRV_ a message or Driver Driver
EM_ Message Text Box
ListBox LB_ Message
WM_ Message Window
Followed by words like
PAINT - Draw in the window
Destroy - Destroy the window
QUIT - to close the window paneling
LBUTTONDOWN - Occurs when you press the left mouse button
LLBUTTONUP - happens when you release the left mouse button
To continue our example, we will process only two messages that will occur.
WM_PAINT: initializing the window will occur
WM_DESTROY: It will happen when you close the window.
The function DefWindowProc () will process messages that do not use because even if we code for them, however they occur. Get the same parameters that WindowsProc (), until now we must look like:
Let's start processing the first message.WM_PAINT. This message occurs when you create the window, so we will see its execution immediately.
Come to 'paint' a message in the window. To do this we need some new functions and variables can be seen below. What I will do is place the code and then explain it:
First, create a device context, which is the drawable. Imagine it's like a sheet of paper pasted on the window.
After PAINTSTRUCT structure, which provides information from the window device context. Is necessary because it defines the area of memory needed to draw on the device context.
BeginPaint ()
This function takes two parameters, the identifier of the window, and the memory address of the PAINTSTRUCT. This returns an integer that is assigned as a handle to device context. With this we are now ready to start painting anything on the window.
Now, to define what is to be drawn, we will create a rectangle, which is nothing more than a simple estrcutrua that defines the exact part of the device context in which to draw.
GetClientRect ()
Retrieves the coordinates of the client area of the window. The client coordinates specify the upper left and lower right of the client area. Because client coordinates are relative to the upper left corner of the client area of the Venan, the coordinates of the upper left corner are (0.0).
The only two parameters passed are the handle of the window and the memory address of the rectangle.
DrawText ()
Now actually draw the text using DrawText (),pass the HDC used and the string to draw.The third parameter is the length of the string, but we have spent -1 because DrawText () is smart enough to realize what is the length of the text. In the fourth parameter passed thememory address where we are drawingrectangle
EndPaint ()
Marks the end of painting for a given window.The call to this function is required for each function call BeginPaint (), but only after the painting process is complete.
It receives as parameters the handle of the window and memorable address PAINTSTRUCTused.
Finally, to finish our window, we will process the WM_DESTROY message, which occurs when you close the window. In this case, we want to close the program finishes execution.
For that, we just need a function that provides the Windows API:
PostQuitMessage ()
Send a message WM_QUIT to the message queue, which is processed by DefWindowProc () to terminate the application. When you send a 0 parameter indicates that everything went well and indicate a successful program.
Following this return also a 0 to finish the program successfully.
Ready, we have our first window in C + + with the help of the Windows API. We can run smoothly and we salute our beautiful window to the world:
The entire program code would look like:
Code
# Include <windows.h>
LRESULT CALLBACK WindowsProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) / / Parse the message you received as a parameter function
{
case WM_PAINT: / / In case WM_PAINT occurs
HDC hDC, / / Create a device context (to draw)
/ / Contains information that can be used to paint the client area of a window for the application itself.
PAINTSTRUCT ps;
hDC = BeginPaint (hwnd, & ps) / / Prepare the window to draw on it
RECT rectangle / / Create a rectangle on the window to draw on the
GetClientRect (hwnd, & rectangle) / / Add the rectangle to the window
/ / Function that draws text on the rectangle created
DrawText (hDC, / / device context identifier
"Hello World !!!!!", / / Text to draw on the screen
- 1, / / We let the function automatically adjusts the text size.
& Rectangle, / / Address of the rectangle where to draw the text
DT_SINGLELINE | DT_CENTER | DT_VCENTER / / Format the text (a single line centered horizontal and verical)
);
EndPaint (hwnd, & ps) / / End the drawing process in the window
break;
case WM_DESTROY: / / In case WM_DESTROY occurs
PostQuitMessage (0) / / Occurs WM_QUIT message to terminate the application
return 0;
break;
}
/ / This function processes messages by WindowsProc untreated (), and resize
/ / The window, maximize it, etc. .. That is, does not alter its function predterminado
return DefWindowProc (hwnd, msg, wParam, lParam);
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
/ / Windows 1.-Specify what kind of window is required
WNDCLASSEX miClase ; //Creamos la variable miClase tipo WNDCLASSEX
miClase. cbSize = sizeof ( WNDCLASSEX ) ; //Tamaño de la clase es igual al tamaño de la estructura
miClase. style = CS_HREDRAW | CS_VREDRAW ; //Redibuja la ventana si cambia su tamaño
miClase. lpfnWndProc = WindowsProc ; //Define la función que procesa los mensajes
miClase. cbClsExtra = 0 ; //No reservamos bytes extra despues de la clase
miClase. cbWndExtra = 0 ; //No reservamos bytes extra despues de la instancia
miClase. hInstance = hInstance ; //Manejador de la instancia
miClase. hIcon = LoadIcon ( 0 , IDI_APPLICATION ) ; //Ajusta el icono por default de un programa windows
miClase. hCursor = LoadCursor ( 0 , IDC_ARROW ) ; //Ajusta el cursor por default de un programa windows
miClase. hbrBackground = ( HBRUSH ) ( COLOR_WINDOW ) ; //El pincel ajsuta el color de fondo de la ventana
miClase. lpszMenuName = 0 ; //No tiene barra de menú
miClase. lpszClassName = "claseVentana" ; //Ajusta el nombre de la clase
miClase. hIconSm = 0 ; //Ajusta el icono pequeño igual que el icono de la aplicación
RegisterClassEx ( & miClase ) ; //Registra la clase de ventana para poder ser usada...
//2.-Crear la ventana
HWND hWnd ; //Variable tipo manejador de ventana, donde se guardara el manejador de la ventana creada.
hWnd = CreateWindow ( "claseVentana" , //Nombre de la clase utilizada para esta ventana
"Ventana creada en C++ con la API de Windows" , //Titulo de la ventana
WS_OVERLAPPEDWINDOW , //Estilo de la ventana
300 , //Posición Horizontal en pixeles
300 , //Posición vertical en pixeles
640 , //Ancho de la ventana en pixeles
480 , //Alto de la ventana en pixeles
0 , //Sin ventana padre
0 , //Sin menú
hInstance , //Instancia actual de la aplicación
0 ) ; //Sin datos extra para la creación de la ventana
ShowWindow ( hWnd , nCmdShow ) ; //Muestra la ventana en pantalla
//3.-Inicializar la ventana
UpdateWindow ( hWnd ) ;
//4.-Manejar los mensajes (se envian a WindowsProc() conforme vaya siendo necesario
MSG mensaje ;
while ( GetMessage ( & mensaje , 0 , 0 , 0 ) == TRUE ) //Obtiene cualquier mensaje
{
TranslateMessage ( & mensaje ) ; //Traduce el mensaje
DispatchMessage ( & mensaje ) ; //Envia el mensaje a WindowsProc()
}
return mensaje. wParam ; //Fin, regresa el control a Windows
}
LRESULT CALLBACK WindowsProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) / / Parse the message you received as a parameter function
{
case WM_PAINT: / / In case WM_PAINT occurs
HDC hDC, / / Create a device context (to draw)
/ / Contains information that can be used to paint the client area of a window for the application itself.
PAINTSTRUCT ps;
hDC = BeginPaint (hwnd, & ps) / / Prepare the window to draw on it
RECT rectangle / / Create a rectangle on the window to draw on the
GetClientRect (hwnd, & rectangle) / / Add the rectangle to the window
/ / Function that draws text on the rectangle created
DrawText (hDC, / / device context identifier
"Hello World !!!!!", / / Text to draw on the screen
- 1, / / We let the function automatically adjusts the text size.
& Rectangle, / / Address of the rectangle where to draw the text
DT_SINGLELINE | DT_CENTER | DT_VCENTER / / Format the text (a single line centered horizontal and verical)
);
EndPaint (hwnd, & ps) / / End the drawing process in the window
break;
case WM_DESTROY: / / In case WM_DESTROY occurs
PostQuitMessage (0) / / Occurs WM_QUIT message to terminate the application
return 0;
break;
}
/ / This function processes messages by WindowsProc untreated (), and resize
/ / The window, maximize it, etc. .. That is, does not alter its function predterminado
return DefWindowProc (hwnd, msg, wParam, lParam);
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
/ / Windows 1.-Specify what kind of window is required
WNDCLASSEX miClase ; //Creamos la variable miClase tipo WNDCLASSEX
miClase. cbSize = sizeof ( WNDCLASSEX ) ; //Tamaño de la clase es igual al tamaño de la estructura
miClase. style = CS_HREDRAW | CS_VREDRAW ; //Redibuja la ventana si cambia su tamaño
miClase. lpfnWndProc = WindowsProc ; //Define la función que procesa los mensajes
miClase. cbClsExtra = 0 ; //No reservamos bytes extra despues de la clase
miClase. cbWndExtra = 0 ; //No reservamos bytes extra despues de la instancia
miClase. hInstance = hInstance ; //Manejador de la instancia
miClase. hIcon = LoadIcon ( 0 , IDI_APPLICATION ) ; //Ajusta el icono por default de un programa windows
miClase. hCursor = LoadCursor ( 0 , IDC_ARROW ) ; //Ajusta el cursor por default de un programa windows
miClase. hbrBackground = ( HBRUSH ) ( COLOR_WINDOW ) ; //El pincel ajsuta el color de fondo de la ventana
miClase. lpszMenuName = 0 ; //No tiene barra de menú
miClase. lpszClassName = "claseVentana" ; //Ajusta el nombre de la clase
miClase. hIconSm = 0 ; //Ajusta el icono pequeño igual que el icono de la aplicación
RegisterClassEx ( & miClase ) ; //Registra la clase de ventana para poder ser usada...
//2.-Crear la ventana
HWND hWnd ; //Variable tipo manejador de ventana, donde se guardara el manejador de la ventana creada.
hWnd = CreateWindow ( "claseVentana" , //Nombre de la clase utilizada para esta ventana
"Ventana creada en C++ con la API de Windows" , //Titulo de la ventana
WS_OVERLAPPEDWINDOW , //Estilo de la ventana
300 , //Posición Horizontal en pixeles
300 , //Posición vertical en pixeles
640 , //Ancho de la ventana en pixeles
480 , //Alto de la ventana en pixeles
0 , //Sin ventana padre
0 , //Sin menú
hInstance , //Instancia actual de la aplicación
0 ) ; //Sin datos extra para la creación de la ventana
ShowWindow ( hWnd , nCmdShow ) ; //Muestra la ventana en pantalla
//3.-Inicializar la ventana
UpdateWindow ( hWnd ) ;
//4.-Manejar los mensajes (se envian a WindowsProc() conforme vaya siendo necesario
MSG mensaje ;
while ( GetMessage ( & mensaje , 0 , 0 , 0 ) == TRUE ) //Obtiene cualquier mensaje
{
TranslateMessage ( & mensaje ) ; //Traduce el mensaje
DispatchMessage ( & mensaje ) ; //Envia el mensaje a WindowsProc()
}
return mensaje. wParam ; //Fin, regresa el control a Windows
}
I hope this helps you understand how Windows manages windows.
0 comments:
Post a Comment