Docsity

Windows Class and Creation: Attributes, Procedures, and Message Handling, Study notes of Windows Programming

Toggle sidebar
bg1
Windows Creation and Message Handling 2
9.1 Multiple Instances
Every running application is an Application Instance. So if you open more than one
application, more than one instance will be running simultaneously. If you write a
program and run it, this running program will be known as a process running in memory.
Whenever you press ALT-CONTROL-DELETE, you can open Task Manager to watch
all the processes present in task list, running under Windows. Each process can have one
or more than one windows. Every process has at least one thread running, which is UI
thread.
9.2 Window Class
Every window in Windows has its own registered Window class. This window class has
set of attributes which are later used by windows. These attributes could be windows
background brush, windows style, cursors, Icons, etc. So Windows class tells the
Operating system about the characteristics and physical layout of its windows. Window
Class is simply a structure named WNDCLASS or WNDCLASSEX that only contains
set of attributes for window.
Each window class has an associated window procedure shared by all windows of the
same class. The window procedure processes messages for all windows of that class and
therefore, controls their behavior and appearance. For more information, see Window
Procedures.
A process must register a window class before it creates a window. Registering a window
class associates a window procedure, class styles and other class attributes particularly a
class name. When a process specifies a class name in the CreateWindow or
CreateWindowEx function, the system creates a window using a registered class name.
A window class defines the attributes of a window such as style, icon, cursor, menu, and
window procedure. The first step in registering a window class is to fill a WNDCLASS
structure. For more information, see Elements of a Window Class. Next step is to pass the
structure to the RegisterClass function.
To register an application global class, specify the CS_GLOBALCLASS style in the
style member of the WNDCLASSEX structure. When registering an application local
class, do not specify the CS_GLOBALCLASS style.
If you register the window class using the ANSI version of RegisterClassEx,
RegisterClassExA, the application requests that the system pass text parameters of
messages to the windows of the created class using the ANSI character set; if you register
the class using the Unicode version of RegisterClassEx, RegisterClassExW, the
application requests that the system pass text parameters of messages to the windows of
the created class using the Unicode character set. The IsWindowUnicode function enables
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Windows Class and Creation: Attributes, Procedures, and Message Handling and more Study notes Windows Programming in PDF only on Docsity!

9.1 Multiple Instances

Every running application is an Application Instance. So if you open more than one

application, more than one instance will be running simultaneously. If you write a

program and run it, this running program will be known as a process running in memory.

Whenever you press ALT-CONTROL-DELETE, you can open Task Manager to watch

all the processes present in task list, running under Windows. Each process can have one

or more than one windows. Every process has at least one thread running, which is UI

thread.

9.2 Window Class

Every window in Windows has its own registered Window class. This window class has

set of attributes which are later used by windows. These attributes could be windows

background brush, windows style, cursors, Icons, etc. So Windows class tells the

Operating system about the characteristics and physical layout of its windows. Window

Class is simply a structure named WNDCLASS or WNDCLASSEX that only contains

set of attributes for window.

Each window class has an associated window procedure shared by all windows of the same class. The window procedure processes messages for all windows of that class and therefore, controls their behavior and appearance. For more information, see Window Procedures.

A process must register a window class before it creates a window. Registering a window class associates a window procedure, class styles and other class attributes particularly a class name. When a process specifies a class name in the CreateWindow or CreateWindowEx function, the system creates a window using a registered class name.

A window class defines the attributes of a window such as style, icon, cursor, menu, and window procedure. The first step in registering a window class is to fill a WNDCLASS structure. For more information, see Elements of a Window Class. Next step is to pass the structure to the RegisterClass function.

To register an application global class, specify the CS_GLOBALCLASS style in the style member of the WNDCLASSEX structure. When registering an application local class, do not specify the CS_GLOBALCLASS style.

