The Windows Programming Model
The Windows Programming Model
R704
MODULE 1
Programs written for traditional operating environments use a procedural programming model in which programs execute from top to bottom in an orderly fashion. The path taken from start to finish may vary with each invocation of the program depending on the input it receives or the conditions under which it is run, but the path remains fairly predictable. In a C program, execution begins with the first line in the function named main and ends when main returns. In between, main might call other functions and these functions might call even more functions, but ultimately it is the programnot the operating systemthat determines what gets called and when. Windows programs operate differently. They use the event-driven programming model illustrated in Figure 1-1, in which applications respond to events by processing messages sent by the operating system. An event could be a keystroke, a mouse click, or a command for a window to repaint itself, among other things. The entry point for a Windows program is a function named WinMain, but most of the action takes place in a function known as the window procedure. The window procedure processes messages sent to the window. WinMain creates that window and then enters a message loop, alternately retrieving messages and dispatching them to the window procedure. Messages wait in a message queue until they are retrieved. A typical Windows application performs the bulk of its processing in response to the messages it receives, and in between messages, it does little except wait for the next message to arrive. The message loop ends when a WM_QUIT message is retrieved from the message queue, signaling that it's time for the application to end. This message usually appears because the user selected Exit from the File menu, clicked the close button (the small button with an X in the window's upper right corner), or selected Close from the window's system menu. When the message loop ends, WinMain returns and the application terminates.
SJCET, PALAI
Module I
R704
SJCET, PALAI
Module I
R704
The window procedure typically calls other functions to help process the messages it receives. It can call functions local to the application, or it can call API functions provided by Windows. API functions are contained in special modules known as dynamic-link libraries, or DLLs. The Win32 API includes hundreds of functions that an application can call to perform various tasks such as creating a window, drawing a line, and performing file input and output. In C, the window procedure is typically implemented as a monolithic function containing a large switch statement with cases for individual messages. The code provided to process a particular message is known as a message handler. Messages that an application doesn't process are passed on to an API function named DefWindowProc, which provides default responses to unprocessed messages.
WM_LBUTTONDOWN The left mouse button is pressed. WM_LBUTTONUP WM_MOUSEMOVE WM_PAINT WM_QUIT WM_SIZE The left mouse button is released. The mouse pointer is moved. A window needs repainting. The application is about to terminate. A window is resized.
SJCET, PALAI
Module I
R704
A message manifests itself in the form of a call to a window's window procedure. Bundled with the call are four input parameters: the handle of the window to which the message is directed, a message ID, and two 32-bit parameters known as wParam and lParam. The window handle is a 32-bit value that uniquely identifies a window. Internally, the value references a data structure in which Windows stores relevant information about the window such as its size, style, and location on the screen. The message ID is a numeric value that identifies the message type: WM_CREATE, WM_PAINT, and so on. wParam and lParam contain information specific to the message type. When a WM_LBUTTONDOWN message arrives, for example, wParam holds a series of bit flags identifying the state of the Ctrl and Shift keys and of the mouse buttons. lParam holds two 16-bit values identifying the location of the mouse pointer when the click occurred. Together, these parameters provide the window procedure with all the information it needs to process the WM_LBUTTONDOWN message.
Collectively these 3 components are called API. Each of the 3 API components is provided as a DLL.An application can call functions in the DLL as though they were part of the application. The API DLLs are normally found in the windows os directory (usually C:\Windows\System) where file required by the system are usually stored. In WIN32 API ,the DLLS are stored as USER32.DLL,GDI32.DLL and KERNEL32.DLL.
In the traditional procedural programming model, the flow of program execution follows a predefined path set down by the programmer. Windows programming is different, it is event driven.
SJCET, PALAI
Module I
R704
In the sequence driven programming model, the operating system simply executes the program and then waits for it to finish. If the program desires, it can take help of the OS to do jobs like file opening, saving, printing etc. In the event driven programming model the application on execution sets up variables and structures and perform other initializations, just as a typical procedural program does. Once this initialization phase is over the activity ceases. The windows application now just sits there, waiting for user input of some form or the other. This input can be in the form of a mouse click or a keystroke. As soon as the user provides this input, a series of event follows, and the application responds to these events
#include <windows.h> LONG WINAPI WndProc (HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { WNDCLASS wc; HWND hwnd; MSG msg; wc.style = 0; // Class style wc.lpfnWndProc = (WNDPROC) WndProc; // Window procedure address wc.cbClsExtra = 0; // Class extra bytes wc.cbWndExtra = 0; // Window extra bytes wc.hInstance = hInstance; // Instance handle wc.hIcon = LoadIcon (NULL, IDI_WINLOGO); // Icon handle wc.hCursor = LoadCursor (NULL, IDC_ARROW); // Cursor handle wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); // Background color wc.lpszMenuName = NULL; // Menu name wc.lpszClassName = "MyWndClass"; // WNDCLASS name RegisterClass (&wc);
// WNDCLASS name
SJCET, PALAI
Module I
R704
"SDK Application", // Window title WS_OVERLAPPEDWINDOW, // Window style CW_USEDEFAULT, // Horizontal position CW_USEDEFAULT, // Vertical position CW_USEDEFAULT, // Initial width CW_USEDEFAULT, // Initial height HWND_DESKTOP, // Handle of parent window NULL, // Menu handle hInstance, // Application's instance handle NULL // Window-creation data ); ShowWindow (hwnd, nCmdShow); UpdateWindow (hwnd); while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg); DispatchMessage (&msg); } return msg.wParam; } LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_PAINT: hdc = BeginPaint (hwnd, &ps); Ellipse (hdc, 0, 0, 200, 100); EndPaint (hwnd, &ps); return 0; case WM_DESTROY: PostQuitMessage (0); return 0; } return DefWindowProc (hwnd, message, wParam, lParam); }
SJCET, PALAI
Module I
R704
WinMain Function
Just as the entry point to a C program is the function main ,the entry point a Windows program is WinMain ,which always appear like this: Int WINAPI WinMain(HINSTANCE hIntance, HINSTANCE hprevIntance,PSTR szCmdLine ,int iCmdShow) It is declared in WINBASE.h. The first parameter to WinMain is something called an instance handle. In Windows Programming a handle is simply a number that an application uses to identify something. In his case, the handle uniquely identifies the program. It is required as an argument to some other Windows function calls. A program could determine whether other instances of itself were running by checking the hprevInstance parameter . The third parameter is the command line used to run the program . The fourth parameter indicates how the window should be initially displayed either normally or maximized, or minimized to be displayed in the task list bar.
Module I
R704
handle of the window's parent window (HWND_DESKTOP for an application's main window); the handle of the menu associated with the window, if any; the application's instance handle (a value that lets the programmer differentiate between the program itself and the modulesthat is, DLLsthat it loads); and a pointer to application-specific window-creation data. I could easily devote a section of this book to CreateWindow and its parameters, but as you'll see later, MFC hides much of this detail inside the class library. A typical MFC application doesn't have a WinMain function (at least not one you can see), and it doesn't call RegisterClass or CreateWindow.
Message Loop
Next comes the message loop. In order to retrieve and dispatch messages, WinMain executes a simple while loop that calls the GetMessage, TranslateMessage, and DispatchMessage API functions repeatedly. GetMessage checks the message queue. If a message is available, it is removed from the queue and copied to msg; otherwise, GetMessage blocks on the empty message queue until a message is available. msg is an instance of the structure MSG, whose fields contain pertinent message parameters such as the message ID and the time at which the message was placed in the queue. TranslateMessage converts a keyboard message denoting a character key to an easier-to-use WM_CHAR message, and DispatchMessage dispatches the message to the window procedure. The message loop executes until GetMessage returns 0, which happens only when a WM_QUIT message is retrieved from the message queue. When this occurs, WinMain ends and the program terminates. Messages dispatched with DispatchMessage generate calls to the window procedure WndProc. The sample program in Figure 1-2 processes just two message types, WM_PAINT and WM_DESTROY; all other messages are passed to DefWindowProc for default processing. A switch-case block inspects the message ID passed in the message parameter and executes the appropriate message handler. The WM_PAINT handler calls the BeginPaint API function to obtain a device context handle before painting begins and the EndPaint API function to release the handle when painting is finished. In between, the Ellipse API function draws an ellipse that is 200 pixels wide and 100 pixels high. A device context handle is the "magic cookie" that permits a Windows application to draw on the screen. Without it, functions such as Ellipse won't work.
The WM_DESTROY handler calls the PostQuitMessage API function to post a WM_QUIT message to the message queue and ultimately cause the program to terminate. The WM_DESTROY message is sent to a window just before it is destroyed. A top-level window Department of Computer Science and Engineering SJCET, PALAI
Module I
R704
must call PostQuitMessage when it receives a WM_DESTROY message, or else the message loop will not fall through and the program will never end.
Window Procedure
Every window that a program creates has an associated window procedure. This window procedure is a function that could be either in our program or in a dynamic link library. Windows sends a message to a window by calling the window procedure. The window procedure does some processing based on the message and returns control to windows. A windows program can contain more than one window procedure. A window procedure is always associated with a particular window class registered by the Register Class. A window procedure is always defined like this: LRESULT CALLBACK wParam,LPARAM lParam) WndProc(HWND hwnd,UINT message,WPARAM
The first parameter is hwnd, the handle to the window receiving the message. The second parameter is the same as the message field in the MSG structure; its a number that identifies the message. The last two parameters are 32-bit message parameter that provides more information about the message. What theses parameters contain is specific to each type of message
SJCET, PALAI
Module I case WM_CREATE: [process WM_CREATE message] return 0; case WM_PAINT: [process WM_PAINT message] return 0; case WM_DESTOY: [process WM_DESTROY message] return 0; } return DefWindowProc(hwnd,imsg,wParam,lParam);
R704
SJCET, PALAI
Module I Common Hungarian Notation Prefixes Prefix b c or ch clr cx, cy dw h l n p sz w Data Type BOOL char COLORREF Horizontal or vertical distance DWORD Handle LONG int Pointer Zero-terminated string WORD
R704
Most MFC programmers use Hungarian notation, too. Glance through the source code for a typical MFC program and you'll see hundreds of hs and lps and other familiar prefixes as well as prefixes representing MFC's own data types (for example, wnd for CWnd variables). It's also common to prefix member variables with m_ so that it's obvious whether a variable is a member of a class. A temporary CString variable created on the stack might have the name strWndClass, but if it's a member variable it will probably be called m_strWndClass. You don't have to abide by these rules yourself, of course, but observing established naming conventions will make your code more readable to other programmers who do.
MENUS
A menu is probably the most important part of the consistent user interface that Windows programs offer, and adding a menu to our program is a relatively easy part of Windows Menu Concepts A windows menu bar is displayed immediately below the caption bar. This menu bar is sometimes called a programs main menu or the top-level menu. Items listed in the top- level menu usually invoke drop-down menus, which are also called popup menus or submenus. You can also define multiple nestings of popups: that is, an item on a popup menu can invoke another popup menu. Sometimes items in popup menus invoke a dialog box for more information. (Dialog boxes are covered in the next chapter.) Most parent windows have, to the far left of the caption bar, a display of the programs small icon. This icon invokes the system Department of Computer Science and Engineering SJCET, PALAI
Module I
R704
mend, which is really another popup menu. Menu items in popups can be checked, which means that Windows draws a small check mark to the left of the menu text. The use of check marks lets the user choose different program options from the menu. These options can be mutually exclusive, but they dont have to be. Toplevel menu items cannot be checked. Menu items in the top-level menu or in popup menus can be enabled, disabled or grayed. The words active and inactive are sometimes used synonymously with enabled and disabled. Menu items flagged as enabled or disabled look the same to the user, but a grayed menu item is displayed in gray text. From the perspective of the user, enabled, disabled, and grayed menu items can all be selected (highlighted). That is, the user can click the mouse on a disabled menu item, or move the reverse-video cursor bar to a disabled menu item, or trigger the menu item by using the items key letter. However, from the perspective of your program, enabled, disabled, and grayed menu items function differently. Windows sends your program a WMCOMMAND message only for enabled menu items. You use disabled and grayed menu items fr options that are not currently valid. If you want to let the user know the option is not valid, make it grayed. Menu Structure
When you create or change menus in a program, its useful to think of the top-level menu and each popup menu as being separate menus. The top-level menu has a menu handle, each popup menu within a top-level menu has its own menu handle, and the system menu (which is also a popup) has a menu handle. Each item in a menu is defined by three characteristics. The first characteristic is what appears in the menu. This is either a text string or a bitmap. The second characteristic is either an ID number that Windows sends to your program in a WM_COMMAND message or the handle to a popup menu that Windows displays when the user chooses that menu item. The third characteristic describes the attribute of the menu item, including whether the item is, disabled, grayed, or checked.
Module I
R704
inactive, its text is grayed, and the item does not generate a WM_COMMAND message. If you select the Inactive option, the menu item is inactive and does not generate a WM_COMMAND message but its text is displayed normally. The Checked option places a check mark next to a menu item. The Separator option causes a horizontal separator bar to be drawn on popup menus. For items in popup menus, you can use the columnar tab character \t in the character string. Text following the \t is placed in a new column spaced far enough to the right to accommodate the longest text string in the first column of the popup. Well see how this works when we look at keyboard accelerators toward the end of this chapter. A \a in the character string right-justifies the text that follows it. The ID values you specify are the numbers that Windows sends to the window procedure in menu messages. The ID values should be unique within a menu. By convention, I use identifiers beginning with the letters 1DM (ID for a Menu).
Drawing on Windows.
Most Windows applications have only one menu in the resource script. You can give the menu a text name that is the same as the name of the program. Programmers often use the name of the program as the name of the menu so that the same character string can be used for the window class, the name of the programs icon, and the name of the menu. The program then makes reference to this menu in the definition of the window class: wndclass.lpszMenuName =szAppName; Referencing the Menu in Your Program
Although specifying the menu in the window class is the most common way to reference a menu resource, thats not the only way to do it. A Windows application can load a menu resource into memory with the LoadMenu function, which is similar to the Loadicon and LoadCursor functions described earlier. LoadMenu returns a handle to the menu, If you use a name for the menu in the resource script, the statement looks like this: hhlenu =LoadMenu (hlnstance, TEXT (MyMenu)); If you use a number, the LoadMenu call takes this form: hMenu = LoadMenu (hlnstance, MAKEINTRESOURCE (ID_MENU));
You can then specify this menu handle as the ninth parameter to Create Window:
hwnd =CreateWindow (TEXT (MyClass), TEXT (Window Captlon), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, hMenu, hlnstance, NULL);
SJCET, PALAI
Module I
R704
In this case, the menu specified in the Create Window call overrides any menu specified in the window class. You can think of the menu in the window class as being a default menu for the windows based on the window class if the ninth parameter to Create Window is NULL. Therefore, you can use different menus for several windows based on the same window class. You can also have a NULL menu name in the window class and a NULL menu handle in the Create Window call and assign a menu to a window after the window has been created:
This form lets you dynamically change a windows menu. Well see an example of this in the NOPOPUPS program, shown later in this chapter. Any menu that is attached to a window is destroyed when the window is destroyed. Any menus not attached to a window should be explicitly destroyed by calls to DestroyMenu before the program terminates.
Drawing on Windows
Windows usually sends a window procedure several different messages when the user selects a menu item. In most cases, your program can ignore many of these messages and simply pass them to DefWindowProc. One such message is WMJNITMENU with the following parameters: wParam: Handle to main menu lParam: 0 The value of wParam is the handle to your maifl menu even if the user is selecting an item from the system menu. Windows programs generally ignore the WM_INITMENU message. Although the message exists to give you the opportunity to change the menu before an item is chosen, I suspect any changes to the top-level menu at this time would be disconcerting to the user.
Your program also receives WM_MENUSELECT messages. A program can receive many WM_MENUSELECT messages as the user moves the cursor or mouse among the menu items. This is helpful for implementing a status bar that contains a full text description of the menu option. The parameters that accompany WM_MENUSELECT are as follows: LOWORD (wParam): Selected item: Menu ID or popup menu index HIWORD (wParam): Selection flags IParam: Handle to menu containing selected item
SJCET, PALAI
Module I
R704
WM_MENUSELECT is a menu-tracking message. The value of wParam tells you what item of the menu is currently selected (highlighted). The selection flags in the high word of wParam can be a combination of the following: MF_GRAYED, MF_DISABLED, MF CHECKED, MFBITMAP, MF.OPUP, MF_HELP, MF_.SYSMENU, and MF_MOUSESELECT. You may want to use WM_MENUSELECT if you need to change something in the client area of your window based on the movement of the highlight among the menu items. Most programs pass this message to DeJWindowProc.
When Windows is ready to display a popup menu, it sends the window procedure a WM_INITMENUPOPUP message with the following parameters: wParam: Popup menu handle LOWORD (lParam): Popup index HIWORD (lParam): I for system menu, 0 otherwise This message is important if you need to enable or disable items in a popup menu before it is displayed. For instance, suppose your program can copy text from the clipboard using the Paste command on a popup menu. When you receive a WM_INITMENUPOPUP message for that popup, you should determine whether the clipboard has text in it. If it doesnt, you should gray the Paste menu item. The most important menu message is WM_COMMAND. This message indicates that the user has chosen an enabled menu item from your windows menu. WM_COMMAND messages also result from child window controls. If you happen to use the same ID codes for menus and child window controls, you can differentiate between them by examining the value of IParam, which will be 0 for a menu item.
The WM_SYSCOMMAND message is similar to the WM_COMMAND message except that WM_SYSCOMMAND signals that the user has chosen an enabled menu item from the system menu: wParam: Menu ID IParam: 0 Department of Computer Science and Engineering SJCET, PALAI
Module I
R704
However, if the WM_SYSCOMMAND message is the result of a mouse click, LOWORD (lParam) and HIWORD (iParam) will contain the x andy screen coordinates of the mouse cursors location. For WM_SYSCOMMAND, the menu ID indicates which item on the system menu has been chosen. For the predefined system menu items, the bottom four bits should be masked out by ANDing with 0xFFF0. The resultant value will be one of the following: SC_SIZE, SC_MOVE, SC_MINIMIZE. SC_MAXIMIZE, SC_NEXTWINDOW. SC_PREVWINDOW, SC_ CLOSE, SC_VSCROLL, SC_HSCROLL, SC_ARRANGE, SC_RESTORE, and SC_TASKLIST. In addition, wParam can be SC_MOUSEMENU or SC_KEYMENU.
If you add menu items to the system menu, the low word of wParam will be the menu ID that you define. To avoid conflicts with the predefined menu IDs, use values below 0xF000. It is important that you pass normal WM_SYSCOMMAND messages to DefWindowProc. If you do not, youll effectively disable the normal system menu commands. The final message well look at is WM_MENUCHAR, which isnt really a menu message at all. Windows sends this message to your window procedure in one of two circumstances: if the user presses Alt and a character key that does not correspond to a menu item, or, when a popup is displayed, if the user presses a character key that does not correspond to an item in the popup. The parameters that accompany the WM_MENUCHAR message are as follows: LOWORD (wParam): Character code (ASCII or Unicode) HIWORD (wParam): Selection code lParam: Handle to menu The selection code is:
0 :No popup is displayed. MF_POPUP :Popup is displayed. MF_SYSMENUSystem menu popup is displayed. Windows programs usually pass this message to DefWindowProc, which normally returns a 0 to Windows, which causes Windows to beep.
SJCET, PALAI
Module I
R704
BUTTONS
The child window procedure can determine the window handle of its parent by calling GetPa rent, hwndParent = GetParent (hwnd); where hwnd is the window handle of the child window. It can then send a message to the parent window procedure: SendMessage (hwndParent, message, wParam, iParam); For this message the child window could set wParam to its child window ID. The lParam could then be set to a I if the child window were being checked and a 0 if it were being unchecked. Thats one possibility. This in effect creates a child window control. The child window processes mouse and keyboard messages and notifies the parent window when the child windows state has changed. In this way, the child window becomes a high-level input device for the parent window. It encapsulates a specific functionality with regard to its graphical appearance on the screen, its response to user input, and its method of notifying another window when an important input event has occurred.
Class name TEXT (button) Window text button[1].szText Window style US_CHILD US_VISIBLE button[i].iStyle x position cxChar y position cyChar (1 + 2 * i) Width 20 * xChar Height 7 * yChar / 4 Parent window hwnd Child window ID (HMENU) i Instance handle ((LPCREATESTRUCT) lParam) hlnstance Extra parameters NULL
The class name parameter is the predefined name. The window style uses WS_CI-IILD, WS_VISIBLE, and one of the 10 button styles (BS_PUSHBUTfON, BS_DEFPUSHBUUON, and so forth) that are defined in the button structure. The window text parameter (which for a normal window is the text that appears in the captioi bar) is text that will be displayed with each button. Ive simply used text that identifies the button style. Department of Computer Science and Engineering SJCET, PALAI
Module I
R704
The x position and y position parameters indicate the placement of the upper left corner of the child window relative to the upper left corner of the parent windows client area. The width and height parameters specify the width and height of each child window, Notice that Im using a function named GetDlalogBaseUn its to obtain the width and height of the characters in the default font. This is the function that dialog boxes use to obtain text dimensions. The function returns a 32-bit value comprising a width in the low word and a height in the high word. While GefDialogBaseUnits returns roughly the same values as can be obtained from (he GetTextMetrics function, its somewhat easier to use and will ensure more consistency with controls in dialog boxes. The child window ID parameter should be unique for each child window. This ID helps your window procedure identify the child window when processing WM_COMMANt) messages from it. Notice that the child window ID is passed in the Create Window parameter normally used to specify the programs menu, so it must be cast to an HMENU, The instance handle parameter of the Create Window call looks a little strange, but were taking advantage of the fact that during a WM_CREATE message IParam is actually a pointer to a structure of type CREATESTRUCT (creation structure) that has a member hinstance. So we cast iParam into a pointer to a CREATESTRUCT structure and get hinstanc out. (Some Windows programs use a global variable named hlnst to give window procedures access to the instance handle available in WinMain. In WinMain, you need to simply set hInst = hlnstance before creating the main window.
SJCET, PALAI
Module I
R704
The notification codes 1 through 4 are for an obsolete button style callod BS...USERBUTTON. (Its been replaced with BS_OWNERDRAW and a different notification mechanism.) The notification codes 6 and 7 are sent only if the button style includes the flag BSNOTIFY, The notification code 5 is sent only for BS_RADIOBUTrON, BS_AUTORADIOBUTrON, and BS_OWNERDRAW buttons, or for other buttons if the button style includes BS_NOTIFY.
The BM_GETCHECK and BM_SETCHECK messages are sent by a parent window to a child window control to get and set the check mark of check boxes and radio buttons. The BM_GETSTATE and BM_SETSTATE messages refer to the normal, or pushed, state of a window when you click it with the mouse or press it with the Spacebar. The BM_SETSTYLE message lets you change the button style after the button is created. Department of Computer Science and Engineering SJCET, PALAI
Module I
R704
Each child window has a window handle and an ID that is unique among its siblings. Knowing one of these items allows you to get the other. If you know the window handle of the child, you can obtain the ID using : id = GetWindowLong (hwndChlld, GWL_ID) ; The area accessed with the GWL_ID identifIer is reserved by Windows when the child window is created.
Push Buttons
A push button is a rectangle enclosing text specified in the window text parameter of the Create Window call. The rectangle takes up the full height and width of the dimensions given in the Create Window or MoveWindow call. The text is centered within the rectangle. Push-button controls are used mostly to trigger an immediate action without retaining any type of on/off indication. The two types of push-button controls have window styles called BS_PUSHBUTTON and BS_DEFPUSHBUTTON. The DEF in BS_DEFPUSHBUTTON stands for default. When used to design dialog boxes, BS_PUSHBUTTON controls and BS_DEFPUSHBUTTON controls function differently from one another. When used as child window controls, however, the two types of push buttons function the same way, although BS_DEFPUSHBUTTON has a heavier outline. When the mouse cursor is inside the push button, pressing the mouse button causes the button to repaint itself using 3D-style shading to appear as if its been depressed. Releasing the mouse button restores the original appearance and sends a WM_COMMAND message to the parent window with the notification code BN_CLICKED. As with the other button types, when a push button has the input focus, a dashed line surrounds the text and pressing and releasing the Spacebar has the same effect as pressing and releasing the mouse button . We can simulate a push-button flash by sending the window a BM_SETSTATE message. This causes the button to be depressed: SendMessage (hwndButton. BM_SETSTATE. 1, 0); This call causes the button to return to normal: SendMessage (hwndButton. BM_SETSTATE, 0. 0);
The hwndButton window handle is the value returned from the Create Window call. We can also send a BM_GETSTATE message to a push button. The child window control returns the current state of the button: TRUE if the button is depressed and FALSE if it isnt depressed. Most applications do not require this information, however. And because push buttons do not retain any on/off information, the BM_SETCHECK and BM_GETCHECK messages are not used.
SJCET, PALAI
Module I
R704
Check Boxes
A check box is a square box with text; the text usually appears to the right of the check boxCheck boxes are usually incorporated in an application to allow a user to select options. The check box commonly functions as a toggle switch: clicking the box once causes a check mark to appear; clicking again toggles the check mark off. The two most common styles for a check box are BS_CHECKBOX and BS_AUTOCHECKBOX. When you use the BS_CHECKBOX style, you must set the check mark yourself by sending the control a BM_SETCHECK message. The wParam parameter is set to 1 to create a check mark and to 0 to remove it. You can obtain the current check state of the box by sending the control a BM_GETCHECK message. You might use code like this to toggle the X mark when processing a WM_COMMAND message from the control: SendMessage ((HWND) lParam, BM_SETCHECK, (WPARAM) !SendMessage ((HWND) Param, BM_GETCHECX, 0, 0), 0) ; Notice the operator in front of the second SendMessage call. The lParam value is the child window handle that is passed to your window procedure in the WM_COMMAND message. When you later need to know the state of the button, send it another BM_ GETCHECK message. Or you can retain the current check state in a static variable in your window procedure. You can also initialize a BS_CHECKBOX check box with a check mark by sending it a BM_SETCHECK message: SendMessaqe (hwndButton. BM_SETCHECK, 1,0) ; For the BS_AUTOCHECKBOX style, the button control itself toggles the check mark on and off. Your window procedure can ignore WIVLCOMMAND messages. When you need the current state of the button, send the control a BM_GETCHECK message: iCheck = (int) SendMessage (hwndButton, BM_GETCHECK, 0, 0); The value of iCheck is TRUE or nonzero if the button is checked and FALSE or 0 if not. The other two check box styles are BS_3STATE and BS_AUTO3STATE. As their names indicate, these styles can display a third state as wella gray color within the check box which occurs when you send the control a WM_SETCHECK message with wParam equal to 2. The gray color indicates to the user that the selection is indeterminate or irrelevant. The check box is aligned with the rectangles left edge and is centered within the top and bottom dimensions of the rectangle that were specified during the Create Window call. Clicking anywhere within the rectangle causes a WM_COMMAND message to be sent to the parent. The minimum height for a check box is one character height. The minimum width is the number of characters in the text, plus two.
Radio Buttons
A radio button is named after the row of buttons that were once quite common on car radios. Each button on a car radio is set for a different radio station, and only one button can be pressed at a time. In dialog boxes, groups of radio buttons are conventionally used to indicate mutually exclusive options. Unlike check boxes, radio buttons do not work as togglesthat is, when you click a radio button a second time, its state remains unchanged. The radio button looks very much like a check box except that it contains a little circle rather Department of Computer Science and Engineering SJCET, PALAI
Module I
R704
than a box. A heavy dot within the circle indicates that the radio button has been checked. The radio button has the window style BS_RADIOBUITON or BS_ AUTORADIOBUTTON, but the latter is used only in dialog boxes. When you receive a WM_COMMAND message from a radio button, you should display its check by sending it a BM_SETCHECK message with wParam equal to 1: SendMessage (hwndButton. BM_SETCHECK,1, 0) ; For all other radio buttons in the same group, you can turn off the checks by sending them BM_SETCHECK messages with wParam equal to 0: SendMessage (hwndButton, BM_SETCHECK, 0, 0);
Group Boxes
The group box, which has the BS_GROUPBOX style, is an oddity in the button class. It neither processes mouse or keyboard input nor sends WM_COMMAND messages to its parent. The group box is a rectangular outline with its window text at the top. Group boxes are often used to enclose other button controls.
SJCET, PALAI
Module I
R704
You can determine if a child window is visible by a call to IsWindowVisible(hwndChild); You can also enable and disable a child window. By default, a window is enabled. You can disable it by calling: EnableWindow (hwndChild, FALSE); For button controls, this call has the effect of graying the button text string. The button no longer responds to mouse or keyboard input. This is the best method for indicating that a button option is currently unavailable.
You can determine whether a child window is enabled by calling IsWindowEnabled (hwndChild);
SJCET, PALAI
Module I
R704
Question Bank :
Short Questions 1.Explain the concept of windows programming? 2.Explain message loop? 3. Write how windows provide multitasking? 4. How windows differ from ordinary programming? 5. What are messages? 6.Explain how message passing allows windows to be multitasking? 7.Explain the role of DLL in windows programming? 8.What are the advantages provide by windows to the users and programmers? 9.What are the functions of windows message system? 10.Diffrentiate between Windows API and MFC programming? Essays 1.Describe in detail the components of windows API? 2.Explain the following: a)winmain function b)Menus and buttons 3.Explain in detail the event driven programming? 4.Explain the frame windows object with an example the usage? 5.What is device context ? How it is used for text and graphics? 6.What is an application object ? 7.What are window classes ? Explain the object oriented programming in window. 8.Advantages for users and programmers by using windows programming ? 9.What are menus? Discuss the features of menus. 10.What is message loop ? Explain the use in windows programming
SJCET, PALAI