banner



How To Open A Window In C++

A Simple Window

Example: simple_window

[images/simple_window.gif] Sometimes people come on IRC and inquire "How do I make a window?"...Well it's not entirely that simple I'chiliad afraid. Information technology's not difficult in one case you know what you're doing but there are quite a few things you need to practice to get a window to evidence up; And they're more than tin can be just explained over a chat room, or a quick annotation.

I ever liked to practice things first and acquire them later...so here is the code to a simple window which will be explained shortly.

#include <windows.h>  const char g_szClassName[] = "myWindowClass";  // Pace 4: the Window Procedure LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {     switch(msg)     {         case WM_CLOSE:             DestroyWindow(hwnd);         break;         case WM_DESTROY:             PostQuitMessage(0);         break;         default:             render DefWindowProc(hwnd, msg, wParam, lParam);     }     render 0; }  int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,     LPSTR lpCmdLine, int nCmdShow) {     WNDCLASSEX wc;     HWND hwnd;     MSG Msg;      //Step 1: Registering the Window Class     wc.cbSize        = sizeof(WNDCLASSEX);     wc.style         = 0;     wc.lpfnWndProc   = WndProc;     wc.cbClsExtra    = 0;     wc.cbWndExtra    = 0;     wc.hInstance     = hInstance;     wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);     wc.hCursor       = LoadCursor(NULL, IDC_ARROW);     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);     wc.lpszMenuName  = Zip;     wc.lpszClassName = g_szClassName;     wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);      if(!RegisterClassEx(&wc))     {         MessageBox(Zero, "Window Registration Failed!", "Error!",             MB_ICONEXCLAMATION | MB_OK);         return 0;     }      // Footstep ii: Creating the Window     hwnd = CreateWindowEx(         WS_EX_CLIENTEDGE,         g_szClassName,         "The championship of my window",         WS_OVERLAPPEDWINDOW,         CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,         NULL, Null, hInstance, Nada);      if(hwnd == NULL)     {         MessageBox(NULL, "Window Creation Failed!", "Error!",             MB_ICONEXCLAMATION | MB_OK);         return 0;     }      ShowWindow(hwnd, nCmdShow);     UpdateWindow(hwnd);      // Footstep iii: The Message Loop     while(GetMessage(&Msg, Aught, 0, 0) > 0)     {         TranslateMessage(&Msg);         DispatchMessage(&Msg);     }     render Msg.wParam; }        
For most function this is the simplest windows program you can write that actually creates a functional window, a mere seventy or then lines. If you got the start example to compile so this 1 should work with no problems.

Pace one: Registering the Window Grade

A Window Form stores data about a type of window, including it'south Window Process which controls the window, the small-scale and large icons for the window, and the background color. This fashion, you lot tin register a class one time, and create as many windows as you desire from it, without having to specify all those attributes over and over. Most of the attributes you prepare in the window class can be changed on a per-window basis if desired.

A Window Grade has NOTHING to exercise with C++ classes.

const char g_szClassName[] = "myWindowClass";        
The variable above stores the proper noun of our window course, we volition use it shortly to register our window class with the system.
          WNDCLASSEX wc;        
          wc.cbSize        = sizeof(WNDCLASSEX);     wc.style         = 0;     wc.lpfnWndProc   = WndProc;     wc.cbClsExtra    = 0;     wc.cbWndExtra    = 0;     wc.hInstance     = hInstance;     wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);     wc.hCursor       = LoadCursor(Goose egg, IDC_ARROW);     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);     wc.lpszMenuName  = NULL;     wc.lpszClassName = g_szClassName;     wc.hIconSm       = LoadIcon(Cypher, IDI_APPLICATION);      if(!RegisterClassEx(&wc))     {         MessageBox(NULL, "Window Registration Failed!", "Error!",             MB_ICONEXCLAMATION | MB_OK);         render 0;     }        