If you register the window class using the ANSI version of RegisterClassEx , RegisterClassExA , the application requests that the system pass text parameters of messages to the windows of the created class using the ANSI character set; if you register the class using the Unicode version of RegisterClassEx , RegisterClassExW , the application requests that the system pass text parameters of messages to the windows of the created class using the Unicode character set. The IsWindowUnicode function enables

applications to query the nature of each window. For more information on ANSI and Unicode functions, see Conventions for Function Prototypes in Microsoft help documents.

The executable or DLL that registered the class is the owner of the class. The system determines class ownership from the hInstance member of the WNDCLASSEX structure passed to the RegisterClassEx function when the class is registered. For DLLs, the hInstance member must be the handle to the .dll instance.

Windows 2000 or Above: The class is not destroyed when the .dll that owns it is unloaded. Therefore, if the system calls the window procedure for a window of that class, it will cause an access violation, because the .dll containing the window procedure is no longer in memory. The process must destroy all windows using the class before the .dll is unloaded and call the UnregisterClass function.

ATOM RegisterClass(

CONST WNDCLASS *lpWndClass

) The complete description its parameters can be found from Microsoft Developer Network

BOOL UnregisterClass( LPCTSTR lpClassName , HINSTANCE hInstance );

The complete description its parameters can be found from Microsoft Developer Network

This function inputs a pointer to CONST WNDCLASS structure and returns ATOM.

ATOM is a unique identifier that will be returned from RegisterClass. ATOM is unsigned

short value.

9.3 Elements of a Window Class

The elements of a window class define the default behavior of windows belonging to the class. The application that registers a window class assigns elements to the class by setting appropriate members in a WNDCLASSEX structure and passing the structure to the RegisterClassEx function. The GetClassInfoEx and GetClassLong functions retrieve information about a given window class. The SetClassLong function changes elements of a local or global class that the application has already registered.

and can use it for any application-defined purpose. The system initializes this memory to zero.

Extra Window Memory

Specifies the amount of extra memory, in bytes, that the system should reserve for each window belonging to the class. The extra memory can be used for any application-defined purpose. The system initializes this memory to zero.

9.3.1 Class Name

Every window class needs a Class Name to distinguish one class from another. Assign a class name by setting the lpszClassName member of the WNDCLASSEX structure to the address of a null-terminated string that specifies the name. Because window classes are process specific, window class names need to be unique only within the same process. Also, because class names occupy space in the system's private ATOM table, you should keep class name strings as short a possible.

The GetClassName function retrieves the name of the class to which a given window belongs.

9.3.2 Window Procedure Address

Every class needs a window-procedure address to define the entry point of the window procedure used to process all messages for windows in the class. The system passes messages to the procedure when it requires the window to carry out tasks, such as painting its client area or responding to input from the user. A process assigns a window procedure to a class by copying its address to the lpfnWndProc member of the WNDCLASSEX structure. For more information, see Window Procedures.

9.3.3 Instance Handle

Every window class requires an instance handle to identify the application or .dll that registers the class. The system requires instance handles to keep track of all modules. The system assigns a handle to each copy of a running executable or .dll.

The system passes an instance handle to the entry-point function of each executable. The executable or .dll assigns this instance handle to the class by copying it to the hInstance member of the WNDCLASSEX structure.

9.3.4 Class Cursor

The class cursor defines the shape of the cursor when it is in the client area of a window in the class. The system automatically sets the cursor to the given shape when the cursor enters the window's client area and ensures it keeps that shape while it remains in the client area. To assign a cursor shape to a window class, load a predefined cursor shape by using the LoadCursor function and then assign the returned cursor handle to the hCursor

member of the WNDCLASSEX structure. Alternatively, provide a custom cursor resource and use the LoadCursor function to load it from the application's resources.

The system does not require a class cursor. If an application sets the hCursor member of the WNDCLASSEX structure to NULL, no class cursor is defined. The system assumes the window sets the cursor shape each time the cursor moves into the window. A window can set the cursor shape by calling the SetCursor function whenever the window receives the WM_MOUSEMOVE message.

9.3.5 Class Icons

