module 1ase

Upload: priya-raju

Post on 05-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Module 1ase

    1/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    MODULE 1

    The Windows Programming Model

    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 theconditions 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, butultimately 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 windowprocedure. 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 userselected 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.

  • 7/31/2019 Module 1ase

    2/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    Figure 1-1.The Windows programming model.

  • 7/31/2019 Module 1ase

    3/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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. APIfunctions 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 switchstatement 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 anAPI function named DefWindowProc, which provides default responses to unprocessed

    messages.

    Messages, Messages, and More Messages

    Where do messages come from, and what kinds of information do they convey? Windows

    defines hundreds of different message types. Most messages have names that begin with the

    letters "WM" and an underscore, as in WM_CREATE and WM_PAINT. These messages can be

    classified in various ways, but for the moment classification is not nearly as important asrealizing the critical role messages play in the operation of an application. The following table

    shows 10 of the most common messages. A window receives a WM_PAINT message, forexample, when its interior needs repainting. One way to characterize a Windows program is to

    think of it as a collection of message handlers. To a large extent, it is a program's unique way of

    responding to messages that gives it its personality.

    Common Windows Messages

    Message Sent When

    WM_CHAR A character is input from the keyboard.

    WM_COMMAND The user selects an item from a menu, or a control sends a

    notification to its parent.

    WM_CREATE A window is created.

    WM_DESTROY A window is destroyed.

    WM_LBUTTONDOWN The left mouse button is pressed.

    WM_LBUTTONUP The left mouse button is released.

    WM_MOUSEMOVE The mouse pointer is moved.WM_PAINT A window needs repainting.

    WM_QUIT The application is about to terminate.

    WM_SIZE A window is resized.

  • 7/31/2019 Module 1ase

    4/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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, amessage 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 holdsa 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 itneeds to process the WM_LBUTTONDOWN message.

    Components of Windows API

    Windows OS has three major components : user, Graphics Devices Interface(GDI) and

    kernel.

    User is a module of code that services input devices such as keyboard. GDI is a module of code that services output to graphics devices-screens, printers etc. Kernel services file management and internal memory management.

    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 theapplication. The API DLLs are normally found in the windows os directory (usuallyC:\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.

    Distinction with ordinary programs-Event driven Programming

    In the traditional procedural programming model, the flow of program execution follows apredefined path set down by the programmer. Windows programming is different, it is event

    driven.

  • 7/31/2019 Module 1ase

    5/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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 likefile 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 thisinitialization 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

    Windows Programming, SDK-Style

    If you haven't programmed Windows in C before, it's instructive to see what the source code for

    a simple program looks like. The program listed in Figure 1-2 creates a window and responds toWM_PAINT messages by drawing an ellipse in the window's upper left corner. This code is

    similar to the source code you'll find in books such as Charles Petzold's Programming Windows(1998, Microsoft Press) and other books that teach Windows programming in C.

    Figure 1-2.C source code for a simple Windows program.

    #include

    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 colorwc.lpszMenuName = NULL; // Menu name

    wc.lpszClassName = "MyWndClass"; // WNDCLASS name

    RegisterClass (&wc);

    hwnd = CreateWindow (

    "MyWndClass", // WNDCLASS name

  • 7/31/2019 Module 1ase

    6/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    "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 windowNULL, // 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);

    }

  • 7/31/2019 Module 1ase

    7/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    WinMain Function

    Just as the entry point to a C program is the function main ,the entry point a Windows program isWinMain ,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 WindowsProgramming 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.

    Registering And Creating Windows

    WinMain begins by calling the API function RegisterClass to register a window class. The

    window class defines important characteristics of a window such as its window procedure

    address, its default background color, and its icon. These and other properties are defined byfilling in the fields of a WNDCLASS structure, which is subsequently passed toRegisterClass.

    An application must specify a window class when it creates a window, and a class must be

    registered before it can be used. That's whyRegisterClass is called at the outset of the program.Keep in mind that a WNDCLASS-type window class is not the same as a C++ window class. To

    avoid confusion, I'll use the term WNDCLASS throughout this book to refer to classes registered

    withRegisterClass. The term window class will refer to C++ classes derived from MFC's CWndclass.

    Once the WNDCLASS is registered, WinMain calls the all-important CreateWindow function tocreate the application's window. The first parameter to CreateWindow is the name of the

    WNDCLASS from which the window will be created. The second parameter is the text that willappear in the window's title bar. The third specifies the window style.WS_OVERLAPPEDWINDOW is a commonly used style that creates a top-level window with a

    resizing border, a title bar, a system menu, and buttons for minimizing, maximizing, and closing

    the window.

    The next four parameters specify the window's initial position and size. CW_USEDEFAULT

    tells Windows to use default values for both. The final four parameters specify, in order, the

  • 7/31/2019 Module 1ase

    8/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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 (avalue 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 aWinMain function (at least not one you can see), and it doesn't call RegisterClass or

    CreateWindow.

    Displaying the Window

    The window that CreateWindow creates is not initially visible on the screen because it was not

    created with the WS_VISIBLE style. (Had it been used, WS_VISIBLE would have beencombined with WS_OVERLAPPEDWINDOW in the call to CreateWindow.) Therefore,

    WinMain follows CreateWindow with calls to ShowWindow and UpdateWindow, which make

    the window visible and ensure that its WM_PAINT handler is called immediately.

    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 APIfunctions 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, whosefields 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 andWM_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 EndPaintAPI function to releasethe handle when painting is finished. In between, theEllipse API function draws an ellipse that is

    200 pixels wide and 100 pixels high. A device context handle is the "magic cookie" that permitsa Windows application to draw on the screen. Without it, functions such asEllipse 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. TheWM_DESTROY message is sent to a window just before it is destroyed. A top-level window

  • 7/31/2019 Module 1ase

    9/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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. Windowssends 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 aparticular window class registered by the Register Class. A window procedure is always defined

    like this:

    LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM

    wParam,LPARAM lParam)

    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 thatidentifies the message.

    The last two parameters are 32-bit message parameter that provides more information about themessage. What theses parameters contain is specific to each type of message

    Processing the messages

    Every message that a window procedure receives is identified by a number, which is the message

    parameter to the window procedure .The windows header file WINUSER.H defines identifiers

    beginning with the prefix WM(window message) for each type of message.

    Generally, windows programmers use a switch and case construction to determine what message

    the window procedure is receiving and how to process it accordingly. When a window procedureprocesses a message, it should return 0 from the window procedure. All messages that a window

    procedure chooses not to process must be passed to a windows function named DefWindowProc.

    The value returned from DefWindowProc must be returned from the window procedure.

    The window procedure is structured like this:

    Switch(imsg)

    {

  • 7/31/2019 Module 1ase

    10/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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);

    Hungarian Notation and Windows Data Types

    Another aspect of Figure 1-2 that deserves mentioning is the variable naming convention that it

    uses. Veteran Windows programmers know it as Hungarian notation, in which each variablename begins with one or more lowercase characters identifying the variable's type: h for handle,

    n for integer, and so on. The table below lists some of the commonly used Hungarian prefixes.

    Prefixes are often combined to form other prefixes, as when p and sz are joined to form psz,

    which stands for "pointer to zero-terminated string."

    Many of the data types shown in this table aren't standard C/C++ data types but rather are

    "special" data types defined in the Windows header files. COLORREF, for example, is theWindows data type for 24-bit RGB color values. A BOOL is a Boolean data type that stores

    TRUE/FALSE values, while a DWORD is a 32-bit unsigned integer. Over time, you'll come to

    know these data types as well as you know your compiler's native data types.

  • 7/31/2019 Module 1ase

    11/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    Common Hungarian Notation Prefixes

    Prefix Data Type

    b BOOL

    c or ch char

    clr COLORREF

    cx, cy Horizontal or vertical distance

    dw DWORD

    h Handle

    l LONG

    n int

    p Pointer

    sz Zero-terminated string

    w WORD

    Most MFC programmers use Hungarian notation, too. Glance through the source code for a

    typical MFC program and you'll see hundreds ofhs and lps and other familiar prefixes as well as

    prefixes representing MFC's own data types (for example, wnd for CWnd variables). It's alsocommon 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 abideby 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 Windowsprograms 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 thefar left of the caption bar, a display of the programs small icon. This icon invokes the system

  • 7/31/2019 Module 1ase

    12/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    mend, which is really another popup menu.

    Menu items in popups can be checked, which means that Windows draws a small check markto 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. Top-

    level menu items cannot be checked.

    Menu items in the top-level menu or in popup menus can be enabled, disabled or grayed. Thewords 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 isdisplayed 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 thereverse-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 currentlyvalid. 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 thirdcharacteristic describes the attribute of the menu item, including whether the item is, disabled,

    grayed, or checked.

    Defining the Menu

    To use Developer Studio to add a menu to your programs resource script, select Resource fromthe Insert menu and pick Menu. (But you probably figured that out already.) You can theninteractively define your menu. Each item in the menu has an associated Menu kern Properties

    dialog box that indicates the items text string. If the Pop-up box is checked, the item invokes a

    popup menu and no ID is associated with the item. If the Pop-up box is not checked, the item

    generates a WM_COMMAND message with a specified ID. These two types of menu items willappear in the resource script as POPUP and MENUITEM statements, respectively.

    When you type the text for an item in a menu, you can type an ampersand (&) to indicate that the

    following character is to be underlined when Windows displays the menu. Such an underlinedcharacter is the character Windows searches for when you select a menu item using the Alt key.

    If you dont include an ampersand in the text, no underline will appear, and Windows will

    instead use the first letter of the menu items text for Alt-key searches.If you select the Grayed option in the Menu Items Properties dialog box, the menu item is

  • 7/31/2019 Module 1ase

    13/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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_COMMANDmessage 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 thelongest 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-justifiesthe 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 theprogram as the name of the menu so that the same character string can be used for the windowclass, the name of the programs icon, and the name of the menu. The program then makesreference 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 theLoadMenu function, which is similar to theLoadicon andLoadCursorfunctions 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, theLoadMenu 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);

  • 7/31/2019 Module 1ase

    14/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    In this case, the menu specified in the Create Window call overrides any menu specified in thewindow 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 theCreate Window call and assign a menu to a window after the window has been created:

    SetMenu (hwnd. hMenu) ;

    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 passthem toDefWindowProc. One such message is WMJNITMENU with the following parameters:

    wParam: Handle to main menu

    lParam: 0

    The value ofwParam 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 indexHIWORD (wParam): Selection flags

    IParam: Handle to menu containing selected item

  • 7/31/2019 Module 1ase

    15/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    WM_MENUSELECT is a menu-tracking message. The value ofwParam tells you what item of

    the menu is currently selected (highlighted). The selection flags in the high word ofwParamcan 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 thismessage toDeJWindowProc.

    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 handleLOWORD (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 thatpopup, 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 childwindow controls, you can differentiate between them by examining the value ofIParam, 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 IDIParam: 0

  • 7/31/2019 Module 1ase

    16/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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 bemasked 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 orSC_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 toDefWindowProc. If you donot, 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 toDefWindowProc, which normally returns a 0 toWindows, which causes Windows to beep.

  • 7/31/2019 Module 1ase

    17/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    BUTTONS

    The child window procedure can determine the window handle of its parent by calling GetPa

    rent,

    hwndParent = GetParent (hwnd);

    where hwndis 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 couldthen 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 forthe 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.

    Creating the Child Windows

    The button window styles all begin with the letters BS, which stand for button style. The 10

    button child windows are created in a for loop during WM_CREATE message processing in

    WndProc. The Create Window call uses the following parameters:

    Class name TEXT (button)

    Window text button[1].szText

    Window style US_CHILD US_VISIBLE button[i].iStylex position cxChar

    y position cyChar (1 + 2 * i)

    Width 20 * xCharHeight 7 * yChar / 4

    Parent window hwnd

    Child window ID (HMENU) iInstance 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.

  • 7/31/2019 Module 1ase

    18/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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 andheight 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. WhileGefDialogBaseUnits returns roughly the same values as can be obtained from (he

    GetTextMetrics function, its somewhat easier to use and will ensure more consistency withcontrols 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 fromit. 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 messageIParam is actually a pointer to astructure of type CREATESTRUCT (creation structure) that has a member hinstance. So we

    cast iParam into a pointer to a CREATESTRUCT structure and get hinstancout.(Some Windows programs use a global variable named hlnstto give window procedures accessto the instance handle available in WinMain. In WinMain, you need to simply set

    hInst = hlnstance before creating the main window.

    The Child Talks to Its Parent

    When you click a button with the mouse, the child window control sends a WM_COMMANDmessage to its parent window.

    LOWORD (wParam): Child window IDHIWORD (wParam): Notification code

    lParam: Child window handle

    The child window ID is the value passed to Create Window when the child window is created.

    The child window handle is the value that Windows returns from the Create Window call.

    The notification code indicates in more detail what the message means. The possiblevalues of button notification codes are defined in the Windows header files:

  • 7/31/2019 Module 1ase

    19/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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 7are sent only if the button style includes the flag BSNOTIFY, The

    notification code 5 is sent only for BS_RADIOBUTrON, BS_AUTORADIOBUTrON, andBS_OWNERDRAW buttons, or for other buttons if the button style includes BS_NOTIFY.

    The Parent Talks to Its Child

    A window procedure can send messages to the child window control. These messages includemany of the window messages beginning with the prefix WM. In addition, eight button-specific

    messages are defined in WTNUSER.H; each begins with the letters BM, which stand for button

    message. These button messages are shown in the following table:

    The BM_GETCHECK and BM_SETCHECK messages are sent by a parent window to a childwindow control to get and set the check mark of check boxes and radio buttons. TheBM_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.

  • 7/31/2019 Module 1ase

    20/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    Each child window has a window handle and an ID that is unique among its siblings. Knowingone 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 windowis created.

    Push Buttons

    A push button is a rectangle enclosing text specified in the window text parameter of the CreateWindow call. The rectangle takes up the full height and width of the dimensions given in the

    Create Window orMoveWindow 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 andBS_DEFPUSHBUTTON controls function differently from one another. When used as child

    window controls, however, the two types of push buttons function the same way, althoughBS_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 theparent 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. Thiscauses 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 isntdepressed. 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.

  • 7/31/2019 Module 1ase

    21/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    Check Boxes

    A check box is a square box with text; the text usually appears to the right of the checkboxCheck 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 andBS_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 thebox 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 thecurrent 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 boxwhich 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. Theminimum 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 mutuallyexclusive 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

  • 7/31/2019 Module 1ase

    22/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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 thelatter 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 neitherprocesses 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.

    Changing the Button Text

    You can change the text in a button (or in any other window) by calling Set WindowText:

    SetWindowText (hwnd. pszString) ;where hwndis a handle to the window whose text is being changed andpszString is a pointer to a

    null-terminated string. For a normal window, this text is the text of the caption bar, For a button

    control, its the text displayed with the button.You can also obtain the current text of a window:

    iLengtb = GetWindowText (hwnd,pszBuffer, iMaxLength);

    The iMaxlength parameter specifies the maximum number of characters to copy into the buffer

    pointed to bypszBuffer. The function returns the string length copied. You can prepare yourprogram for a particular text length by first calling

    iLength = GetWindowTextLength (hwnd) ;

    Visible and Enabled Buttons

    To receive mouse and keyboard input, a child window must be both visible (displayed) andenabled. When a child window is visible but not enabled, Windows displays the text in grayrather than black.

    If you dont include WS_VISIBLE in the window class when creating the child window, the

    child window will not be displayed until you make a call to Show Window:

    ShowWindow (hwndChild, SW_SHOWNORMAL);

    But if you include WS_VISIBLE in the window class, you dont need to call Show Window.However, you can hide the child window by this call to ShowWindow:

    ShowWindow (hwndChild, SW_HIDE);

  • 7/31/2019 Module 1ase

    23/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET, PALAI

    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 candisable it by calling:EnableWindow (hwndChild, FALSE);

    For button controls, this call has the effect of graying the button text string. The button no longerresponds to mouse or keyboard input. This is the best method for indicating that a button option

    is currently unavailable.

    You can re enable a child window by calling:

    EnableWindow (hwndChild, TRUE);

    You can determine whether a child window is enabled by callingIsWindowEnabled (hwndChild);

  • 7/31/2019 Module 1ase

    24/24

    Module I R704 Advanced Software Environments

    Department of Computer Science and Engineering SJCET PALAI

    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 buttons3.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