This is the lawmaking we utilise in WinMain() to register our window class. Nosotros fill up out the members of a WNDCLASSEX construction and call RegisterClassEx().

The members of the struct affect the window class every bit follows:

cbSize
The size of the structure.
style
Course Styles (CS_*), not to be confused with Window Styles (WS_*) This can usually be set to 0.
lpfnWndProc
Pointer to the window procedure for this window form.
cbClsExtra
Amount of extra data allocated for this grade in retention. Usually 0.
cbWndExtra
Corporeality of extra data allocated in retentivity per window of this blazon. Normally 0.
hInstance
Handle to application instance (that we got in the beginning parameter of WinMain()).
hIcon
Large (usually 32x32) icon shown when the user presses Alt+Tab.
hCursor
Cursor that will be displayed over our window.
hbrBackground
Background Brush to ready the color of our window.
lpszMenuName
Name of a menu resource to use for the windows with this class.
lpszClassName
Name to identify the form with.
hIconSm
Small (normally 16x16) icon to show in the taskbar and in the meridian left corner of the window.
Don't worry if that doesn't make much sense to you yet, the various parts that count will be explained more later. Another thing to call back is to non endeavor and remember this stuff. I rarely (never) memorize structs, or function parameters, this is a waste matter of effort and, more importantly, time. If you lot know the functions you demand to call then it is a matter of seconds to wait up the exact parameters in your help files. If you lot don't have help files, get them. Y'all are lost without. Eventually you will come to know the parameters to the functions you use most.

We and then call RegisterClassEx() and check for failure, if information technology fails we pop upward a message which says and then and abort the plan by returning from the WinMain() function.

Pace two: Creating the Window