A class icon is a picture that the system uses to represent a window of a particular class. An application can have two class icons — one large and one small. The system displays a window's large class icon in the Task-switch window that appears when the user presses ALT+TAB, and in the large icon views of the task bar and explorer. The small class icon appears in a window's title bar and in the small icon views of the task bar and explorer.

To assign a large and small icon to a window class, specify the handles of the icons in the hIcon and hIconSm members of the WNDCLASSEX structure. The icon dimensions must conform to required dimensions for large and small class icons. For a large class icon, you can determine the required dimensions by specifying the SM_CXICON and SM_CYICON values in a call to the GetSystemMetrics function. For a small class icon, specify the SM_CXSMICON and SM_CYSMICON values.

If an application sets the hIcon and hIconSm members of the WNDCLASSEX structure to NULL, the system uses the default application icon as the large and small class icons for the window class. If you specify a large class icon but not a small one, the system creates a small class icon based on the large one. However, if you specify a small class icon but not a large one, the system uses the default application icon as the large class icon and the specified icon as the small class icon.

You can override the large or small class icon for a particular window by using the WM_SETICON message. You can retrieve the current large or small class icon by using the WM_GETICON message.

9.3.6 Class Background Brush

A class background brush prepares the client area of a window for subsequent drawing by the application. The system uses the brush to fill the client area with a solid color or pattern, thereby removing all previous images from that location whether they belong to the window or not. The system notifies a window that its background should be painted by sending the WM_ERASEBKGND message to the window.

To assign a background brush to a class, create a brush by using the appropriate GDI functions and assign the returned brush handle to the hbrBackground member of the WNDCLASSEX structure.

Style Action

CS_BYTEALIGNCLIENT

Aligns the window's client area on a byte boundary (in the x direction). This style affects the width of the window and its horizontal placement on the display.

CS_BYTEALIGNWINDOW

Aligns the window on a byte boundary (in the x direction). This style affects the width of the window and its horizontal placement on the display.

CS_CLASSDC

Allocates one device context to be shared by all windows in the class. Because window classes are process specific, it is possible for multiple threads of an application to create a window of the same class. It is also possible for the threads to attempt to use the device context simultaneously. When this happens, the system allows only one thread to successfully finish its drawing operation.

CS_DBLCLKS

Sends a double-click message to the window procedure when the user double-clicks the mouse while the cursor is within a window belonging to the class.

CS_DROPSHADOW

Windows XP: Enables the drop shadow effect on a window. The effect is turned on and off through SPI_SETDROPSHADOW. Typically, this is enabled for small, short-lived windows such as menus to emphasize their Z order relationship to other windows.

CS_GLOBALCLASS Specifies that the window class is an application global class. For more information.

CS_HREDRAW Redraws the entire window if a movement or size adjustment changes the width of the client area.

CS_NOCLOSE Disables Close on the window menu.

CS_OWNDC Allocates a unique device context for each window in the class.

CS_PARENTDC

Sets the clipping rectangle of the child window to that of the parent window so that the child can draw on the parent. A window with the CS_PARENTDC style bit receives a regular device context from the system's cache of device contexts. It does not give the child the parent's device context or device context settings. Specifying CS_PARENTDC enhances an application's performance.

CS_SAVEBITS

Saves, as a bitmap, the portion of the screen image obscured by a window of this class. When the window is removed, the system uses the saved bitmap to restore the screen image, including other windows that were obscured. Therefore, the system does not send WM_PAINT messages to windows that were obscured if the memory used by the bitmap has not been discarded and if other screen actions have not invalidated the stored image.

This style is useful for small windows (for example, menus or dialog boxes) that are displayed briefly and then removed before other screen activity takes place. This style increases the time required to display the window, because the system must first allocate memory to store the bitmap.

CS_VREDRAW Redraws the entire window if a movement or size adjustment changes the height of the client area.

9.4 Using Window Class ( Example )

#include <windows.h>

// Declaration of Global variable

HINSTANCE hinst;

// Function prototypes.

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE

hInstPrev, LPSTR str, int cmd);

InitApplication(HINSTANCE);

InitInstance(HINSTANCE, int);

LRESULT CALLBACK MainWndProc(HWND, UINT, WPARAM,

LPARAM);

// Application entry point.

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE

hInstPrev, LPSTR str, int cmd)

MSG msg;

if (!InitApplication(hinstance))

return FALSE;

return 0;

//Initialize Application by registering class

BOOL InitApplication(HINSTANCE hinstance)

WNDCLASSEX wcx;

// Fill in the window class structure with

//parameters

// that describe the main window.

9.5 About Windows

Every graphical Microsoft® Windows®-based application creates at least one window, called the main window that serves as the primary interface between the user and the application. Most applications also create other windows, either directly or indirectly, to perform tasks related to the main window. Each window plays a part in displaying output and receiving input from the user.

When you start an application, the system also associates a taskbar button with the application. The taskbar button contains the program icon and title. When the application is active, its taskbar button is displayed in the pushed state.

An application window includes elements such as a title bar, a menu bar, the window menu (formerly known as the system menu), the minimize button, the maximize button, the restore button, the close button, a sizing border, a client area, a horizontal scroll bar, and a vertical scroll bar. An application's main window typically includes all of these components. The following illustration shows these components in a typical main window.

9.5.1 Client Area

The client area is the part of a window where the application displays output, such as text or graphics. For example, a desktop publishing application displays the current page of a document in the client area. The application must provide a function, called a window procedure, to process input to the window and display output in the client area.

9.5.2 Nonclient Area

The title bars, menu bar, window menu, minimizes and maximize buttons, sizing border, and scroll bars are referred to collectively as the window's nonclient area. The system

manages most aspects of the nonclient area, and the application manages the appearance and behavior of its client area.

The title bar displays an application-defined icon and line of text; typically, the text specifies the name of the application or indicates the purpose of the window. An application specifies the icon and text when creating the window. The title bar also makes it possible for the user to move the window by using a mouse or other pointing device.

Most applications include a menu bar that lists the commands supported by the application. Items in the menu bar represent the main categories of commands. Clicking an item on the menu bar typically opens a pop-up menu whose items correspond to the tasks within a given category. By clicking a command, the user directs the application to carry out a task.

The window menu is created and managed by the system. It contains a standard set of menu items that, when chosen by the users, sets a window’s size or position, closes the application, or performs tasks.

The buttons in the upper-right corner affect the size and position of the window. When you click the maximize button , the system enlarges the window to the size of the screen and positions the window, so it covers the entire desktop, minus the taskbar. At the same time, the system replaces the maximize button with the restore button. When you click the restore button , the system restores the window to its previous size and position. When you click the minimize button , the system reduces the window to the size of its taskbar button, positions the window over the taskbar button, and displays the taskbar button in its normal state. To restore the application to its previous size and position, click its taskbar button. When you click the close button , application exits.

The sizing border is an area around the perimeter of the window that enables the user to size the window by using a mouse or other pointing device.

The horizontal scroll bar and vertical scroll bar convert mouse or keyboard input into values that an application uses to shift the contents of the client area either horizontally or vertically. For example, a word-processing application that displays a lengthy document typically provides a vertical scroll bar to enable the user to page up and down through the document.

9.6 Prototype of CreateWindow

Here is a prototype of CreateWindow Function.

HWND CreateWindow(

LPCTSTR lpClassName; //class name (identification) LPCTSTR lpWindowName; //Window caption bar Name DWORD dwStyle; // style of the windows Int x; //starting X point of window on screen

cannot have a menu bar. This style cannot be used with the WS_POPUP style.

WS_CHILDWINDOW Same as the WS_CHILD style.

WS_CLIPCHILDREN Excludes the area occupied by child windows when drawing occurs within the parent window. This style is used when creating the parent window.

WS_CLIPSIBLINGS Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of a child window, to draw within the client area of a neighboring child window.

WS_DISABLED Creates a window that is initially disabled. A disabled window cannot receive input from the user. To change this after a window has been created, use EnableWindow.

WS_DLGFRAME Creates a window that has a border of a style typically used with dialog boxes. A window with this style cannot have a title bar.

WS_GROUP Specifies the first control of a group of controls. The group consists of this first control and all controls defined after it, up to the next control with the WS_GROUP style. The first control in each group usually has the WS_TABSTOP style so that the user can move from group to group. The user can subsequently change the keyboard focus from one control in the group to the next control in the group by using the direction keys.

You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use SetWindowLong.

WS_HSCROLL Creates a window that has a horizontal scroll bar.

WS_ICONIC Creates a window that is initially minimized. Same as the WS_MINIMIZE style.

WS_MAXIMIZE Creates a window that is initially maximized.

WS_MAXIMIZEBOX Creates a window that has a maximize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified.

WS_MINIMIZE Creates a window that is initially minimized. Same as the WS_ICONIC style.

WS_MINIMIZEBOX Creates a window that has a minimize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified.

WS_OVERLAPPED Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_TILED style.

WS_OVERLAPPEDWINDOW Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_TILEDWINDOW style.

WS_POPUP Creates a pop-up window. This style cannot be used with the WS_CHILD style.

WS_POPUPWINDOW Creates a pop-up window with WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible.

WS_SIZEBOX Creates a window that has a sizing border. Same as the WS_THICKFRAME style.

WS_SYSMENU Creates a window that has a window menu on its title bar. The WS_CAPTION style must also be specified.

WS_TABSTOP Specifies a control that can receive the keyboard focus when the user presses the TAB key. Pressing the TAB key changes the keyboard focus to the next control with the WS_TABSTOP style.

You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use SetWindowLong.

WS_THICKFRAME Creates a window that has a sizing border. Same as the WS_SIZEBOX style.

WS_TILED Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_OVERLAPPED style.

WS_TILEDWINDOW Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_OVERLAPPEDWINDOW style.

WS_VISIBLE Creates a window that is initially visible.

This style can be turned on and off by using ShowWindow or SetWindowPos

CW_USEDEFAULT is valid only for overlapped windows; if CW_USEDEFAULT is

specified for a pop-up or child window, nWidth and nHeight are set to zero.

9.6.7 Height of the Window ( nHeight )

This member specifies the height, in device units, of the window. For overlapped

windows, nHeight is the window's height, in screen coordinates.

If nWidth is set to CW_USEDEFAULT, the system ignores nHeight.

9.6.8 Parent of the Window ( hWndParent )

This member is a HANDLE to the parent or owner window of the window being created.

To create a child window or an owned window, supply a valid window handle. This

parameter is optional for pop-up windows.

9.6.9 Menu of the Window ( hMenu )

This member is a HANDLE to a menu, or specifies a child-window identifier depending

on the window style. For an overlapped or pop-up window, hMenu identifies the menu to

be used with the window; it can be NULL if the class menu is to be used. For a child

window, hMenu specifies the child-window identifier, an integer value used by a dialog

box control to notify its parent about events. The application determines the child-

window identifier; it must be unique for all child windows with the same parent window.

9.6.10 Instance Handle ( hInstance )

This member is Application instance handle.

In Windows NT/2000 or later This value is ignored.

9.6.11 Long Param ( lpParam )

This member is a pointer to a value to be passed to the window through the

CREATESTRUCT structure passed in the lParam parameter the WM_CREATE

message. If an application calls CreateWindow to create a multiple document interface

(MDI) client window, lpParam must point to a CLIENTCREATESTRUCT structure.

9.6.12 Return Value

If the CreateWindow function is successful, then it returns a valid handle of the newly

created window. Otherwise it returns NULL.

9.7 Using Windows ( Example )

HINSTANCE hinst;

HWND hwndMain;

// Create the main window.

hwndMain = CreateWindowEx(

0, // no extended styles

"MainWClass", // class name

"Main Window", // window name

WS_OVERLAPPEDWINDOW | // overlapped window

WS_HSCROLL | // horizontal scroll bar

WS_VSCROLL, // vertical scroll bar

CW_USEDEFAULT, // default horizontal

position

CW_USEDEFAULT, // default vertical

position

CW_USEDEFAULT, // default width

CW_USEDEFAULT, // default height

(HWND) NULL, // no parent or owner

window

(HMENU) NULL, // class menu used

hinstance, // instance handle

NULL); // no window creation data

if (!hwndMain)

return FALSE;

Now Show the window using the flag specified by the program that started the application, and send the application WM_PAINT message.

ShowWindow(hwndMain, SW_SHOWDEFAULT);

UpdateWindow(hwndMain);

9.8 Messages in Windows

Unlike MS-DOS-based applications, Win32®-based applications are event-driven. They

do not make explicit function calls (such as C run-time library calls) to obtain input.

Instead, they wait for the system to pass input to them. The system passes all input for an

application to the various windows in the application. Each window has a function, called

9.9.2 Message Type( uMsg )

This member specifies the message type; the message could be a Mouse message,

character message, keyboard message, etc. Message is unsigned 32bit number.

9.9.3 Message’s WPARAM( wParam )

This specifies additional message information. The contents of this parameter depend on

the value of the uMsg parameter e.g. key down message keeps the key pressed value in

this parameter.

9.9.4 Message’s LPARAM( lParam )

This specifies additional message information. The contents of this parameter depend on

the value of the uMsg parameter e.g. mouse down messages keep information of mouse

pointer’s x and y position in this parameter.

9.9.5 Return Value

The return value is the result of the message processing and depends on the message sent

function.

9.10 Getting message from Message Queue

We can get message from message Queue by using GetMessage or PeekMessage APIs.

The GetMessage function retrieves a message from the calling thread's message queue

and also removes the message from the queue. And then function dispatches incoming

sent messages until a posted message is available for retrieval.

GetMessage inputs four parameters,

BOOL GetMessage()

(

LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax

)

lpMsg

[out] Pointer to an MSG structure that receives message information from the thread's message queue.

hWnd

[in] Handle to the window whose messages are to be retrieved. The window must belong to the calling thread. The following value has a special meaning.

wMsgFilterMin

[in] Specifies the integer value of the lowest message value to be retrieved. Use WM_KEYFIRST to specify the first keyboard message or WM_MOUSEFIRST to specify the first mouse message.

wMsgFilterMax

[in] Specifies the integer value of the highest message value to be retrieved. Use WM_KEYLAST to specify the first keyboard message or WM_MOUSELAST to specify the last mouse message.

return Value

If the function retrieves a message other than WM_QUIT , the return value is

nonzero. If the function retrieves the WM_QUIT message, the return value is zero.

If there is an error, the return value is -1. For example, the function fails if hWnd is an

invalid window handle or lpMsg is an invalid pointer. To get extended error information,

use GetLastError function.

9.11 Message Dispatching

After getting message from message queue, message is dispatched to the actual window

procedure. For dispatching messages to window procedure, we use DispatchMessage

API.

DispatchMessage inputs one argument that is pointer to MSG structure.

BOOL DispatchMessage

(

MSG *lpMsg

)

Summary

In this lecture, we learnt how to Register Window class using RegisterClass API, and

how to set attributes of window class structure. After registration of Window class we

learnt to use CreateWindow API. CreateWindow API uses window class name, caption

name, style of window, starting points, width and height of windows and windows parent

handle or handle to owner mainly. We have window handle in variable of type handle to

window. Using window handle we can send different types of messages to the window.

Then we learnt how to get messages from application message queue. And after getting

messages from application message queue, we dispatch messages to the windows

message handling procedure. Windows message procedure inputs four parameters. These

parameters are also the members of MSG structure. These parameters are important for

every one who is developing applications for Windows.