Once the class is registered, we tin create a window with information technology. You should wait up the paramters for CreateWindowEx() (as you should E'er do when using a new API phone call), just I'll explain them briefly here.

          HWND hwnd;        
          hwnd = CreateWindowEx(         WS_EX_CLIENTEDGE,         g_szClassName,         "The championship of my window",         WS_OVERLAPPEDWINDOW,         CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,         NULL, Goose egg, hInstance, Zero);        

The first parameter (WS_EX_CLIENTEDGE) is the extended windows mode, in this case I have set it to give information technology a sunken inner edge around the window. Fix information technology to 0 if you'd like to run into the difference. Likewise play with other values to see what they practise.

Next we have the class name (g_szClassName), this tells the organisation what kind of window to create. Since we want to create a window from the class we but registered, we use the name of that grade. Later on that nosotros specify our window proper noun or title which is the text that will be displayed in the Explanation, or Championship Bar on our window.

The parameter we accept equally 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 exercise. These volition be covered more later on.

The next iv parameters (CW_USEDEFAULT, CW_USEDEFAULT, 320, 240) are the X and Y co-ordinates for the tiptop left corner of your window, and the width and height of the window. I've fix 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 Ten value of zero and information technology 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 tin can display at a given resolution.

Next (Zippo, NULL, g_hInst, Zero) nosotros have the Parent Window handle, the menu handle, the application instance handle, and a pointer to window cosmos data. In windows, the windows on your screen are arranged in a heirarchy of parent and child windows. When you see a button on a window, the push is the Child and information technology is contained within the window that is it'southward Parent. In this instance, the parent handle is Naught considering nosotros accept no parent, this is our main or Pinnacle Level window. The menu is NULL for now since we don't have one yet. The instance handle is fix to the value that is passed in as the first parameter to WinMain(). The creation data (which I nigh never employ) that tin exist used to send additional data to the window that is being created is also Null.

If yous're wondering what this magic NULL is, it'south but divers equally 0 (null). Actually, in C it'south defined as ((void*)0), since it's intended for apply with pointers. Therefore you will maybe become warnings if y'all utilize NULL for integer values, depending on your compiler and the warning level settings. Yous tin choose to ignore the warnings, or just use 0 instead.

Number i 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 encounter if they failed or not. CreateWindow() will fail at some point fifty-fifty 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!

          if(hwnd == NULL)     {         MessageBox(Nada, "Window Cosmos Failed!", "Error!",             MB_ICONEXCLAMATION | MB_OK);         return 0;     }        

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 and so update it to ensure that it has properly redrawn itself on the screen.

          ShowWindow(hwnd, nCmdShow);    UpdateWindow(hwnd);        

The nCmdShow parameter is optional, you could simply pass in SW_SHOWNORMAL all the time and exist done with it. Even so using the parameter passed into WinMain() gives whoever is running your program to specify whether or not they desire your window to start off visible, maximized, minimized, etc... Y'all will discover options for these in the properties of windows shortcuts, and this parameter is how the choice is carried out.

Stride 3: The Bulletin Loop

This is the heart of the whole program, pretty much everything that your plan does passes through this indicate of control.

          while(GetMessage(&Msg, NULL, 0, 0) > 0)     {         TranslateMessage(&Msg);         DispatchMessage(&Msg);     }     render Msg.wParam;        

GetMessage() gets a message from your application's message queue. Any time the user moves the mouse, types on the keyboard, clicks on your window's menu, or does any number of other things, messages are generated by the organization and entered into your programme's message queue. By calling GetMessage() you are requesting the next bachelor message to be removed from the queue and returned to you for processing. If there is no message, GetMessage() Blocks. If you are unfamiliar with the term, it means that information technology waits untill there is a bulletin, and and then returns it to yous.

TranslateMessage() does some additional processing on keyboard events like generating WM_CHAR messages to get forth with WM_KEYDOWN messages. Finally DispatchMessage() sends the message out to the window that the message was sent to. This could be our principal window or information technology could exist another one, or a control, and in some cases a window that was created backside the scenes by the sytem or some other plan. This isn't something you demand to worry about because all we are concerned with is that nosotros become the message and ship it out, the organization takes care of the rest making sure information technology gets to the proper window.

Step 4: the Window Procedure

If the message loop is the heart of the programme, the window procedure is the brain. This is where all the messages that are sent to our window become processed.
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {     switch(msg)     {         case WM_CLOSE:             DestroyWindow(hwnd);         suspension;         case WM_DESTROY:             PostQuitMessage(0);         break;         default:             return DefWindowProc(hwnd, msg, wParam, lParam);     }     return 0; }        

The window process is called for each message, the HWND parameter is the handle of your window, the i that the message applies to. This is important since y'all might take 2 or more than 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 starting time paramter, any other windows volition not be affected, only the one that the message was intended for.

WM_CLOSE is sent when the user presses the Shut Push button [x] or types Alt-F4. This will cause the window to exist destroyed by default, but I like to handle information technology explicitly, since this is the perfect spot to do cleanup checks, or ask the user to salvage files etc. earlier exiting the program.

When we phone call DestroyWindow() the organization sends the WM_DESTROY message to the window getting destroyed, in this case it's our window, and and then destroys any remaining kid windows earlier finally removing our window from the system. Since this is the only window in our program, we are all done and we want the program to get out, so we call PostQuitMessage(). This posts the WM_QUIT bulletin to the bulletin loop. Nosotros never receive this message, because it causes GetMessage() to render Faux, and as you'll see in our bulletin loop lawmaking, when that happens we stop processing letters and return the final result code, the wParam of WM_QUIT which happens to be the value we passed into PostQuitMessage(). The return value is simply really useful if your programme is designed to exist called by another program and you desire to return a specific value.

Step 5: There is no Step v

Phew. Well that's it! If I haven't explained stuff clearly plenty yet, just hang in there and hopefully things will become more articulate as we get into more usefull programs.

Source: http://www.winprog.org/tutorial/simple_window.html

Posted by: mcginnismanday.blogspot.com

0 Response to "How To Open A Window In C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel