unit i -windows programming

unit i -windows programming
P.S.N.A. COLLEGE OF ENGINEERING & TECHNOLOGY,
Kothandaraman Nagar, Muthanampatti(PO), Dindigul – 624 622.
Phone: 0451-2554032, 2554349
Web Link: www.psnacet.edu.in
SHORT QUESTIONS & ANSWERS
Subject code & Name: CS1253 – VISUAL PROGRAMMING
Course & Branch
: B.E [Computer Science & Engineering]
Year & Semester: II / IV
Name of the Faculty: Mr. S.K. Somasundaram, Mr. D. Suresh
UNIT I: WINDOWS PROGRAMMING
Two Mark Questions - PART A
1. Define a window
A window is a rectangular area on the screen which gets the input from the user and
displays the output in the form of text or graphics. The caption in the caption bar of the
window differentiates each window. A user can view the information on a single screen by
using scroll bars.
2. Mention the important aspect of Windows 98 and Windows NT.
Both Windows 98 and Windows NT are 32-bit preemptive multitasking and
multithreading graphical operating systems. This means programs themselves can split into
multiple threads of execution that seem to run concurrently. Windows possesses a graphical
user interface (GUI), sometimes also called a "visual interface" or "graphical windowing
environment."
3. What is GUI?
GUI stands for Graphical User Interface. All GUIs make use of graphics on a bitmapped
video display. Graphics provides better utilization of screen real estate, a visually rich
environment for conveying information, and the possibility of a WYSIWYG (what you see is
what you get) video display of graphics and formatted text prepared for a printed document.
4. What do you mean by Dynamic Link Library?
Programs running in Windows can share routines that are located in other files called
"dynamic-link libraries." Windows includes a mechanism to link the program with the routines
in the dynamic-link libraries at run time. Windows itself is basically a set of dynamic-link
libraries.
5. What is the purpose of GDI?
Programs written for Windows do not directly access the hardware of graphics display
devices such as the screen and printer. Instead, Windows includes a graphics programming
language called the Graphics Device Interface, or GDI that allows the easy display of
graphics and formatted text. Windows virtualizes display hardware.
6. Mention about windows.h header file.
WINDOWS.H is a master include file that includes other Windows header files, some
of which also include other header files. The most important and most basic of these header
files are:
•
•
•
•
•
WINDEF.H Basic type definitions.
WINNT.H Type definitions for Unicode support.
WINBASE.H Kernel functions.
WINUSER.H User interface functions.
WINGDI.H Graphics device interface functions
7. Give the syntax for “WinMain”.
int WINAPIWinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nShowCmd
)
8. Briefly explain about the parameters to “WinMain”.
• 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.
• The second parameter to WinMain is always NULL (defined as 0).
• The third parameter to WinMain is the command line used to run the program.
• The fourth parameter to WinMain indicates how the program should be initially
displayed—either normally or maximized to fill the window, or minimized to be
displayed in the task list bar.
9. What is the use of Message Box
The MessageBox function is designed to display short messages. The little window that
MessageBox displays is actually considered to be a dialog box, although not one with a lot of
versatility.
10. What are the argument used in Message Box and uses.
• The first argument to Message Box is normally a window handle.
• The second argument is the text string that appears in the body of the message
box
• The third argument is the text string that appears in the caption bar of the
message box
• The fourth argument to MessageBox can be a combination of constants
beginning with the prefix MB_ that are defined in WINUSER.H.
11. What buttons you wish to appear in the dialog box.
#define MB_OK
#define MB_OKCANCEL
#define MB_ABORTRETRYIGNORE
#define MB_YESNOCANCEL
#define MB_YESNO
#define MB_RETRYCANCEL
12. Give the syntax for CreateWindow command.
hwnd = CreateWindow (szAppName,
// window class name
TEXT ("The Hello Program"), // window caption
WS_OVERLAPPEDWINDOW,
// window style
CW_USEDEFAULT,
// initial x position
CW_USEDEFAULT,
// initial y position
CW_USEDEFAULT,
// initial x size
CW_USEDEFAULT,
// initial y size
NULL,
// parent window handle
NULL,
// window menu handle
hInstance,
// program instance handle
NULL) ;
// creation parameters
13. Briefly tell about ShowWindow command.
ShowWindow (hwnd, iCmdShow) ;
The first argument is the handle to the window just created by CreateWindow. The
second argument is the iCmdShow value passed as a parameter to WinMain. This
determines how the window is to be initially displayed on the screen, whether it's normal,
minimized, or maximized.
14. What is the necessity of UpdateWindow command.
The ShowWindow function puts the window on the display. If the second argument
to ShowWindow is SW_SHOWNORMAL, the client area of the window is erased with the
background brush specified in the window class. The function call
UpdateWindow (hwnd) ;
then causes the client area to be painted. It accomplishes this by sending the window
procedure a WM_PAINT message.
15. Briefly explain about window procedure.
When Windows sends a message to the program, it indicates that the Windows calls
a function within the program. The parameters to this function mention a particular message
that is being sent by Windows and received by our program. This function is said to be the
"window procedure." Every window that our program creates has its unique window
procedure. Windows sends a message to a window by calling the window procedure. The
window procedure processes the message and then returns control to Windows.
16. When WM_PAINT message is encountered by the window?
A window procedure receives a WM_PAINT message whenever one of the following
events occurs:
•
•
•
•
A previously hidden area of the window is brought into view when a user moves a
window or uncovers a window.
The user resizes the window (if the window class style has the CS_HREDRAW and
CW_VREDRAW bits set).
The program uses the ScrollWindow or ScrollDC function to scroll part of its client
area.
The program uses the InvalidateRect or InvalidateRgn function to explicitly generate
a WM_PAINT message.
17. What is invalid region?
Although a window procedure should be prepared to update the entire client area
whenever it receives a WM_PAINT message, it often needs to update only a smaller area,
most often a rectangular area within the client area. This is most obvious when a dialog box
overlies part of the client area. Repainting is required only for the rectangular area
uncovered when the dialog box is removed. That area is known as an "invalid region" or
"update region."
18. What is painting?
Painting is the process of validating the client area of the window. In Windows, we
can draw text and graphics only in the client area of our window. For ex, whenever the user
opens a window for the first time, the entire client area of the window should be painted.
When it is closed the client area will be invalidated.
19. What is Repainting?
When the user tries to open the same window again, then the client area should be
repainted again and this process of validating the client area is said to be repainting.
•
•
•
•
As another example, suppose the user opens a first window, again he tries to
open a second window.
Now this second window partially covers our first application's window.
The Windows of the first application window will not save the coordinates of the
second window.
When the second window is closed, then the first window will request that our
program needs to repaint this portion of our client area. Windows is a messagedriven system.
20. What are the steps for Window Creation?
The window creation steps are,
Window Main
• Variable declarations
• Window class registration
• Checking the registration
• Creating the window
• Displaying the window
• Message loop
Window procedure
• WM_CREATE
• WM_PAINT
• WM_DESTROY
• DefWindowProc
21. What is the function used to display the text on the output window?
The function that is used to display the text on the output window is Drawtext()
which is shown below,
DrawText (hdc, TEXT (“HAI WINDOWS"), -1, &rect, DT_SINGLELINE |
DT_CENTER | DT_VCENTER);
•
•
•
•
The first argument is a handle to the device context returned from BeginPaint.
The second argument is the text to draw.
The third argument is set to -1 to indicate that the text string is terminated with a zero
character.
The last argument to DrawText is a series of bit flags defined in WINUSER.H.
22. Define WM_PAINT Message:
The second message that WndProc processes is WM_PAINT. Initially the entire
client area of the window will be invalid. So when the program calls the UpdateWindow()
function, then the window is displayed on the screen and the entire client area should be
validated and this is done by calling WM_PAINT message. When the window is first created,
the entire client area is invalid because the program has not yet processed any message on
the window. The first WM_PAINT message directs the window procedure to validate the
client area. When we resize the window, the client area becomes invalid. This indicates that
the Windows should invalidate the whole window when the size changes.
23. Define WM_CREATE Message:
The very first message that a window procedure receives is WM_CREATE. WndProc
receives this message while Windows is processing the CreateWindow function in WinMain.
That is, when the window program calls CreateWindow() function, the window class
actuomatically calls the window procedure WndProc with the first argument set to the
window handle and the second argument set to WM_CREATE (the value 1). WndProc
processes the WM_CREATE message and returns controls back to Windows.
24. How do we check whether the class is registered?
if (!RegisterClass (&wndclass))
{
MessageBox (NULL, TEXT ("This program requires to register all the
Parameter of the window class "), szName, MB_ICONERROR) ;
return 0 ;
}
25. What is meant by window class?
A window features are created based on the "window class." The window class
identifies the window procedure that processes messages to the window. The multiple
windows can share the same window class and they can use the same window procedure.
26. Define Window Handle.
A handle is a unique integer identifier number (32 bits in size) that refers to an
object. A program identifies the window by the handle. The program uses the handle in other
Windows functions to refer to the object. The handles for the three main subsystems of
windows are as follows,
Identifier
Meaning
HINSTANCE
Handle to an "instance"—the program itself (
kernel )
HWND
Handle to a window (user)
HDC
Handle to a device context (GDI)
27. What are the Data Types used for window creation?
The data types are as follows,
•
•
•
•
•
UINT – This data type is used as second parameter to WndProc and it is simply an
unsigned int,
PSTR – This data type is the third parameter to WinMain and it’s a pointer to a
nonwide character string, that is, a char *.
WPARAM - When Windows was a 16-bit system, the third parameter to WndProc
was defined as a WORD, which was a 16-bit unsigned short integer,
LPARAM - The fourth parameter was defined as a LONG, which was a 32-bit signed
long integer.
LRESULT – This is the return data type of the window procedure WndProc function.
L denotes LONG.
28. Define Hungarian Notation:
Windows programming uses a new type of convention known as "Hungarian
Notation". Hungarian notation system is the process of prefacing the variable name with a
short prefix that indicates the data type of the variable.
•
•
•
•
•
•
Here the variable name begins with a lowercase letter or letters that denote the
data type of the variable.
For example, the sz prefix in szCmdLine stands for "string terminated by zero."
The h prefix in hInstance and hPrevInstance stands for "handle;"
The i prefix in iCmdShow stands for "integer."
For example, in the WinMain function, the msg variable is a structure of the MSG
type; wndclass is a structure of the WNDCLASS type.
In the WndProc function, ps is a PAINTSTRUCT structure and rect is a RECT
structure.
29. What are the Windows Function Calls?
The windows function calls are as follows,
•
•
•
•
LoadIcon: Loads an icon for use by a program.
LoadCursor: Loads a mouse cursor for use by a program.
GetStockObject: Obtains a graphic object, a brush used for painting the window's
background.
RegisterClass: Registers a window class for the program's window.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MessageBox: Displays a message box.
CreateWindow: Creates a window based on a window class.
ShowWindow: Shows the window on the screen.
UpdateWindow: Directs the window to paint itself.
GetMessage: Obtains a message from the message queue.
TranslateMessage: Translates some keyboard messages.
DispatchMessage: Sends a message to a window procedure.
PlaySound: Plays a sound file.
BeginPaint: Initiates the beginning of window painting.
GetClientRect: Obtains the dimensions of the window's client area.
DrawText: Displays a text string.
EndPaint: Ends window painting.
PostQuitMessage: Inserts a "quit" message into the message queue.
DefWindowProc: Performs default processing of messages.
30. What are the three main subsystems of windows?
The three main subsystems of Windows were,
1. Kernel
2. User
3. GDI.
• Kernel is implemented in 6-bit KRNL386.EXE and the 32-bit KERNEL32.DLL
handles the functions such as memory management, file I/O, and tasking.
• User is implemented in 16-bit USER.EXE and the 32-bit USER32.DLL.
• GDI (Graphical Device Interface) is implemented in the 16-bit GDI.EXE and the 32-bit
GDI32.DLL and it allows the program to display text and graphics on the screen.
31. Define Paint Information Structure
The "paint information structure" is maintained by windows for each window, which
contains the coordinates of the invalid region. The paint information structure is shown
below. We can use only the first three fields. The remaining fields are used internally by
Windows. Windows erases the background using the brush specified in the hbrBackground
field of the WNDCLASS structure that we use when registering the window class during
initialization of the window class in Window main function. The statement used to indicate
the background of the window lass is as follows,
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
The paint information structure is as follows:
typedef struct tagPAINTSTRUCT
{
HDC
hdc ;
BOOL
fErase ;
RECT
rcPaint ;
BOOL
fRestore ;
BOOL
fIncUpdate ;
BYTE
rgbReserved[32] ;
} PAINTSTRUCT ;
32. What is the use of TextOut function?
TextOut is the GDI function that is used for displaying text. Its syntax is
TextOut (hdc, x, y, psText, iLength) ;
The first argument is the handle to the device context, either the hdc value returned from
GetDC or the hdc value returned from BeginPaint during processing of a WM_PAINT
message.
The attributes of the device context control the characteristics of the text that is
displayed. For ex, one attribute of the device context specifies the text color.
The default text color is black. The default device context also defines a text background
color and it is white.
When a program writes text to the display, Windows uses this background color to fill in
the rectangular space surrounding each character, called the "character box."
The psText argument is a pointer to a character string.
iLength is the number of characters in the string.
The x and y arguments define the starting point of the character string within the client
area. The x value is the horizontal position and the y value is the vertical position.
33. Define System Font.
The device context also uses the font that Windows uses when we call TextOut to
display text. The default font of the windows is called the "system font" or SYSTEM_FONT.
The system font is the font that Windows uses by default for text strings in title bars, menus,
and dialog boxes.
34. What are the types of system fonts?
The types of font are as follows,
• Fixed- pitch font
• Variable-pitch.
• Raster font
The fixed-pitch font has all the characters of same width. In Windows 3.0, the system
font is the variable-pitch font, in which the different characters have different widths. The
system font is a "raster font," in which the characters are defined as blocks of pixels.
35. What are the types of mouse messages?
The mouse messages are of two types,
• Client-area mouse messages
• Nonclient-area mouse messages
Client-area mouse messages are the events that occur in the client area of the window.
Nonclient-area mouse messages are the events that occur on the non client area of the
window. We always ignore the processing of non client mouse messages.
36. What are the possible events of the mouse?
The possible events on the mouse are as follows,
Pressing or releasing the mouse button
Double clicking the mouse button
Dragging the mouse
37. What are the types of graphics output devices?
The graphics output devices are divided into two groups:
1. Raster devices 2. Vector devices.
Raster devices are those that represent images as a rectangular pattern of dots. Example
for the raster devices are video display adapters, dot-matrix printers, and laser printers.
Vector devices are those that draw images using lines.
38. What is meant by Device Context?
The device context ("DC") is a data structure maintained internally by GDI. A device
context is associated with a particular display device, such as a video display or a printer.
The values in the device context are graphical "attributes." These attributes defines the
processing of the GDI drawing functions.
39. What are the four methods of Getting a Device Context Handle?
There are four methods for getting the device context handle. The first method of
getting the device context handle is by using BeginPaint and EndPaint function in the
WM_PAINT message:
1) hdc = BeginPaint (hwnd, &ps) ;
[other program lines]
EndPaint (hwnd, &ps);
The variable ps is a structure variable of type PAINTSTRUCT.
The second method of getting the device context handle is by using GetDC and ReleaseDC
function and it can be used in any messages other than WM_PAINT:
2) hdc = GetDC (hwnd) ;
[other program lines]
ReleaseDC (hwnd, hdc) ;
The third method of getting the device context handle is by using GetWindowDC and
ReleaseDC function. This method is used to draw on the entire window that include both the
window's client area and non client area and it as follows,
3) hdc = GetWindowDC (hwnd) ;
[other program lines]
ReleaseDC (hwnd, hdc);
The fourth method of getting the device context handle is used for obtaining a handle to a
device context is CreateDC:
4) hdc = CreateDC (pszDriver, pszDevice, pszOutput, pData) ;
[other program lines]
DeleteDC (hdc);
40. What are the line drawing functions?
Windows can draw straight lines, elliptical lines, and Bezier Splines. The seven
functions that is used to draw the lines are as follows,
LineTo: Draws a straight line.
Polyline, PolylineTo: Draw a series of connected straight lines.
PolyPolyline: Draws multiple polylines.
Arc: Draws elliptical lines.
PolyBezier, PolyBezierTo: Draw Bezier splines.
The extra three line-drawing functions supported by higher versions of windows are,
ArcTo, AngleArc: Draw elliptical lines.
PolyDraw: Draws a series of connected straight lines and Bezier splines.
The functions that draw lines by filling the enclosed area are as follows,
Rectangle: Draws a rectangle.
Ellipse: Draws an ellipse.
RoundRect: Draws a rectangle with rounded corners.
Pie: Draws a part of an ellipse that looks like a pie slice.
Chord: Draws part of an ellipse formed by a chord.
41. How do we set a Pixel?
The SetPixel function is used to draw a pixel at a specific x- and y-coordinate with a
particular color and the syntax is as follows,:
SetPixel (hdc, x, y, crColor);
The first parameter is the device context handle. The second and third parameters indicate
the x and y coordinate position. The last parameter is the structure variable of type
COLORREF that is used for setting the color of the pixel point.
42. What are the functions used to draw a line?
To draw a straight line, we must make two function calls. The first function specifies
the starting point at which the line begins, and the second function specifies the destination
point of the line and the syntax for drawing a line is as follows,
MoveToEx (hdc, xBeg, yBeg, NULL);
LineTo (hdc, xEnd, yEnd);
The function MoveToEx sets the attribute of the device context to the current position. The
LineTo function then draws a straight line from the starting position to the destination point
specified in the LineTo function
43. List out the GDI objects.
The Six GDI objects are
1. Pen
2. Brushes
3. Bitmaps
4. Regions
5. Fonts
6. Palettes.
44. What is meant by GDI Mapping Mode?
When we call the function TextOut( ) with x and y values, those coordinates values
are passed to the function as "logical coordinates". Those logical coordinates must be
converted to device pixel coordinates by the process called mapping modes. Windows has a
variety of "mapping modes", which is the process of describing how the logical coordinates
specified in GDI drawing functions are translated to the physical pixel coordinates of the
display. The mapping mode is defined in the device context. The default mapping mode is
called MM_TEXT. Under the MM_TEXT mapping mode, logical units are the same as that of
the physical pixel units, and in this the Values of x increase as we move to the right in the
client area, and values of y increase as we move down in the client area.
45. What is meant by Device Coordinate Systems?
The three coordinate systems are
•
•
•
Screen coordinate system
Whole window coordinate system
Client area coordinate system
The coordinates of the entire screen of the system is said to be the "screen coordinates."
The coordinates of the entire application window including the client area and non client area
is called as "Whole-window coordinates" and it includes the title bar, menu, scroll bars, and
border. The coordinate of the client area of the window is called "client area coordinates".
46. Define child window controls.
The window that is display on the surface of the parent window is called the child
window. We can have a separate window procedure for the child window as ChildProc. The
input given to the child window is received by the child window procedure ChildProc and the
message is sent to its parent window procedure (WndProc) for processing of the message.
The child window procedure get the parent window handle by using the function GetParent,
hwndParent = GetParent (hwnd) ;
where hwnd is the child window handle. Then the child window procedure can send the
message to the parent window procedure by using SendMessage function,
SendMessage (hwndParent, message, wParam, lParam) ;
When the child window is creates then the creation parameters lparam and wparam are
assigned with some values.
47. List out the child window controls.
The child window controls are,
• Button class
• Controls and colors
• Static class
• Edit class
•
•
•
Scroll Bar class
List box class
Combo Box
48. How do we create a Child Window?
The child window can be created by using the CreateWindow function with the
following parameters:
hwndchild = CreateWindow (
TEXT ("Child window Text”), // child window class name
szText,
// child window text
WS_CHILD
//Window style
CW_USEDEFAULT,
// initial x position
CW_USEDEFAULT,
// initial y position
CW_USEDEFAULT,
// initial x size
CW_USEDEFAULT,
// initial y size
NULL,
// parent window handle
NULL,
// child window menu handle
hInstance,
// program instance handle
NULL) ;
// creation parameters
49. Define Push Buttons and its types.
A push button is a rectangle enclosing text that is specified in the window text
parameter of the child CreateWindow function call. The two types of push-button and their
button styles are as follows,
1. PushButton Æ BS_PUSHBUTTON
2. Default PushButton Æ BS_DEFPUSHBUTTON.
50. Define Check Boxes and its types.
A check box is a square box with text; the text that appears to the right or left of the
check box. By default the text will appear to the right of the check box. We can make the text
to appear on the left side of the check box by including BS_LEFTTEXT style when creating
the button child window. The check boxes are used in the application for the user to select
options. When clicking the check box, click mark will appear.The two types of check boxes
and their button styles are as follows,
Check box Æ BS_CHECKBOX
Automatic Check box Æ BS_AUTOCHECKBOX.
51. Define Radio Buttons and its types
A Radio button is a circle with text; the text that appears to the right or left of the radio
button. By default the text will appear to the right of the radio button. We can make the text
to appear on the left side of the radio button by including BS_LEFTTEXT style when creating
the button child window. The Radio buttons are used in the application for the user to select
options. When clicking the radio button, a dot will appear inside the circle. The two types of
radio buttons and their button styles are as follows,
1. Radio Button Æ BS_RADIOBUTTON
2. Automatic Radio Button Æ BS_AUTO
3. RADIOBUTTON
52. Define Group Boxes and its types.
The group box is used to enclose all the button controls present within the
rectangular outline and the group box text will be at the top. The style of the group box is
BS_GROUPBOX. The group box does not processe any messages and does not send any
messages to the parent window.
53. Define WM_CTLCOLORBTN Message
This is the message that is sent by the child window to the parent window when the
button child window is trying to paint its client area. When the parent window procedure is
receiving this message WM_CTLCOLORBTN from the button child window, then the
wParam parameter is the handle to the button child window’s device context and lParam is
the button child window handle.
54. What is meant by Static Child window control?
The static child window control will draw a rectangle or a frame in the client area of
the child window. The six styles of the static class is shown below,
•
•
•
•
•
•
SS_BLACKRECT
SS_BLACKFRAME
SS_GRAYRECT
SS_GRAYFRAME
SS_WHITERECT
SS_WHITEFRAME
55. Define Scroll bar child window control Class.
The scroll bar that appears on the right and bottom of the application window are the
"window scroll bars". The window scroll bars are created by adding the window style
identifier WS_VSCROLL or WS_HSCROLL while creating the window. The Scroll bar
controls are the child windows that can be displayed anywhere in the client area of the
parent window. The scroll bar child window controls are created by using the built in child
window class namely "scrollbar" with the scrollbar styles SBS_VERT and SBS_HORZ.
56. What are the messages sent by the Scroll bar controls?
Scroll bar controls do not send WM_COMMAND messages to the parent window.
The scroll bar controls send WM_VSCROLL and WM_HSCROLL messages to the parent
window. The height and the width of a horizontal scroll bar can be retrieved by the function
GetSystemMetrics as,
GetSystemMetrics (SM_CYHSCROLL);
GetSystemMetrics (SM_CXVSCROLL);
57. List the scroll bar window style identifiers.
The scroll bar window style identifiers are as follows,
SBS_LEFTALIGN
SBS_RIGHTALIGN
SBS_TOP ALIGN
SBS_BOTTOMALIGN
58. Define Window Sub classing.
The default window procedure for the scroll bar controls is present in the Windows.
We can get the address of the default window procedure for the scroll bar control by calling
the function GetWindowLong with the GWL_WNDPROC identifier as the parameter. We
can create our own scroll bar child window procedure by calling the function
SetWindowLong. This technique is called "window subclassing".
59. List down the Edit Class Styles.
The Edit control is created by giving the class name to be "edit" as the window class
in the CreateWindow call. The window style should be WS_CHILD. Here we can make the
text in the edit class to be left-justified, right-justified, or centered. The edit class styles are
as follos,
•
•
•
•
•
•
ES_LEFT
ES_RIGHT
ES_CENTER
ES_AUTOHSCROLL
ES_AUTOVSCROLL
ES_MULTILINE
60. What are the types of list box and its style?
The types of the list box are as follows,
•
Single selection list box
•
Multiple selection list box
The user can select the item by pressing the Spacebar in the single-selection list box. The
arrow keys can be used fro moving the current selected text and for scrolling the contents of
the list box. An item can also be selected by clicking or double-clicking the mouse on the
item. In the multiple-selection list box, the Spacebar toggles the selection state of the item
where the cursor is positioned. In this type, the list box item will be deselected when we
place the cursor on the already selected item. The list box styles are,
• LBS_NOTIFY
• LBS_SORT
• LBS_MULTIPLESEL
UNIT II - VISUAL C++ PROGRAMMING
Two Mark Questions - PART A
1. What is an application framework?
Application framework is defined as an an integrated collection of objectoriented software components that offers all that's needed for a generic application
2. Why we use the application framework?
ƒ The MFC library is the C++ Microsoft Windows API
ƒ Application framework applications use a standard structure.
ƒ Application framework applications are small and fast.
ƒ The Visual C++ tools reduce coding drudgery.
ƒ The MFC library application framework is feature rich.
3. What are the ways to develop a window application?
ƒ Program in C with the Win32 API
ƒ Write your own C++ Windows class library that uses Win32
ƒ Use the MFC application framework
ƒ Use another Windows-based application framework such as Borland's Object
Windows Library (OWL)
4. Difference between Application framework and class library
Application Framework
ƒ
ƒ
ƒ
It is the collection of Object
oriented
software
components.
Superset of the class library
Application framework defines
the structure of the program
itself
Class Library
It is the collection of Related classes.
Subset of the class library
Here the isolated set of classes
designed to incorporate into program.
5. Briefly explain about the CMyApp class and the CmyFrame class.
The CMyApp class—an object of class CMyApp represents an application.
The program defines a single global CMyApp object, theApp. The CWinApp base
class determines most of theApp's behavior.
The CMyFrame class—an object of class CMyFrame represents the
application's main frame window. When the constructor calls the Create member
function of the base class CFrameWnd, Windows creates the actual window
structure and the application framework links it to the C++ object.
6. Define document-view architecture.
Document-view architecture is the core of the application framework. The
document-view architecture separates data from the user's view of the data. One
obvious benefit is multiple views of the same data.
7. What is a make file?
A make file stores compiler and linker options and expresses all the
interrelationships among source files. A make program reads the make file and then
invokes the compiler, assembler, resource compiler, and linker to produce the final
output, which is generally an executable file.
8. Mention the Visual C++ components.
• The project
• The Resource editors – Workspace Resource View
• The C/C++ Compiler
• The Source Code Editor
• The Resource Compiler
• The Linker
• The Debugger
• AppWizard
• Class wizard
9. Mention the files generated by VC++.
File Extension
Description
APS
BSC
CLW
Supports
ResourceView
Browser information file
Supports ClassWizard
DEP
DSP
Dependency file
Project file*
DSW
MAK
Workspace file*
External makefile
NCB
OPT
Supports ClassView
Holds workspace
configuration
Builds log file
PLG
10. Mention the usage of source code editor and resource compiler.
• The Source Code Editor
Visual C++ 6.0 includes a sophisticated source code editor that supports
many features such as dynamic syntax coloring, auto-tabbing, keyboard
bindings
• The Resource Compiler
The Visual C++ resource compiler reads an ASCII resource script (RC) file
from the resource editors and writes a binary RES file for the linker.
11. What is AppWizard?
AppWizard is a code generator that creates a working skeleton of a Windows
application with features, class names, and source code filenames that you specify
through dialog boxes. AppWizard code is minimalist code; the functionality is inside
the application framework base classes.
12. What is ClassWizard?
ClassWizard is a program (implemented as a DLL) that's accessible from Visual
C++'s View menu. ClassWizard takes the drudgery out of maintaining Visual C++
class code. ClassWizard writes the prototypes, the function bodies, and (if
necessary) the code to link the Windows message to the function. ClassWizard can
update class code that you write, so you avoid the maintenance problems common to
ordinary code generators.
13. What is ATL?
ATL (Active Template Library) is a tool, separate from MFC, for building ActiveX
controls. You can build ActiveX controls with either MFC or ATL, but ATL controls are
much smaller and quicker to load on the Internet.
14. What are the windows diagonistic tools?
Visual C++ 6.0 contains a number of useful diagnostic tools.
ƒ SPY++ gives you a tree view of your system's processes, threads, and
windows. It also lets us to view the messages and examine the windows of
running applications.
ƒ PVIEW (PVIEW95 for Windows 95) useful for killing errant processes that
aren't visible from the Windows 95 task list.
15. What is message mapping?
When the user presses the left mouse button in a view window, Windows
sends a message—specifically WM_LBUTTONDOWN—to that window. If your
program needs to take action in response to WM_LBUTTONDOWN, your view class
must have a member function that looks like this:
The Message Handler:
Void CMyView::OnLButtonDown(UINT nFlags, CPoint point)
{
// event processing code here
}
The Message Map:
BEGIN_MESSAGE_MAP(CMyView, CView)
ON_WM_LBUTTONDOWN()
// entry specifically for OnLButtonDown
// other message map entries
END_MESSAGE_MAP()
Finally, our class header file needs the statement
DECLARE_MESSAGE_MAP()
16. What are the two ways to optimize the painting in windows?
There are two ways to optimize painting in Windows.
ƒ First of all, we must be aware that Windows updates only those pixels that are
inside the invalid rectangle. Thus, the smaller you make the invalid rectangle, the
quicker it can be repainted.
ƒ Second, it's a waste of time to execute drawing instructions outside the invalid
rectangle. our OnDraw function could call the CDC member function GetClipBox
to determine the invalid rectangle, and then it could avoid drawing objects outside
it.
17. Define CRect , CPoint and CSize.
The CRect, CPoint, and CSize classes are derived from the Windows RECT,
POINT, and SIZE structures, and thus they inherit public integer data members as
follows:
CRect
left, top, right, bottom
CPoint
x, y
CSize
cx, cy
18. What is MM_TEXT mapping mode?
In MM_TEXT, coordinates map to pixels, values of x increase as you move right,
and values of y increase as you move down, But we are allowed to change the origin
through calls to the CDC functions SetViewportOrg and SetWindowOrg.
19. How to find whether a Point is Inside a Rectangle?
The CRect class has a member function PtInRect that tests a point to see whether it
falls inside a rectangle. The second OnLButtonDown parameter (point) is an object of
class CPoint that represents the cursor location in the client area of the window. If we
want to know whether that point is inside the m_rectEllipse rectangle, we can use
PtInRect in this way:
if (m_rectEllipse.PtInRect(point))
{
// point is inside rectangle
}
20. How to find whether a Point Inside an Ellipse?
The code determines whether the mouse hit is inside the rectangle. We can find out
whether the hit is inside the ellipse. To do this, we must construct an object of class
CRgn that corresponds to the ellipse and then use the PtInRegion function instead of
PtInRect.
CRgn rgn;
rgn.CreateEllipticRgnIndirect(m_rectEllipse);
if (rgn.PtInRegion(point))
{
// point is inside ellipse
}
21. What is Variable scale mapping mode?
Windows provides two mapping modes:
MM_ISOTROPIC and MM_ANISOTROPIC,
That allows you to change the scale factor as well as the origin. With these mapping
modes, your drawing can change size as the user changes the size of the window. Also,
if you invert the scale of one axis, you can "flip" an image about the other axis and you
can define our own arbitrary fixed-scale factors.
22. What is fixed mapping mode?
One important group of Windows mapping modes provides fixed scaling
In the MM_HIMETRIC mapping mode, x values increase as you move right and
y values decrease as you move down.
The only difference among the fixed mapping modes is the actual scale factor,
listed in the table shown here.
Mapping Mode
Logical Unit
MM_LOENGLISH
0.01 inch
MM_HIENGLISH
0.001 inch
MM_LOMETRIC
0.1 mm
MM_HIMETRIC
0.01 mm
1/1440 inch
MM_TWIPS
23. Define MM_TEXT mapping mode.
In MM_TEXT, coordinates map to pixels, values of x increase as you move
right, and values of y increase as you move down, but we are allowed to change the
origin through calls to the CDC functions SetViewportOrg and SetWindowOrg.
24. Define MM_ISOTROPIC and MM_ANISOTROPIC.
The MM_ISOTROPIC mode is one in which, a 1:1 aspect ratio is always preserved.
In other words, a circle is always a circle as the scale factor changes.
The MM_ANISOTROPIC mode is one in which, the x and y scale factors can change
independently. Circles can be squished into ellipses.
25. What are the CDC Functions used to translate the logical to device units?
The Windows GDI has two CDC functions to translate the logical to device units and
they are,
• LPtoDP
• DPtoLP
26. What is modal dialog box?
The user cannot work elsewhere in the same application (more correctly, in the same
user interface thread) until the dialog is closed. Example: Open File dialog.
27. What is modeless dialog box?
The user can work in another window in the application while the dialog remains on
the screen
Example: Microsoft Word's Find and Replace dialog is a good example of a
modeless dialog; you can edit your document while the dialog is open.
28. Mention the differences in creating modal and modeless dialogs.
Modal Dialog
Modeless Dialog
Constructor with resource ID Default constructor (no
param
params)
Constructor
used
Function
used
create
window
DoModal
to
Create with resource ID
param
29. Briefly explain the methods for sending window messages in modeless dialogs.
We have two options for sending Windows messages: the CWnd::SendMessage
function or the Post Message function. The former causes an immediate call to the
message-handling function, and the latter posts a message in the Windows message queue.
Because there's a slight delay with the Post Message option, it's reasonable to expect that
the handler function has returned by the time the view gets the message
30. What is a font?
Fonts are an integral part of the Windows GDI. This means that fonts behave the
same way other GDI objects do. They can be scaled and clipped, and they can be selected
into a device context as a pen or a brush can be selected. All GDI rules about deselection
and deletion apply to fonts.
31. What is a system modal dialog?
The 16-bit versions of Windows support a special kind of modal dialog called a
system modal dialog, which prevents the user from switching to another application. Win32
also supports system modal dialogs but with weird results: the user can switch to another
application, but the dialog remains as the top window.
32. Mention the windows common controls.
• The Progress Indicator Control
• The Trackbar Control
• The spin button
• The list control
• The tree control
33. What is a progress indicator control?
The progress indicator is the easiest common control to program and is represented
by the MFC CProgressCtrl class. It is generally used only for output. This control, together
with the trackbar, can effectively replace the scroll bar controls. To initialize the progress
indicator, call the SetRange and SetPos member functions in your OnInitDialog function,
and then call SetPos anytime in your message handlers.
34. Give the structure of DIB within a BMP file.
35. What is a spin button control?
The spin button control (class CSpinButtonCtrl) is an itsy-bitsy scroll bar that's most
often used in conjunction with an edit control. The edit control, located just ahead of the spin
control in the dialog's tabbing order, is known as the spin control's buddy.
36. Give the usage of WM_NOTIFY message.
The original Windows controls sent their notifications in WM_COMMAND messages.
The standard 32-bit wParam and lParam message parameters are not sufficient, however,
for the information that a common control needs to send to its parent. Microsoft solved this
"bandwidth" problem by defining a new message, WM_NOTIFY. With the WM_NOTIFY
message, wParam is the control ID and lParam is a pointer to an NMHDR structure, which is
managed by the control.
37. Give the structure of NHMDR.
typedef struct tagNMHDR
{
HWND hwndFrom; // handle to control sending the message
UINT idFrom; // ID of control sending the message
UINT code; // control-specific notification code
} NMHDR;
38. Mention the various common dialog classes.
Class
Purpose
CColorDialog
Allows the user to select or create a color
CFileDialog
Allows the user to open or save a file
CFindReplaceDialog Allows the user to substitute one string for another
CPageSetupDialog
CFontDialog
CPrintDialog
Allows the user to input page measurement
parameters
Allows the user to select a font from a list of
available fonts
Allows the user to set up the printer and print a
Document
39. What is a GDI bitmap?
GDI bitmap objects are represented by the Microsoft Foundation Class (MFC) Library
version 6.0 CBitmap class.The GDI bitmap object has an associated Windows data
structure, maintained inside the Windows GDI module that is device-dependent. •GDI
bitmaps can be freely transferred among programs on a single computer, but because of
their device dependency, transferring bitmaps by disk or modem doesn't make sense
40. What is a DIB?
• DIB (Device Independent Bitmap)s offer many programming advantages over GDI
bitmaps.
• Since a DIB carries its own color information, color palette management is easier.
• DIBs also make it easy to control gray shades when printing. Any computer running
Windows can process DIBs, which are usually stored in BMP disk files or as a
resource in your program's EXE or DLL file.
41. What is Standard Video Graphics Array Video Cards?
A standard Video Graphics Array (VGA) video card uses 18-bit color registers
and
thus has a palette of 262,144 colors. Because of video memory constraints, however, the
standard VGA board accommodates 4-bit color codes, which means it can display only16
colors at a time. Each Windows color is represented by a combination of 8-bit "red,"
"green," and "blue" values.
42. What is Progress Indicator Control?
The Progress control is used to display the status of an activity, especially for a long
operation. A progress control is used only to display information to the user who cannot edit
and update its functionality. The progress indicator class is CProgressCtrl class. We
initialize the progress indicator then we can call the SetRange and SetPos member
functions in our OnInitDialog function and can retrieve the range and position of the progress
indicator control by using GetRange and GetPos function
43. Define Animation control?
An animation is a series of pictures put together to produce a video clip. It can be
used to display the evolution of an ongoing task to the user. For example, making a copy of
a CD is usually a long process that can take minutes. We can display an animation to make
the user to know when the task will be completed. An animation first originates from an avi
file created by an external application.
44. What are the Characteristics of Dialog Box?
• It cannot be minimized, maximized, or restored.
• A dialog box does not have any other system button except close button.
• It is usually modal. The user is usually not allowed to continue any other operation
until the dialog box is closed.
• It is equipped with the system Close button. As the only system button, this button
allows the user to close the dialog and ignore whatever the user would have done on
the dialog box.
45. What are the types of Bitmaps?
Bitmaps are divided in two categories that control their availability to display on a
device and they are,
• GDI Bitmaps (Device-Dependent Bitmap)
• Device-Independent Bitmaps
46. Define Device- Independent Bitmap.
A Device- Independent Bitmap (DIB) is a bitmap that is designed to be loaded on
any application or display on any device and produce the same visual effect. To make this
possible, such a bitmap contains a table of colors that describes how the colors of the
bitmap should be used on pixels when displaying it. The characteristics of a DIB are defined
by the BITMAPINFO structure.
47. Define Device- Dependent Bitmap.
A Device-Dependent Bitmap (DDB) is a bitmap created from the BITMAP structure
the dimensions of the bitmap. GDI bitmaps can be freely transferred among programs on a
single computer
48. What are the Font Height Measurements?
The font height measurement parameters are available in the CDC function
GetTextMetrics. The font height measurements are
• tmHeight
• tmExternalLeading
• tmInternalLeading
49. What are the types of fonts?
The two types of fonts are
1. Window fonts
2. True type fonts
The true type fonts may further classified into
1. Device-independent TrueType fonts
2. Device-dependent True Type fonts
50. Define CDialog class
To create dialog box, derive a class from CDialog and use a constructor to specify
the resource that holds the default characteristics of the object. The CDialog class provides
three constructors as follows:
• CDialog();
• CDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL);
• CDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL);
UNIT III - DOCUMENT AND VIEW ARCHITECTURE
Two Mark Questions - PART A
1. Define menu.
A menu is a list of actions that the user can perform on an application. The actions
are presented in one or more groups. A main menu, also called a top-level menu, displays
categories of menu items using a range of items called a menu bar.
2. Define Keyboard Accelerators.
Each menu items has an underlined letter. In Visual C++, pressing Ctrl-S activates the
File Save menu item.
• Keyboard accelerators are the shortcut method of using the keyboard to choose
menu items from menus.
• In Windows, the keystroke of a menu is linked with the particular menu items with a
table of key combinations with associated command IDs.
3. How the application framework searches for the message handlers on receiving the
command message from the frame window?
For a SDI application, the searching sequence of the message handlers is as follows,
ƒ View
ƒ Document
ƒ SDI Main frame window
ƒ Application
For a MDI application, the searching sequence of the message handlers is as follows,
ƒ View
ƒ Document
ƒ MDI Child frame window
ƒ MDI main frame window Application
4. What is meant by Update Command User Interface Handlers?
Generally we need to change the appearance of a menu item according to our
application. If our application's Edit menu includes a Clear All menu item, then we may wish
to disable that item if there is empty document to clear.
•
•
•
•
In this case, we can provide this functionality by executing a piece of code that
changes the internal state of the menu item to update the menu.
The MFC library uses a special approach by calling update command user
interface (UI) handler function when there is an empty document to clear.
The handler function's argument is a CCmdUI object, which contains a pointer to
the corresponding menu item.
The handler function can then use this pointer to modify the menu item's
appearance.
5. Explain the concept of Enabling and Disabling the Menu Items.
• The application framework can disable a menu item if it does not find a command
message handler for that particular menu item.
• So there is no need to write the ON_UPDATE_COMMAND_UI handlers for that
disabled menu item.
• We can disable a menu item by setting the CFrameWnd data member
m_bAutoMenuEnable as FALSE.
6. Define Rich Edit Control
A Rich Edit control is a Windows object that resembles an edit box but can handle
text that is formatted. This means that it can display text with various characters formats and
can show paragraphs with different alignments. A rich edit control can also allow a user to
change the formatting on characters and control the alignment of paragraphs.
7. What are the MFC Text Editing Options?
The Rich Edit Control provides powerful text editing features to our application. The
Text editing features are as follows,
Edit Control (CEditView)
Rich Edit Control(CRichEditView)
Rich Edit Common Control. (CRichEditCtrl)
8. What is a TOOLBARS?
A toolbar consists of horizontally or vertically arranged graphical buttons that are
grouped together. The graphical images for the tool bar buttons are stored in a single bitmap
that are stored in the application's resource file. When a tool bar button is clicked, it sends a
command message. An update command UI message handler is used to update the state of
the tool bar button.
9. Define Toolbar Bitmap.
Each toolbar button on a toolbar appears to have its own bitmap. The toolbar bitmap
is stored in the file Toolbar.bmp in the application's \res subdirectory.
• The bitmap is identified in the resource script (RC) file as IDR_MAINFRAME.
•
The toolbar bitmap has a tile in which each button has 15 pixels high and 16 pixels
wide.
10. How does your view find its main frame window?
In an SDI application, we call the function CWnd::GetParentFrame to find the main
frame window.
• However this function is not used in an MDI application because the view's parent
frame is the MDI child frame, not the MDI frame window.
• Actually the view class should work with both the SDI and MDI applications; so
we must locate the main frame window through the global application object.
• The global function AfxGetApp returns a pointer to the application object and we
use that pointer to get the CWinApp data member m_pMainWnd.
• In an MDI application, the MFC AppWizard generates code that sets the data
member m_pMainWnd.
• In an SDI application, the framework sets m_pMainWnd during the view creation
process and we can use it in our view class and the code is shown below,
CMainFrame*pFrame=(CMainFrame*) AfxGetApp()->m_pMainWnd;
CToolBar* pToolBar = &pFrame->m_wndToolBar;
11. What is meant by a ToolTip?
A ToolTip is the text that is displayed in a small rectangle box namely ToolTip box,
when the user places the mouse on a toolbar button and it is shown below. To create a
ToolTip, we add the text to the end of the menu prompt after a new line \n character which is
shown below,
A ToolBar with Tooltip
12. What is a STATUS BAR?
The status bar is an object of class CStatusBar. The status bar window does not
accept user input and does not generate any command messages. It is used only to display
text in status bar panes. The status bar has two types of text panes,
Message line panes
Status indicator panes.
13. Define a Message Line Pane of a status bar.
A Message line pane displays a string that is given by the program at runtime.
• If we want to set the value of the message line pane, then we must first access
the status bar object and then we must call the function
CStatusBar::SetPaneText with a zero-based index parameter.
• Pane 0 is the leftmost pane, 1 is the next pane to the right.
14. Define Status Indicator Pane of a status bar.
• A Status indicator pane is linked to a single resource-supplied string that is
displayed or hidden with the corresponding update command UI message
handler function.
• An indicator is identified by a string resource ID, and that same ID is used to
process the update command UI messages.
15. How the caps lock mode is enabled?
• The Caps Lock indicator is handled in the main frame class by a message map
entry.
• The Enable function is used to set the Caps Lock mode. The code is as follows,
Void CMainFrame::OnUpdateKeyCapsLock(CCmdUI* pCmdUI)
{
pCmdUI->Enable(::GetKeyState(VK_CAPITAL) & 1);
}
16. Define Reusable Base Classes
Generally the reusable base classes are difficult to write because of the following
reasons,
• When we build the reusable base class, we must know the future programming
needs.
• Reusable base class should be general and complete
• Reusable base class should be efficient and easy to use.
• Building the reusable software by satisfying the programmer and the user is difficult.
• While build the reusable base class, we have to be concerned about the window size
and position, taskbar, toolbar, status bar, and dynamic link library (DLL).
• Because of the above reasons, building the reusable base class is difficult.
17. Why do we choose the class CFrameWnd as the base class for a persistent
window rather than choosing persistent view class?
• In an MFC SDI application, the main frame window is the parent of the view window.
• The frame window is created first and then the control bars and the view are created
as child windows.
• The application framework ensures that the child windows maximize and minimize
automatically as the user changes the size of the frame window.
• The CFrameWnd::ActivateFrame member function is used for controlling the
frame's size.
• The standard application framework calls this virtual function during the SDI main
frame window creation process.
• Then the application framework calls CWnd::ShowWindow member function with
the parameter nCmdShow.
18. What is the use of PreCreateWindow Member Function in CWnd.
The function PreCreateWindow in the CWnd is another virtual function that can be
overridden to change the characteristics of our window before it is displayed to the user. The
framework calls this function before calling the ActivateFrame function. The
PreCreateWindow function is automatically generated in the view and frame window classes
by the MFC AppWizard. This function has a CREATESTRUCT structure as a parameter with
the following two data members,
• style
• dwExStyle
The style flag determines whether the window has a border, scroll bars, a minimize box etc.
The dwExStyle flag controls other characteristics, such as always-on-top status.
19. Define Windows Registry and its purpose.
In Microsoft Visual C++ Win32-based applications use .INI files, but in reusable
frame window class uses the Windows Registry. The windows Registry is a set of system
files managed by Windows, in which Windows and the individual user applications can store
and access permanent information. The Registry is grouped like a hierarchical database in
which string and integer data is accessed by a multipart key. For example, the TEXTPROC
structure in a text processing application is as follows,
TEXTPROC
Text formatting
Font = Arial
Points = 16
Unicode
20. What are the functions of CString Class?
The MFC CString class has many operators and member functions and it provides
dynamic memory allocation. The uses of the CString objects are as follows,
CString strFirstName("Shyamala");
CString strLastName("Sofia");
CString strTotal = strFirstName + " " + strLastName; // concatenation
AfxMessageBox(strTotal);
The CString class has const char*() operator that converts a CString object to a character
pointer. we can call the AfxMessageBox function as,
char szMessage[] = "Visual Programming";
AfxMessageBox(szMessage);
(Or)
CString strMessage("Visual Programming ");
AfxMessageBox(strMessage);
The formatted string can be generated by using the function CString::Format as,
int nError = 100;
CString strFormatMsg;
strFormatMsg.Format("Error number %d", nError);
AfxMessageBox(strFormatMsg);
21. What are the functions in CWnd that are used to retrieve the window’s position?
• We can retrieve the screen coordinates of a window by calling the CWnd function
GetWindowRect.
• If the window is maximized, GetWindowRect returns the coordinates of the
screen rather than getting the window's unmaximized coordinates.
22. What are the functions in CFrameWnd that are used to save and load the control
bar status in the windows registry?
The MFC library has two member functions in the class CFrameWnd, and they are,
• SaveBarState( )
• LoadBarState( )
The above functions are used to save and load the control bar status to and from the
Registry. These functions process the size and position of the status bar
•
•
•
The function CWnd::GetWindowPlacement retrieves the unmaxi-mized
coordinates together with some flags that indicate whether the window is
currently minimized or maximized.
The SetWindowPlacement function is used to set the maximized and minimized
status and the size and position of the window.
23. How to create the Default Window Rectangle?
Generally we use the device coordinates or logical coordinates to define the
rectangles. But we have special function parameters in the CRect object which creates the
default rectangle in the output and it is shown below,
CRect rect(CW_USEDEFAULT, CW_USEDEFAULT, 0, 0);
The above statement creates a new window with default rectangle. This function positions
the window in a cascade pattern with the top left corner below and to the right of the window
most recently created. The right and bottom edges of the window are always within the
display's boundaries. The static rectDefault data member is constructed using
CW_USEDEFAULT which is present in CFrameWnd class's.
24. Define CPersistentFrame Class.
For creating reusable frame window class, we use CPersistentFrame class which is
derived from the CFrameWnd class. This CPersistentFrame class supports a persistent SDI
(Single Document Interface) frame window that has the following built in characteristics.
• Window size
• Window position
• Maximized status
• Minimized status
• Toolbar position
• Status bar position
25. What are the Rich Edit control classes?
• The CEditView Class is based on the Windows edit control. Text size is limited to
64 KB, and we cannot mix fonts.
• The CRichEditView Class uses the rich edit control and it supports mixed fonts
and it can occupy large quantities of text. The CRichEditView class is designed to
be used with the CRichEditDoc and CRichEditCntrItem classes to implement a
complete ActiveX container application.
• The CRichEditCtrl Class is similar to a text editor. We will use an ordinary view
class derived from CView, and we will cover the view's client area with a big rich
edit control that resizes itself when the view size changes. The functions in the
CRichEditCtrl are as follows.
26. What are the functions of Document-View Interaction?
The document object holds the data and the view object displays the data to the user
and allows them for editing and updating.
• An SDI application has a document class derived from CDocument and it has one or
more view classes, each view classes derived from CView.
• The interaction process takes place between the document, the view, and the rest of
the standard application framework.
• The five important member functions in the document and view classes, out of which
two are nonvirtual base class functions that we call in our derived classes and they
are as follows,
ƒ CView::GetDocument
ƒ CDocument::UpdateAllViews
• Three are virtual functions that we override in our derived classes. The functions are
as follows,
ƒ CView::OnUpdate
ƒ CView::OnInitialUpdate
ƒ CDocument::OnNewDocument
27. Define CView::GetDocument Function.
A view object has only one associated document object. The GetDocument function
allows an application to find the way from a view to its document.
•
•
•
•
Suppose a view object gets a message that the user has entered new data into an
edit control.
The view must tell the document object to update its internal data.
The GetDocument function provides the document pointer that can be used to
access document class member functions or public data embers.
When AppWizard generates a derived CView class, it creates a special type-safe
version of the GetDocument function that does not returns a CDocument pointer but
a pointer to an object of our derived class.
28. Define CDocument::UpdateAllViews Function.
If the document data is changed, all views data must be updated so that they can
update their original data.
• If the function UpdateAllViews is called from the derived document class member
function, its first parameter pSender is NULL.
• If UpdateAllViews is called from a member function of a derived view class, set the
pSender parameter to the current view which is as follows,
GetDocument()->UpdateAllViews(this);
• The non-null parameter prevents the application framework from notifying the current
view.
29. Define CView::OnUpdate Virtual Function.
This virtual function is called by the application framework when our application calls
the function CDocument::UpdateAllViews function.
• We call this function directly inside our derived CView class.
• Our derived view class's OnUpdate function accesses the document, gets the
document's data, and then updates the view's data members or update the changes.
30. Define CView::OnInitialUpdate Virtual Function.
• This virtual function CView is called when the application starts.
• This function is called when the user chooses New from the File menu, and when the
user chooses Open from the File menu.
• The CView base class version of OnInitialUpdate does nothing but call OnUpdate.
• If we override OnInitialUpdate in our derived view class, we must check that the view
class calls the base class's OnInitialUpdate function or the derived class's OnUpdate
function.
31. What is the purpose of CDocument::OnNewDocument Function?
• The framework calls this virtual function after a document object is first constructed
and when the user chooses New from the File menu in an SDI application.
• At this place only we can set the initial values of our document's data members.
• AppWizard generates an overridden OnNewDocument function in our derived
document class.
32. What is the use of CFormView Class?
The CFormView class is a useful view class that has many of the characteristics of a
modeless dialog window. Like a class derived from CDialog, a derived CFormView class is
associated with a dialog resource that defines the frame characteristics. The CFormView
class supports the same dialog data exchange and validation (DDX and DDV) functions.
33. What is meant by CObject Class?
The CObject class is at the top most root class from which all the other MFC classes
are derived from the CObject root class. When a class is derived from CObject, it inherits
many characteristics. If we derive CObject class, then it allows the objects to participate in
the diagnostic dumping scheme and allows objects to be elements in the collection classes.
34. What is Diagnostic Dumping?
• The MFC library has some useful tools for diagnostic dumping.
• We enable these diagonostic dumping tools when we select the Debug target.
• When we select the Win32 Release target, diagnostic dumping is disabled and the
diagnostic code is not linked to our program.
• All diagnostic output goes to the Debug view in the debugger's Output window.
• To clear diagnostic output from the debugger's Output window, position the cursor in
the Output window and click the right mouse button.
• Then choose Clear from the pop-up menu.
35. Explain the purpose of TRACE Macro.
The statements of the TRACE macro are active whenever the constant _DEBUG is
defined. A TRACE statement works similar to C language printf statements, but they are
completely disabled in the release version of the program. The example is shown below,
int nCount = 15;
CString strDescription("total");
TRACE("Count = %d, Description = %s\n", nCount, strDescription);
36. What is the use of AfxDump Object?
The alternative statement to TRACE in the C++ language is the MFC afxDump
object. This afxDump object accepts the program variables with the syntax similar to cout
statement in C++, which is an output stream object. Here overloaded operators control the
output format. The afxDump output goes to the same destination as the TRACE output, but
the afxDump object is defined only in the Debug version of the MFC library. For example,
int nCount = 15;
CString strDescription("total");
#ifdef _DEBUG
afxDump<<"Count="<<nCount<<",Description="<<strDescription<<"\n";
#endif // _DEBUG
37. Define the term Serialization.
The objects can be persistent, which means that they can be saved on disk when a
program exits and then can be restored when the program is restarted. This process of
saving and restoring objects is called serialization.
38. How do we know whether Serialize should read or write data and how the Serialize
connected to a disk file?
• In the MFC library, objects of class CFile represent disk files.
• A CFile object encapsulates the binary file handle that we get through the Win32
function CreateFile.
• It is a handle to a binary file. The application framework uses this file handle for
Win32 ReadFile, WriteFile, and SetFilePointer calls.
• The CArchive object buffers data for the CFile object, and it maintains an internal
flag that indicates whether the archive is storing (writing to disk) or loading (reading
from disk).
• Only one active archive is associated with a file at any one time. The application
framework takes care of constructing the CFile and CArchive objects, opening the
disk file for the CFile object and associating the archive object with the file.
• All we have to do is to load data from or store data in the archive object.
• The application framework calls the document's Serialize function during the File
Open and File Save processes.
39. What is meant by Serializable Class?
A Serializable class must be derived directly or indirectly from CObject. The class
declaration must contain the DECLARE_SERIAL macro call, and the class implementation
file must contain the IMPLEMENT_SERIAL macro call.
40. Define the Serialize Function.
The CStudent class, derived from CObject, has the following data members:
public:
CString m_strName;
int m_nGrade;
The Serialize function for the CStudent class is as follows,
void CStudent::Serialize(CArchive& ar)
{
TRACE("Entering CStudent::Serialize\n");
if (ar.IsStoring())
{
ar << m_strName << m_nGrade;
}
else
{
ar >> m_strName >> m_nGrade;
}
}
41. How the objects are loaded from an Archive?
There are two ways to load an object from an archive
• Embedded objects.
• Embedded pointers.
42. Define embedded object.
The CStudent object has other objects embedded in it, and these objects are not
instances of standard classes such as CString, CSize, and CRect. Let us add a new data
member to the CStudent class:
Public:
CTranscript m_transcript;
The CTranscript is a custom class, derived from CObject, with its own Serialize member
function. There's no overloaded << or >> operator for CObject, so the CStudent::Serialize
function now becomes which is as follows,
Void CStudent::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
ar << m_strName << m_nGrade;
}
else
{
ar >> m_strName >> m_nGrade;
}
m_transcript.Serialize(ar);
}
43. Explain how the embedded pointers are used to load the object from an archive?
Suppose instead of an embedded object, our CStudent object contained a
CTranscript pointer data member such as this:
public:
CTranscript* m_pTranscript;
We could use the Serialize function, as shown below, but we must construct a new
CTranscript object which is as follows,
void CStudent::Serialize(CArchive& ar)
{
if (ar.IsStoring())
ar << m_strName << m_nGrade;
else {
m_pTranscript = new CTranscript;
ar >> m_strName >> m_nGrade;
}
m_pTranscript->Serialize(ar);
}
Because the CArchive insertion and extraction operators are indeed overloaded for CObject
pointers, we could also write Serialize as,
void CStudent::Serialize(CArchive& ar)
{
if (ar.IsStoring())
ar << m_strName << m_nGrade << m_pTranscript;
else
ar >> m_strName >> m_nGrade >> m_pTranscript;
}
44. What is meant by Serializing Collections?
Since all the collection classes are derived from the CObject class and the collection
class declarations contain the DECLARE_SERIAL macro call, we can easily serialize
collections with a call to the collection class's Serialize member function.
•
•
•
•
•
If we call Serialize for a CObList collection of CStudent objects, for example, the
Serialize function for each CStudent object will be called in turn.
If a collection contains pointers to objects of mixed classes, the individual class
names are stored in the archive so that the objects can be properly constructed with
the appropriate class constructor.
If a container object, such as a document, contains an embedded collection, loaded
data is appended to the existing collection.
We need to empty the collection before loading from the archive.
This is usually done in the document's virtual DeleteContents function, which is
called by the application framework.
45. Define Windows Application Object.
For each of our application project, AppWizard has been generating a class derived
from CWinApp and it generates the following statement,
CMyApp theApp;
The class CMyApp is derived from the class CWinApp, and theApp is a globally declared
instance of the class. This global object is called the Windows application object.
46. What are the execution processes of MFC Library Application?
The startup steps in a MFC library application are as follows:
1. Windows loads our program into memory.
2. The global object theApp is constructed.
3. Windows calls the global function WinMain, which is the main program entry point of
the MFC library.
4. WinMain searches for the one and only instance of a class derived from CWinApp.
5. WinMain calls the InitInstance member function for theApp, which is overridden in our
derived application class.
6. InitInstance function starts the process of loading a document and displaying the
main frame and view windows.
7. WinMain calls the Run member function for theApp, which starts the processes of
dispatching window messages and command messages.
8. The ExitInstance function is called when the application terminates, after all its
windows are closed.
47. Define SDI Document Template Class.
If we look at the InitInstance function that AppWizard generates for our derived
application class, the following statements are featured as follows,
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS (CStudentDoc),
RUNTIME_CLASS (CMainFrame), // main SDI frame window
RUNTIME_CLASS (CStudentView));
AddDocTemplate(pDocTemplate);
48. List out the resources of the SDI Document Template Resource.
The first AddDocTemplate parameter is IDR_MAINFRAME, the identifier for a string
table resource. The corresponding string that AppWizard generates for an application's RC
file is shown below,
IDR_MAINFRAME
"ex\n"
// application window caption
"\n"
// root for default document name
"Ex\n"
// document type name
"Ex Files (*.ex)\n" // document type description and filter
".ex\n"
// extension for documents of this type
"Ex. Document\n"
// Registry file type ID
"Ex Document"
// Registry file type description
49. How do we create an Empty Document using CWinApp::OnFileNew Function?
After our application class's InitInstance function calls the AddDocTemplate member
function, it calls OnFileNew,and the steps are as follows,
1. Constructs the document object but does not attempt to read data from the disk.
2. Constructs the main frame object of class CMainFrame. The main frame window
includes the IDR_MAINFRAME menu, the toolbar, and the status bar.
3. Constructs the view object which creates the view window but does not show it.
4. Establishes connections among the document, main frame, and view objects.
5. Calls the virtual CDocument::OnNewDocument member function for the document
object, which calls the virtual DeleteContents function.
6. Calls the virtual CView::OnInitialUpdate member function for the view object.
7. Calls the virtual CFrameWnd::ActivateFrame for the frame object to show the main
frame window together with the menus, view window, and control bars.
50. Define the OnFileOpen Function.
When AppWizard generates an application, it maps the File Open menu item to the
CWinApp::OnFileOpen member function. When called, this function invokes a sequence of
functions to accomplish the following steps:
1. Prompts the user to select a file.
2. Calls the virtual function CDocument::OnOpenDocument for the already existing
document object. This function opens the file, calls CDocument::DeleteContents, and
constructs a CArchive object set for loading. It then calls the document's Serialize
function, which loads data from the archive.
3. Calls the view's OnInitialUpdate function.
51. What is the purpose of DeleteContents Function of the Document Class?
When we load an existing SDI document object from a disk file, we must erase the
existing contents of the document object.
•
•
•
•
The best way to implement this is by overriding the CDocument::DeleteContents
virtual function in our derived document class.
The overridden function is used to clean up our document class's data members.
In response to both the File New and File Open menu items, the CDocument
functions OnNewDocument and OnOpenDocument both the function calls
DeleteContents function
This means that the function DeleteContents is called immediately after the
document object is first constructed.
52. Define Document's "Dirty" Flag.
• If the user closes a document or exits the program, a message box asks whether the
user wants to save the document.
• This is done by CDocument data member m_bModified.
• This Boolean variable is TRUE if the document has been modified, else it is FALSE.
• The protected m_bModified flag is accessed through the CDocument member
functions SetModifiedFlag and IsModified.
• The framework sets the document object's flag to FALSE when the document is
created or read from disk and when it is saved on disk.
53. Define the MDI Document Template Class.
The MDI template construction call in InitInstance is as follows,
CMultiDocTemplate* pDocTemplate;
pDocTemplate = new CMultiDocTemplate(
IDR_EX18ATYPE,
RUNTIME_CLASS(CStudentDoc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(CStudentView));
AddDocTemplate(pDocTemplate);
54. What is meant by MDI Frame Window and MDI Child Window?
The SDI had only one frame window class and only one frame window object. For
SDI applications, AppWizard generated a class named CMainFrame, which was derived
from the class CFrameWnd. An MDI application has two frame window classes and many
frame objects
Base Class
AppWizardGenerated
Class
Number
of
Objects
Menu
and
Control
Bars
Contains
a View
CMDIFrameWnd
CMainFrame
1 only
Yes
No
CMDIChildWnd
CChildFrame
1 per
child
window
No
Yes
Object
Constructed
In application
class's
InitInstance
function
By
application
framework
when a new
child window
is opened
55. Define MDI Document Template Resources.
An MDI application has two separate string and menu resources, identified by the
IDR_MAINFRAME and IDR_EXTYPE constants. The first resource set goes with the empty
main frame window; the second set goes with the occupied main frame window. The two
string resources with substrings are as follows,
IDR_MAINFRAME
"ex"
// application window caption
IDR_EXTYPE
"\n"
// (not used)
"Ex\n"
// root for default document name
"Ex\n"
// document type name
"Ex Files (*.ex)\n" // document type description and filter
".ex\n"
// extension for documents of this type
"Ex.Document\n"
// Registry file type ID
"ExDocument"
// Registry file type description
56. How the Loading and Storing is done in MDI Documents?
In MDI applications, documents are loaded and stored the same way as in SDI
applications but with two important differences:
1. A new document object is constructed each time a document file is loaded from disk
2. The document object is destroyed when the child window is closed.
57. Define Splitter Window.
• A splitter window is a special type of frame window that holds several views in
panes.
• The application program can split the window on creation, or the user can split the
window by choosing a menu command or by dragging a splitter box on the window's
scroll bar.
• After the window has been split, the user can move the splitter bars with the mouse
for adjusting the size of the panes.
• Splitter windows can be used with both SDI and MDI applications
58. Which class is used for splitting the window?
The CSplitterWnd class object represents the splitter window. A CSplitterWnd object
is an actual window that fully occupies the client area of the frame window.
•
•
•
The view windows occupy the splitter window pane areas.
The splitter window does not take part in the command dispatch mechanism.
The active view window is connected directly to its frame window.
59. What are the types of Splitter Windows?
The types of splitter windows are as follows,
1. Dynamic splitter window
2. Static splitter window
60. Define dynamic splitter window.
A dynamic splitter window allows the user to split the window at any time by
choosing a menu item or by dragging a splitter box located on the scroll bar. The panes in a
dynamic splitter window generally use the same view class. The top left pane is initialized to
a particular view when the splitter window is created. In a dynamic splitter window, scroll
bars are shared among the views. A dynamic splitter application starts with a single view
object. When the user splits the frame, other view objects are constructed. When the user
unsplits the frame, view objects are destroyed.
61. Define static splitter window.
The panes of a static splitter window are defined when the window is first created
and they cannot be changed. The user can move the bars but cannot unsplit or resplit the
window. Static splitter windows can accommodate multiple view classes, with the
configuration set at the creation time. In a static splitter window, each pane has separate
scroll bars. In a static splitter window application, all view objects are constructed when the
frame is constructed and they are all destroyed when the frame is destroyed.
62. What is meant by DLL?
DLL is a file on disk with a DLL extension consisting of global data, compiled
functions, and resources that becomes part of our process. It is compiled to load at a
preferred base address, and if there is no conflict with other DLLs, the file gets mapped to
the same virtual address in our process. The DLL consists of exported functions, and the
client program imports those exported functions. Windows matches up the imports and
exports when it loads the DLL.
63. How the Imported functions are matched with the Exported functions in DLL?
A DLL contains a table of exported functions. These functions are identified by their
symbolic names and by integers called ordinal numbers. The function table also contains
the addresses of the functions within the DLL. When the client program first loads the DLL, it
does not know the addresses of the functions it needs to call, but it does know the symbols
or ordinals. The dynamic linking process then builds a table that connects the client's calls to
the function addresses in the DLL. If we edit and rebuild the DLL, we do not need to rebuild
our client program unless we have changed function names or parameter sequences. Many
DLLs call functions inside other DLLs. Thus, a particular DLL can have both exports and
imports. In the DLL code, we must explicitly declare our exported functions like this:
__declspec(dllexport) int MyFun(int n);
On the client side, we need to declare the corresponding imported function like this:
__declspec(dllimport) int MyFun(int n);
64. What are the types of linkages in DLL?
The types of linkages are
•
•
•
•
Implicit linkage.
Explicit linkage.
Ordinal linkage.
Symbolic linkage.
65. Explain the Implicit Linkage and Explicit Linkage.
When we build a DLL in Implicit linkage, the linker produces import LIB file, which
contains every DLL's exported symbols and ordinals, but no code. The LIB file for the DLL is
added to the client program's project. When we statically link the client, the imported
symbols are matched to the exported symbols in the LIB file, and those symbols (or ordinals)
are bound into the EXE file. The LIB file also contains the DLL filename (but not its full
pathname), which gets stored inside the EXE file. When the client is loaded, Windows finds
and loads the DLL and then dynamically links it by symbol or by ordinal.
In Explicit linkage, we do not use an import file; instead we call the Win32
LoadLibrary function, specifying the DLL's pathname as a parameter. LoadLibrary returns
an HINSTANCE parameter that we can use in a call to GetProcAddress, which converts a
symbol (or an ordinal) to an address inside the DLL. determine at runtime which DLLs to
load.
66. Explain the Symbolic Linkage and Ordinal Linkage.
• In Symbolic linkage, the exported functions are matched with the imported functions
by its symbolic name.
• In ordinal linkage, the exported functions are matched with the imported functions
by its ordinal number.
• In Win16, the more efficient ordinal linkage was used.
• In Win32, the symbolic linkage is used.
• Ordinal linkage permits that program's EXE file to be smaller because it does not
have to contain the long symbolic names of its imports.
• If we build our own DLL with ordinal linkage, we must specify the ordinals in the
project's DEF file, which does not have too many other uses in the Win32
environment.
67. Which the Entry Point in DLL?
The DllMain function is the DLL entry point. By default, the linker assigns the main
entry point _DllMain CRTStartup to our DLL. When Windows loads the DLL, it calls this
function, which first calls the constructors for global objects and then calls the global function
DllMain. DllMain is called not only when the DLL is attached to the process but also when it
is detached. If we do not write a DllMain function for our DLL, a do-nothing version is brought
in from the runtime library. The DllMain function is also called when individual threads are
started and terminated, as indicated by the dwReason parameter. The DllMain function is as
follows,
HINSTANCE g_hInstance;
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID
lpReserved)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
TRACE0("Program Initializing!\n");
// Do initialization here
}
else if (dwReason == DLL_PROCESS_DETACH)
{
TRACE0("Program Terminating!\n");
// Do cleanup here
}
return 1; // ok
}
68. How do you get an instance handle?
If we want the EXE's handle, we call the Win32 GetModuleHandle function with a
NULL parameter. If we want the DLL's handle, you call the Win32 GetModuleHandle
function with the DLL name as a parameter.
69. How do we get the Instance Handles for Loading Resources?
Each DLL in a process is identified by a unique 32-bit HINSTANCE value. In addition,
the process itself has an HINSTANCE value. All these instance handles are valid only within
a particular process, and they represent the starting virtual address of the DLL or EXE. In
Win32, the HINSTANCE and HMODULE values are the same and the types can be used
alternatively. The process (EXE) instance handle is almost always 0x400000, and the
handle for a DLL loaded at the default base address is 0x10000000. If our program uses
several DLLs, each will have a different HINSTANCE value, either because the DLLs had
different base addresses specified at build time or because the loader copied and relocated
the DLL code. Instance handles are particularly important for loading resources. The Win32
FindResource function takes an HINSTANCE parameter. EXEs and DLLs can each have
their own resources.
70. How the Client Program Finds a DLL?
If we link explicitly with LoadLibrary, we can specify the DLL's full pathname. If we do
not specify the pathname, that is linking implicitly, Windows follows this search sequence to
locate our DLL:
1.
2.
3.
4.
5.
The directory containing the EXE file
The process's current directory
The Windows system directory
The Windows directory
The directories listed in the Path environment variable
UNIT IV- ACTIVEX CONTROL AND OBJECT LINKING AND EMBEDDING
Two Mark Questions - PART A
1. Define ActiveX Controls.
• ActiveX Controls are generally known as OLE controls or OCXs.
• ActiveX Controls are the industrial-strength replacement for VBXs based on Microsoft
COM technology.
• ActiveX controls can be used by application developers in both VB and Visual C++
6.0.
• VB were written mostly in C language, ActiveX controls can be written in C++ with
the help of the MFC library or with the help of the ActiveX Template Library (ATL).
• An ActiveX control is a software module that plugs into our C++ program.
2. What is meant by Ordinary Controls?
Ordinary Windows controls such as the edit control and the list box works similarly.
These controls are all child windows that we use most often in dialog box, and they are
represented by MFC classes such as CEdit and CTreeCtrl. The program written by the
client is responsible for the creation of the control's child window.
3. List out the Similarities between ActiveX Controls and Ordinary Controls.
• ActiveX control is also a child window like an ordinary control.
• If we want to include an ActiveX control in a dialog, we use the dialog editor to place
the ActiveX control.
• The identifiers for the ActiveX control are stored in the resource template.
• If we are creating our own ActiveX control, then we must call a Create member
function for a class that represents the control, usually in the WM_CREATE handler
for the parent window.
• When we want to manipulate an ActiveX control, we call a C++ member function
control class. The window that contains a control is called a container.
4. List out the Differences between ActiveX Controls and Ordinary Controls.
• The ActiveX Controls have properties and methods which is not present in the
ordinary controls.
• The C++ member functions of the ActiveX Controls are used to manipulate a control
instance depends on the properties and methods, which is not involved in the
ordinary controls.
• Properties of the ActiveX Controls have symbolic names that are matched to integer
indexes.
• For each property of the ActiveX Controls, the control designer assigns a property
name, such as BackColor or CellEffect, and a property type, such as string, integer,
or double.
• Even a bitmaps and icons of the ActiveX Controls have a picture type.
• The client program can set an individual ActiveX control property by specifying the
property's integer index and its value.
• The client can get a property by specifying the index and accepting the appropriate
return value.
• The ClassWizard enables us to define the data members in our client window class
that are associated with the properties of the ActiveX controls.
• The generated Dialog Data Exchange (DDX) code exchanges data between the
control properties and the client class data members. The above features are not
present in the ordinary control.
• ActiveX Controls methods are like functions. A method has a symbolic name, a set of
parameters, and a return value.
•
•
•
•
We call a method by calling a C++ member function of the class that represents the
control.
An ActiveX control does not send WM_ notification messages to its container as the
ordinary controls but we call the events of the ActiveX controls as "fires events."
An event has a symbolic name and can have an arbitrary sequence of parameters
which is a container function that the ActiveX control calls.
A DLL is used to store one or more ActiveX controls and the DLL file has the file
name extension as .OCX instead of a .DLL extension.
5. What kind of data members we can add to the dialog for an ActiveX control?
• If we want to set a control property before we call DoModal for the dialog, we can add
a dialog data member for that property.
• If we want to change the properties of the ActiveX control inside the dialog member
functions, then we must add a data member that is an object of the wrapper class for
the ActiveX control.
• The CDialog::OnInitDialog function calls CWnd::UpdateData(FALSE) to read the
dialog class data members.
• The CDialog::OnOK function calls UpdateData(TRUE) to write the members.
• Instead of using the above method, we can call Get function.
• To call that function, we must first tell ClassWizard to add a wrapper class object
data member.
• Suppose we have a Calendar wrapper class CCalendar and we have an m_calendar
data member in our dialog class.
• If we want to get the Value property, then we can have a code as follows,
COleVariant var = m_calendar.GetValue();
•
•
•
If we want to set the day to the 5th of the month before the control is displayed.
To do this, add a dialog class data member m_sCalDay that corresponds to the
control's short integer Day property.
Then add the following line to the DoDataExchange function:
DDX_OCShort(pDX, ID_CALENDAR1, 0x11, m_sCalDay);
6. Define DDX.
• The DDX code sets the property value from the data member before the control is
displayed.
• The DDX code sets the data member from the property value when the user clicks
the OK button.
7. How to Create the ActiveX Controls at Runtime?
If we need to create an ActiveX control at runtime without a resource template entry,
then the following steps are used.
1. Insert the component into our project, so that ClassWizard will create the files for the
wrapper class.
2. Add an embedded ActiveX control wrapper class data member to our dialog class or
other C++ window class.
3. An embedded C++ object is then constructed and destroyed along with the window
object.
4. Choose Resource Symbols from Visual C++'s View menu.
5. Add an ID constant for the new ActiveX control.
6. If the parent window is a dialog, use ClassWizard to map the dialog's
WM_INITDIALOG message, thus overriding CDialog-::OnInitDialog.
7. For other windows, use ClassWizard to map the WM_CREATE message. The new
function should call the embedded control class's Create member function.
8. This call indirectly displays the new control in the dialog. The control will be properly
destroyed when the parent window is destroyed.
9. In the parent window class, manually add the necessary event message handlers
and prototypes for our new control.
8. Define COM
• COM is not a programming language
• COM is not DLL
• COM is not only a set of API or functions
• Its simple and efficient
• It is available on Windows, Windows NT
COM is a protocol that connects one software module with another and then drops out of the
picture. After the connection is made, the two modules can communicate through a
mechanism called an interface. COM is a standard approach to access all kinds of software
services, regardless of how they are provided
9. How can we identify an Interface in COM?
The interface in COM can be identified by the following,
• Human-readable name
• Globally Unique Identifier (GUID)
Interface Identifier (IID)
10. What is the Interface Definition Language in COM?
• uuid(E3BE7D4D-F26C-4C35-B694-ABA329A4A0E5),
• version(1.0)
• helpstring("aks_ATL 1.0 Type Library")
11. What are the essences of COM?
COM provides a unified, expandable, object-oriented communications protocol for
Windows that supports the following features:
• A standard, language-independent way for a Win32 client EXE to load and call a
Win32 DLL.
• A general-purpose way for one EXE to control another EXE on the same computer.
• A replacement for the VBX control, called an ActiveX control.
• A powerful new way for application programs to interact with the operating system.
• Expansion to accommodate new protocols such as Microsoft's OLE DB database
interface.
• The distributed COM (DCOM) that allows one EXE to communicate with another
EXE residing on a different computer, even if the computers use different
microprocessor-chip families.
12. List out the COM Classes.
Class identifier (CLSID)
• An object of a specific class supports a certain set of interfaces
• An object’s class identifies a particular implementation of a group of interfaces
13. What is meant by COM Library?
• The COM library implements a group of functions that supply basic services to
objects and their clients
• The COM library’s services are accessed through ordinary function calls
14. What are the advantages of nesting programming in COM interface?
Nesting has two advantages:
• The nested class member functions can access parent class data members without
the need for CSpaceship pointer data members.
•
The nested classes are neatly packaged along with the parent while remaining
invisible outside the parent.
15. Define the function prototype of GetClassObject function.
GetClassObject has the following three parameters:
BOOL GetClassObject(int nClsid, int nIid, void** ppvObj);
•
•
•
The first GetClassObject parameter, nClsid, is a 32-bit integer that uniquely identifies
the CSpaceship class.
The second parameter, nIid, is the unique identifier of the interface that we want.
The third parameter is a pointer to an interface to the object.
16. Draw the structure for accessing a COM object in a Remote Server.
17. How can we lock the ActiveX Controls in Memory?
Generally, an ActiveX control remains mapped in our project as long as its parent
dialog window is active. So it must be reloaded each time when the user opens a modal
dialog. The reloading of the ActiveX control is usually quicker than the initial load because of
caching the disk. But we can lock the ActiveX control into memory for better performance. To
lock the ActiveX control into memory, the following statement is added in the OnInitDialog
function which is as follows,
AfxOleLockControl(m_calendar.GetClsid());
18. How the MFC AppWizard Support for ActiveX Controls to process?
When the MFC AppWizard ActiveX Controls option is checked in the step 3 of
AppWizard, then the MFC AppWizard inserts the following statement in our application class
InitInstance member function:
AfxEnableControlContainer();
It also inserts the following statement in the project's StdAfx.h file #include <afxdisp.h>
19. Define Containment.
In containment, the inner object or inner class does not know the details of outer
class or outer object, but the outer class knows all the details of the inner class that is
embedded inside it. The client cannot access the inner class object interfaces.
20. Define Aggregation.
In aggregation, the client can have direct access to the inner object's interfaces and
both the inner class and outer class know their details of each other.
21. Define OLE .
• Object Linking and Embedding (OLE) is one type of compound document
technology.
•
•
•
•
•
OLE is a Microsoft technology which allows you to link elements from different
applications within each other.
For example, you can embed an Excel spreadsheet or chart inside a PowerPoint
presentation.
When you change the chart or spreadsheet, it changes inside the PowerPoint
presentation.
OLE allows an object such as a graphic, video clip, spreadsheet, etc. to be
embedded into a document, called the "container application."
If the object is playable such as a video, when it is double clicked by the user, a
media player is launched.
22. What are the interfaces used in OLE DRAG AND DROP?
OLE Drag and drop is used for the movement of the data object. OLE supports the
drag and drop operation with two interfaces,
• IDropSource
• IDropTarget
23. List out the process of OLE Drag and Drop .
The drag-and-drop process is as follows,
•
•
•
•
•
•
•
The MFC library provides good drag-and-drop operation at the view level
The drag-and-drop transfers are immediate and independent of the clipboard.
If the user cancels the operation then there is no "memory" of the object being
dragged.
Drag-and-drop transfers should work consistently between applications, between
windows of the same application, and within a window.
When the user starts the operation, the cursor should change to an arrow_rectangle
combination.
If the user holds down the Ctrl key, the cursor turns into a plus sign (+), which
indicates that the object is being copied rather than moved.
MFC also supports drag-and-drop operations for items in compound documents.
24. How the transfer takes place in Source Side of drag and drop operation?
When our source program starts a drag-and-drop operation for a data object, it calls
the function COleDataSource::DoDragDrop. This function internally creates an object of
MFC class COleDropSource, which implements the IOleDropSource interface.
DoDragDrop is one of the functions that do not return any value for a while, but it returns
when the user drops the object or cancels the operation or when a specified number of
milliseconds have elapsed. If we are perform drag-and-drop operations to work with a
CRectTracker object, we should call DoDragDrop only when the user clicks inside the
tracking rectangle, not on its border, and the function used to check that functionality is
CRectTracker::HitTest. When we call DoDragDrop, we need to set a flag that tells us
whether the user is dropping the object into the same view or document that it was dragged
from.
25. How the transfer takes place in destination Side of drag and drop operation?
If we want to use the MFC library's view class drag-and-drop support, we must add a
data member of class COleDropTarget to our derived view class. This class implements the
IDropTarget interface, and it holds an IDropSource pointer that links back to the
COleDropSource object. In our view's OnInitialUpdate function, we call the Register
member function for the embedded COleDropTarget object. Then after making a view drop
target, we must override four CView virtual functions, which the framework calls during the
drag-and-drop operation.
26. List out the drag and drop functions.
The functions are as follows,
OnDragEnter
Adjusts the focus rectangle and then calls OnDragOver
OnDragOver
Moves the dotted focus rectangle and sets the drop effect
(determines cursor shape)
OnDragLeave
Cancels the transfer operation; returns the rectangle to its
original position and size
OnDrop
Adjusts the focus rectangle and then calls the DoPaste helper
function to get formats from the data object
27. What are the types of OLE?
The object linking and embedding can be of two types
1. Embedding
2. In place activation
28. Define Embedding.
An embedded component can run only in its own window, and that window has a
special menu that does not include file commands. Some container applications support only
embedded components. Embedding is a subset of in-place activation. Embedding has two
key interfaces which are used for in-place activation
•
•
IOleObject
IOleClientSite
29. What is meant by In-Place Activation?
The In-place activation is also known as Visual Editing. A component that supports
in-place activation also supports embedding. Both in-place activation and embedding store
their data in a container's document, and the container can activate both. An in-placecapable component can run inside the container application's main window, taking over the
container's menu and toolbar, and it can run in its own top-level window if necessary. An inplace container program allows the user to activate in-place components either in place or in
their own windows.
30. What is a Metafile and give an example?
Metafiles are the integral part of Windows. For example consider the metafile as a
cassette tape for GDI instructions. To use a cassette, we need a player or recorder which is
the metafile device context (DC). If we specify a filename when we create the metafile DC,
our metafile will be saved on disk. Otherwise, it's saved in memory and we access it by
using the handle. In the OLE embedding, components create metafiles and a container uses
it to play them.
31. How we draw a rectangle with some text for a metafile?
The component code that creates a metafile containing some text and a rectangle is as
follows:
CMetaFileDC dcm; // MFC class for metafile DC
VERIFY (dcm.Create());
dcm.SetMapMode(MM_ANISOTROPIC);
dcm.SetWindowOrg(0,0);
dcm.SetWindowExt(5000, -5000);
// drawing code
dcm.Rectangle(CRect(500, -1000, 1500, -2000));
dcm.TextOut(0, 0, m_strText);
HMETAFILE hMF = dcm.Close();
ASSERT (hMF != NULL);
32. What is the use of SetwindowExt and SetViewportExt?
• The metafile contains a SetWindowExt call to set the x and y extents of the window
• The program that plays the metafile calls SetViewportExt to set the extents of the
viewport.
33. What is meant by Mini-Servers Linking?
A mini-server cannot be able to run as a stand-alone program. It depends on a
container application to launch it. It cannot do it own file I/O operations and it depends on the
container's files.
34. Define Full Servers Linking.
A full server can run both as a stand-alone program and from a container. When it's
running as a stand-alone program, it can read and write its own files, which mean that it
supports OLE linking. In embedding, the container document contains all the data that the
component needs. In linking, the container contains only the name of a file that the
component must open.
35. List out the Disadvantages of In-place Activation.
• From the programming point of view, In-place Activation is difficult for containers and
components to coordinate the size and scale of embedded objects.
• From the user’s point of view, in-place activation can be slow and uncomfortable
36. What are the Uses of Metafiles?
• The metafiles are used because the container needs to draw something in the
component's rectangle, even if the component program is not running.
• The component creates the metafile and hands it off in a data object to the inprocess OLE handler module on the container side of the Remote Procedure Call
(RPC) link.
• The handler then caches the metafile and plays it on demand and also transfers it to
and from the container's storage.
• When a component is in-place active its view code is drawing directly in a window
that is managed by the container.
37. List out the MFC OLE base classes.
The three new MFC OLE base classes are as follows,
• COleIPFrameWnd
• COleServerDoc
• COleServerItem.
38. What are the types of menus created in the OLE Component project?
• When we use AppWizard to generate an OLE component, then the AppWizard
generates a class derived from each of the base classes, in addition to an application
class, a main frame class, and a view class.
• The COleIPFrameWnd class is similar to CFrameWnd class.
• It is our application's main frame window, which contains the view.
• So when we use OLE Component in our project then we have three menu
ƒ IDR_SRVR_INPLACE
ƒ IDR_SRVR_EMBEDDED
ƒ IDR_MAINFRAME.
39. Define the menu types in OLE.
• It has a menu IDR_SRVR_INPLACE, which is inserted into the container program's
menu.
•
•
When our component program is running in place, it is using the in-place frame, and
when it is running stand-alone or embedded, it is using the regular frame, which is an
object of a class derived from CFrameWnd.
The embedded menu is IDR_SRVR_EMBEDDED, and the stand-alone menu is
IDR_MAINFRAME and they are shown below,
40. How the Loading and saving is done for the Component's Native Data?
The component can load and save its native data when the container calls the Load
and Save functions of IPersistStorage. But now the container is going to save the
component's class ID in the storage. The container can read the class ID from the storage
and use it to start the component program prior to calling IPersistStorage::Load. The
embedded object needs to be saved in the storage. The storage must always be available
because the object is constantly loading and saving itself and reading and writing temporary
data. The container manages the whole file, but the embedded components are responsible
for storing inside the storage. There is a main storage for each embedded object and the
container does not know what is actually stored inside.
41. What is meant by Clipboard Data Transfers?
• If we run any OLE container programs on the Microsoft excel, then we can copy and
paste the whole embedded objects.
• There is a special data object namely CF_EMBEDDEDOBJECT for embedded
objects.
• If we put an IDataObject pointer on the clipboard and that data object contains the
CF_EMBEDDEDOBJECT format, then another program can load the proper
component program and reconstruct the object.
• The only thing inside the CF_EMBEDDEDOBJECT format is an IStorage pointer.
• The clipboard copy program verifies that IPersistStorage::Save has been called to
save the embedded object's data in the storage, and then it passes off the IStorage
pointer in a data object.
• The clipboard paste program gets the class ID from the source storage, loads the
component program, and then calls IPersistStorage::Load to load the data from the
source storage.
42. How does the component deliver the metafile?
The component delivers the metafile by using IDataObject interface. The container
calls the function IDataObject::GetData and asks for CF_METAFILEPICT format. Then the
container is supposed to get the metafile even if the component program is not running.
43. Define Object handler.
If the component program is running, it is in a separate process. Sometimes it is not running
at all. In either case, the OLE32 DLL is linked into the container's process. This DLL is
known as the object handler.
44. List out the Component States.
The four component states that an embedded object can have are as follows,
State
Description
Passive
The object exists only in storage.
Loaded
The object handler is running and has a metafile in its cache, but
the EXE component program is not running.
Running
The EXE component program is loaded and running, but the
window is not visible to the user.
Active
The EXE component's window is visible to the user.
45. How the Interaction occurs between the container and component.
• When the container creates an embedded object, it calls IOleObject::SetClientSite
to establish one of the two connections from component to container.
• The site maintains an IOleObject pointer to its component object.
• When the component decides it’s time to save itself to its storage, it asks the site to
store by calling IOleClientSite::SaveObject.
• The handler needs to save the metafile to the storage.
• The SaveObject function calls IPersistStorage::Save at the handler level, so the
handler can store before calling the component's Save function.
• The component program calls the IOleClientSite function OnShowWindow when it
starts running and when it stops running.
46. Define Advisory Connection.
The IOleClientSite connection goes directly from the component to the container, but
the IAdviseSink connection is routed through the handler. After the site has created the
embedded object, it calls IViewObject2::SetAdvise, passing its IAdviseSink pointer. At that
time, the handler has gone ahead and established two advisory connections to the
component. When the embedded object is created, the handler calls IOleObject::Advise and
then calls IDataObject::DAdvise to notify the advise sink of changes in the data object.When
the component's data changes, it notifies the handler through the IDataObject advisory
connection. When the user saves the component's data or closes the program, the
component notifies the handler through the IOleObject advisory connection. When the
handler gets the notification that the component's data has changed it can notify the
container by calling IAdviseSink::OnViewChange. The container responds by calling
IViewObject2::Draw in the handler.
47. What is meant by Limitations of the Container?
• The container does not support in-place activation.
• It allows the user to edit embedded objects only in a separate window.
• The container supports only one embedded item per document, and that means
there's no linking support.
• The container uses a structured storage file to hold the document's embedded item,
but it handles the storage directly, bypassing the framework's serialization system.
• Clipboard support is provided and does not support drag-and-drop
48. List out the OLE interfaces.
The OLE interfaces are as follows,
•
•
•
•
The IOleObject Interface
The IViewObject2 Interface
IOleClientSite Interface
IAdviseSink Interface
49. What are the Features of containers?
• As an MFC MDI application, containers handle multiple documents.
• Containers display the component's metafile in a sizeable, moveable tracker
rectangle in the view window.
• Maintains a temporary storage for each embedded object.
• Implements the Insert Object menu option, which allows the user to select a
registered component. The selected component program starts in its own window.
• Allows embedded objects to be copied (and cut) to the clipboard and pasted. These
objects can be transferred to and from other containers such as Microsoft Word and
Microsoft Excel.
• Allows an embedded object to be deleted.
•
•
Tracks the component program's loaded-running transitions and hatches the tracker
rectangle when the component is running or active.
Redraws the embedded object's metafile on receipt of component change
notifications.
50. What are the functions of IAdviseSink Interface?
Containers implement this interface. Embedded object handlers call its functions in
response to component notifications.
Void OnClose(void);
The Component programs call this function when they are being terminated.
Void OnViewChange(DWORD dwAspect, …);
The handler calls OnViewChange when the metafile has changed. Because the
component program must have been running for this notification to have been sent, the
handler can call the component's IDataObject::GetData function to get the latest metafile for
its cache.
UNIT V –ADVANCED CONCEPTS
Two Mark Questions - PART A
1. List out the databases supported by VC++.
Windows programmers have various programmable database management systems
(DBMS's), such as,
•
•
•
•
Inprise Paradox
Microsoft Access
Microsoft FoxPro
Powersoft PowerBuilder
2. What is the data base connectivity in VC++?
These databases can access both local data and remote data on a central computer.
Visual C++ contains all the components that we need to write C++ database applications for
Microsoft Windows. The database connectivity in VC++ are as follows,
•
•
•
Open DataBase Connectivity (ODBC)
DataAccessObject (DAO)
OLE DB
3. What is the Purpose of Database?
• Database is used to store data
• Provide access to manipulate the data.
• Use of standard file formats
• Provides multiple user interaction
4. List out the Advantages of Database Management.
The advantages are as follows,
• Use of standard file formats
• Indexed file access
• Data integrity safeguards
• Multi-user access control
5. Define Structured Query Language (SQL)
Structured Query Language (SQL) is a standard database access language with its
own definitions. In SQL, a database is a collection of tables that consist of rows and
columns. Many Data Base Management Systems support SQL.
6. How the Database is accessed through ODBC?
ODBC is based on a standardized version of Structured Query Language (SQL).
This database access uses the ODBC API to access data from a variety of different data
sources. ODBC data base connection contains Driver Manager for performing the database
activities. The Microsoft Open Database Connectivity (ODBC) standard defines not only the
rules of SQL grammar but also the C-language programming interface to any SQL database.
It is now possible for a single compiled C or C++ program to access any DBMS that has an
ODBC driver.
7. List out the data base drivers supported by ODBC.
The ODBC Software Development Kit (SDK), included with Visual C++, contains 32bit database drivers for the following,
DBF files
• Microsoft Access MDB databases
• Microsoft Excel XLS files
• Microsoft FoxPro files
• ASCII text files
•
•
Microsoft SQL Server databases.
Microsoft Oracle Server
8. What are the Uses of ODBC?
• If we develop an MFC program with the dBASE/Xbase driver, then we can run
the same program with an Access database driver.
• No recompilation is needed since the program simply loads a different DLL.
• Not only can C++ programs use ODBC but other DBMS programming
environments can also take advantage of this new standard.
• We could write a C++ program to update a SQL Server database, and then we
could use an off-the-shelf ODBC-compatible report writer to format and print the
data.
• ODBC thus separates the user interface from the actual database-management
process.
• It is implemented by C native API
9. List out the MFC ODBC Classes.
There are 3 different Built in classes provided by MFC
CDatabase
- Manages the Connection to a data source.
- Work as a Database Manager
CRecordSet
- Manages a set of rows returned from the database.
- CRecordset represents scrollable rowsets.
CRecordView
- Simplifies the display of data from CRecordSet Object.
10. What is meant by CDatabase?
This class used to encapsulate our application's dealings with a connection to the
database. It perform ODBC API connection Handles. We can retrieve CDatabase object
associated with CRecordset by,
m_pSet->m_pDatabase variable in CRecordset
11. What are the Transactions that can be done with CDatabase?
Enables to execute a series of SQL statements as a single operation. In this if any
one of the operations fails, rest of all can be undone. This is most useful future for doing
related updation to various tables at the same time. The functions used are,
CanTransact()
BeginTrans()
ExecuteSQL()
CommitTrans()
Rollback ()
12. Define the class CRecordSet.
MFC Appwizard generates a CRecordSet derived class and returns a pointer named
m_pSet to our application program. CRecordset represents scrollable rowsets. We can
move the data back and forth from recordset to data base. The exchange is set up by
implementing the CRecordset:: DoFieldExchange() function, and it maps the member
variables of Recordset and Database.
13. What are the types of Record Set Selection?
Visual C++ provides 3 types of Recordset as follows,
• Snapshot
• Dynaset
•
Table
Snapshot:
•
•
•
•
Download the entire query in one shot
Have data as a static copy
When any changes made to the database will not reflect to the current
Application.
Occupy more memory to hold the data.
Dynaset:
•
•
•
•
Only the records you actually need to fill the screen will get downloaded.
Take less time to reflect.
Constantly resynchronizes the recordset, so that any changes will reflect
immediately.
The snapshot and Dynaset work at the record level. ODBC will only support both
this two options.
Table:
•
•
•
Work with table level and supported by DAO.
Places the contents of the query into Temporary table.
Have a problem with updation.
14. Define the CRecordView class.
This class is basically a form view and makes it easier to display data from a
recordset. It enables you to use dialog data exchange to display data directly in a dialog box
from the recordset. It will move data between the view controls and column data member
variables of CRecordset. The default implementation supplied by Class Wizard returns the
pointer stored in CRecordView ::m_pSet. The Functions of CRecordView classes are as
follows,
• DoDataExchange() - Perform dialog data exchange.
• OnGetRecordSet() - Retrieve a pointer of the CRecordset.
• OnMove() - takes only one parameter, specifying where to move. This can be
one of the following constants:
ƒ
ID_RECORD_FIRST
ƒ
ID_RECORD_LAST
ƒ
ID_RECORD_NEXT
ƒ
ID_RECORD_PREV
15. What are the ODBC Elements?
The three important ODBC elements are,
Environment
Connection
Statement
16. What is meant by Filter and Sort Strings?
SQL query statements can have an ORDER BY clause and a WHERE clause. The
CRecordset class has a public data member m_strSort that holds the text of the ORDER
BY clause. Another public data member, m_strFilter, holds the text of the WHERE clause.
17. How the Database is accessed with DAO?
This access type is supplied in the form of redistributable components. This type of
data base connectivity enables us to access and manipulate databases through the
Microsoft Jet database engine. It is similar to ODBC and does not support Remote
Communication. It is based on OLE.
18. What are the features of DAO?
The features of DAO are as follows,
• DAO is a set of COM interfaces, which is a set of pure virtual function declarations.
These interfaces have names such as DAOWorkspace, DAODatabase, and
DAORecordset.
•
The other feature of DAO is the implementation of those interfaces. Microsoft
supplies the COM module DAO350.DLL, which connects to the same Jet database
engine DLL that serves the Microsoft Access database product.
19. What are the MFC DAO Classes?
.
DAO Classes
20. Define the class CDaoDatabase.
This class represents a connection to a database. The functions are,
ƒ A connection is created by calling CDaoDatabase::Open and terminated by
calling CDaoDatabase::Close.
ƒ A new database can be created by calling CDaoDatabase::Create.
ƒ DeleteTableDef ()Deletes a DAO TableDef object and also the underlying table
and all its data from the database.
21. Define Threads.
The execution of a single instruction is a thread. The two types of threads are,
1. User interface (UI) threads
2. Worker threads.
22. List out the difference between the two types of threads.
• UI threads have message loops and a worker thread does not have message
loops.
• UI threads can create windows and process messages sent to those
windows.
• Worker threads perform background tasks that receive no direct input from
the user and therefore don't need windows and message loops.
23. Define User interface (UI) threads with an example.
When we open a folder in the operating system shell, the shell launches a UI thread
that creates a window showing the folder's contents. If you drag-copy a group of files to the
newly opened folder, that folder's thread performs the file transfers. This is the best example
for user interface threads. Launching a UI thread that creates a window is conceptually
similar to launching an application within an application. The most common use for UI
threads is to create multiple windows serviced by separate threads of execution.
24. How to Create a UI Thread?
Creating a UI thread is different process from creating a worker thread. A worker
thread is defined by its thread function, but a UI thread's behavior is governed by a
dynamically creatable class derived from CWinThread that resembles an application class
derived from CWinApp. The UI thread class shown below creates an output window that
closes itself when clicked with the right mouse button. Closing the window terminates the
thread, because CWnd::OnNcDestroy posts a WM_QUIT message to the thread's message
queue. Posting a WM_QUIT message to a secondary thread ends the thread and also the
application. The code is shown below,
25. Define Worker threads with an example.
Worker threads are ideal for performing isolated tasks that can be broken off from the
rest of the application and performed in the background. An example of a worker thread is
the thread that an animation control uses to play AVI clips. The thread in this application
does little more than draw a frame that put itself to sleep for a fraction of a second, and wake
up and repeat the process. It adds little to the processor's workload because it spends most
of its life suspended between frames, and yet it also provides a valuable service.
26. How to Create a Worker Thread?
The best way to launch a thread in an MFC application is to call AfxBeginThread.
MFC defines two different versions of AfxBeginThread:
•
•
One that starts a UI thread
Another that starts a worker thread.
The function AfxBeginThread is used to create the worker thread. When called,
AfxBeginThread creates a new CWinThread object, launches a thread and attaches it to the
CWinThread object, and returns a CWinThread pointer. The statement used to create the
worker thread is shown below,
CWinThread* pThread = AfxBeginThread (ThreadFunc, &threadInfo);
The above statement starts a worker thread and passes it the address of an applicationdefined data structure (&threadInfo) that contains input to the thread. ThreadFunc is the
thread function that gets executed when the thread itself begins to execute. The complete
function prototype is as follows:
27. How to Suspend and Resume the Threads?
• A running thread can be suspended with CWinThread::SuspendThread and started
again with CWinThread::ResumeThread.
• The suspended thread cannot call ResumeThread to wake by itself; it needs some
other thread to resume it by calling ResumeThread on its behalf.
• For each thread, Windows maintains a suspend count that's incremented by
SuspendThread and decremented by ResumeThread.
• A thread is scheduled for processor time only when its suspend count is 0. If
SuspendThread is called twice in succession, ResumeThread must be called twice
also.
•
A thread created without a CREATE_SUSPENDED flag has an initial suspend count
of 0.
• A thread created with a CREATE_SUSPENDED flag begins with a suspend count of
1
28. How to make the Threads to Sleep?
A thread can put itself to sleep for a specified period of time by calling the API
function ::Sleep. A sleeping thread uses no processor time. The statement ::Sleep (10000)
suspends the current thread for 10 seconds. One use for ::Sleep is to implement threads
whose actions are inherently time-based, such as the background thread in an animation
control or a thread that moves the hands of a clock. ::Sleep can also be used to relinquish
the remainder of a thread's timeslice. The statement ::Sleep (0); suspends the current
thread and allows the scheduler to run other threads of equal or higher priority.
29. How to terminate a Thread?
Once a thread begins, it can terminate in two ways.
1. A worker thread ends when the thread function executes a return statement or when
any function anywhere in the thread calls AfxEndThread.
2. A UI thread terminates when a WM_QUIT message is posted to its message queue
or when the thread itself calls AfxEndThread.
A thread can post a WM_QUIT message to itself with the API function ::PostQuitMessage.
AfxEndThread, ::PostQuitMessage, and return all accept a 32-bit exit code that can be
retrieved with ::GetExitCodeThread after the thread has terminated.
30. List out the priority of the thread.
The priority of the thread is shown below in a table,
Priority Value
Description
THREAD_PRIORITY_ID
LE
The thread's base priority level is 1 if the process's priority
class is HIGH_PRIORITY_CLASS or lower, or 16 if the
process's priority class is REALTIME_PRIORITY_CLASS.
THREAD_PRIORITY_LO
WEST
The thread's base priority level is equal to the process's
priority class minus 2.
THREAD_PRIORITY_BE
LOW_NORMAL
The thread's base priority level is equal to the process's
priority class minus 1.
THREAD_PRIORITY_N
ORMAL
The default thread priority value. The thread's base priority
level is equal to the process's priority class.
THREAD_PRIORITY_AB
OVE_NORMAL
The thread's base priority level is equal to the process's
priority class plus 1.
THREAD_PRIORITY_HI
GHEST
The thread's base priority level is equal to the process's
priority class plus 2.
THREAD_PRIORITY_TI
ME_CRITICAL
The thread's base priority level is 15 if the process's
priority class is HIGH_PRIORITY_CLASS or lower, or 31 if
the
process's
priority
class
is
REALTIME_PRIORITY_CLASS.
31. What is Network Protocol?
The application program talks to the top layer and the bottom layer talks to the
network. The following figure shows us the stack for a local area network (LAN) running
TCP/IP. Each layer is logically connected to the corresponding layer at the other end of the
communications channel. The server program, as shown at the right is continuously listens
on one end of the channel, while the client program, as shown on the left, periodically
connects with the server to exchange data.
LAN running TCP/IP.
32. What is Internet Protocol?
The Internet Protocol (IP) layer is TCP/IP. The IP protocol defines packets called
datagrams that are the fundamental units of Internet communication. These packets have
less than 1000 bytes in length.
IP datagram layout.
33. Define User Datagram Protocol with its format
The TCP/IP protocol should really be called TCP/UDP/IP because it includes the
User Datagram Protocol (UDP), which is a peer of TCP. All IP-based transport protocols
store their own headers and data inside the IP data block. The UDP layout is shown below,
34. What is the relationship between IP and UDP datagram?
35. Define IP Address Format.
IP addresses are 32-bits long. 232 (more than 4 billion) uniquely addressed
computers could exist on the Internet. Part of the address identifies the LAN on which the
host computer is located, and part of it identifies the host computer within the network. Most
IP addresses are Class C addresses, which are formatted as shown below,
Layout of a Class C IP address.
36. What is meant by WINSOCK and its types?
Winsock is the lowest level Windows API for TCP/IP programming. Part of the code
is located in wsock32.dll, and part is inside the Windows kernel. We can write both internet
server programs and internet client programs using the Winsock API. This API is based on
the original Berkely Sockets API for UNIX. The types of winsock are,
ƒ
ƒ
ASynchronous winsock mode
Synchronous winsock mode.
37. Define Asynchronous Winsock mode.
In asynchronous mode, all sorts of hidden windows and PeekMessage calls
enabled single-threaded programs to make Winsock send and receive calls without blocking,
thus keeping the user interface (UI) alive. Asynchronous Winsock programs were complex,
often implementing "state machines" that processed callback functions.
38. Define Synchronous Winsock mode.
In synchronous mode, all sorts of hidden windows and PeekMessage calls enabled
multi-threaded programs and its simplex.
39. List out the MFC Winsock Classes.
40. Define Blocking Socket Classes.
CBlockingSocket is a thin wrapping of the Winsock API, designed only for
synchronous use in a worker thread. The features are,
• Exception-throwing on errors
• Time-outs for sending and receiving data.
The exceptions help us to write cleaner code because we don't need to have error tests after
every Winsock call. CHttpBlockingSocket is derived from CBlockingSocket and provides
functions for reading HTTP data. CSockAddr and CBlockingSocketException are helper
classes.
41. Define CBlockingSocketException Class.
• All CBlockingSocket functions throw a CBlockingSocketException object when
Winsock returns an error.
• This class is derived from the MFC CException class and thus overrides the
GetErrorMessage function.
• This function gives the Winsock error number and a character string that
CBlockingSocket provided when it threw the exception.
42. What is the purpose of CSockAddr Helper Class?
Many Winsock functions take socket address parameters. A socket address consists
of a 32-bit IP address plus a 16-bit port number. The actual Winsock type is a 16-byte
sockaddr_in structure, which is as follows,
struct sockaddr_in
{
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
43. How to Start the Server in Winsock?
The server starts in response to some user action, such as a menu choice. The
command handler is as follows,
CBlockingSocket g_sListen;
void CSocketView::OnInternetStartServer()
{
try {
CSockAddr saServer(INADDR_ANY, 80);
g_sListen.Create();
g_sListen.Bind(saServer);
g_sListen.Listen();
AfxBeginThread(ServerThreadProc, GetSafeHwnd());
}
catch(CBlockingSocketException* e) {
g_sListen.Cleanup();
e->Delete (); }}
44. Define CBlockingSocketException Class.
• All CBlockingSocket functions throw a CBlockingSocketException object when
Winsock returns an error.
• This class is derived from the MFC CException class and thus overrides the
GetErrorMessage function.
• This function gives the Winsock error number and a character string that
CBlockingSocket provided when it threw the exception.
45. Define WININET.
WinInet is a higher-level API than Winsock, but it works only for HTTP, FTP, and
gopher client programs. The types are
• Asynchronous WinInet mode
• Synchronous WinInet mode.
46. Discuss about IIS Security.
• After we double-click on the WWW service icon of the Microsoft Internet Service
Manager screen, we could see a property sheet.
• The Service page lets us to configure IIS security.
• Most Web page visitors do not supply a user name and password, so they are
considered anonymous users.
• Those users have the same rights they would have if they had logged on to our
server locally as IUSR_MYMACHINENAME.
• The IIS Setup program normally defines this anonymous user for us.
47. What are the advantages of WinInet?
WinInet benefits are as follows,
Caching - WinInet client program caches HTML files and Internet files. The second time our
client requests a particular file, it is loaded from a local disk instead of from the Internet.
Security: WinInet supports basic authentication, Windows NT challenge / response
authentication, and the Secure Sockets Layer (SSL).
Web proxy access: we enter proxy server information through the Control Panel, and it is
stored in the Registry. WinInet reads the Registry and uses the proxy server when required.
Buffered I/O: WinInet's read function does not return until it can deliver the number of bytes
we asked for. Also, we can read individual text lines.
Easy API: Status callback functions are available for UI update and cancellation. One
function, CInternetSession::OpenURL finds the server's IP address, opens a connection,
and makes the file ready for reading. Some functions even copy Internet files directly to and
from disk.
User friendly: WinInet parses and formats headers. If a server has moved a file to a new
location, it sends back the new URL in an HTTP Location header.
48. What are the MFC WinInet Classes?
WinInet is a modern API available only for Win32. The MFC wrapping is efficient,
which means we need not have to write our own WinInet class library. MFC WinInet
supports blocking calls in multithreaded programs. The MFC classes are as follows,
• CInternetSession
• CHttpConnection
• CFtpConnection
• CGopherConnection
• CInternetFile
• CHttpFile
• CFtpFileFind
• CGopherFileFind
• CInternetException
49. Define CInternetSession class.
We need only one CInternetSession object for each thread that accesses the
Internet. After we have our CInternetSession object, we can establish HTTP, FTP, or gopher
connections or we can open remote files directly by calling the OpenURL member function.
We can use the CInternetSession class directly, or we can derive a class from it in order to
support status callback functions. The CInternetSession constructor calls the WinInet
InternetOpen function, which returns an HINTERNET session handle that is stored inside the
CInternetSession object.
50. Define CHttpConnectioc class.
An object of class CHttpConnection represents a "permanent" HTTP connection to a
particular host. WinInet gives the appearance of a permanent connection because it
remembers the host name. After we have our CInternetSession object, we call the
GetHttpConnection member function, which returns a pointer to a CHttpConnection object.
The GetHttpConnection member function calls the WinInet InternetConnect function, which
returns an HINTERNET connection handle that is stored inside the CHttpConnection object
and used for subsequent WinInet calls.
51. What is the purpose of CInternetFile class?
With HTTP, FTP, or gopher, our client program reads and writes byte streams. The
MFC WinInet classes make these byte streams look like ordinary files. CInternetFile is
derived from CStdioFile, which is derived from CFile. Therefore, CInternetFile and its derived
classes override familiar CFile functions such as Read and Write. For FTP files, we use
CInternetFile objects directly, but for HTTP and gopher files, we use objects of the derived
classes CHttpFile and CGopherFile. We do not construct a CInternetFile object directly, but
we call CFtpConnection::OpenFile to get a CInternetFile pointer.
52. Define CHttpFile Class.
This Internet file class has member functions that are unique to HTTP files, such as
AddRequestHeaders, SendRequest, and GetFileURL. We do not construct a CHttpFile
object directly, but we call the function CHttpConnection::OpenRequest, which calls the
WinInet HttpOpenRequest function and returns a CHttpFile pointer. we can specify a GET or
POST request for this call. Once we have our CHttpFile pointer, we call the
CHttpFile::SendRequest member function, which actually sends the request to the server.
Then we call Read function.
53. Define INTERNET INFORMATION SERVER.
Internet Information Server (IIS) 4.0 is bundled with Microsoft Windows NT Server
4.0. IIS is actually three separate servers
1. One for HTTP (for the World Wide Web)
2. Another for FTP
3. Next one for gopher.
The two kinds of extensions are:
1. ISAPI server extension
2. ISAPI filter, both of which are DLLs.
An ISAPI server extension can perform Internet business transactions such as order entry.
An ISAPI filter intercepts data traveling to and from the server and thus can perform
specialized logging and other tasks.
54. What is meant by IIS Logging?
IIS is capable of making log entries for all connections. We can control logging from
the Internet Service Manager's Logging property page. We can specify text log files, or we
can specify logging to an SQL/ODBC database. Log entries consist of date, time, client IP
address, file requested, query string, and etc...
55. Define ISAPI SERVER EXTENSION.
An ISAPI server extension is a program (implemented as a DLL loaded by IIS) that
runs in response to a GET or POST request from a client program (browser). The browser
can pass parameters to the programs, which are the values that the browser user types into
edit controls, selects from list boxes, etc. The ISAPI server extension typically sends back
HTML code based on those parameter values.
56. What are the MFC ISAPI Server Extension Classes?
The three MFC classes that are used to create an MFC ISAPI server extension are
as follows,
• CHttpServer
• CHttpServerContext
• CHtmlStream
57. Define CHttpServer class.
With the help of the ISAPI Extension Wizard, we derive a class from CHttpServer for
each ISAPI server extension DLL that we create. We need one member function for each
extension function, and we need an overridden GetTitle function. The framework calls our
extension functions in response to client requests, using the connections established in the
parse map. The ISAPI Extension Wizard provides an overridden function
GetExtensionVersion, which we edit unless we need initialization code to be executed
when the DLL is loaded. One of the CHttpServer member functions that we call is
AddHeader, which adds special response headers, such as Set-Cookie, before the
response is sent to the server.
58. What is the use of CHttpServerContext Class?
There is one CHttpServer object per DLL, but there is one CHttpServerContext object
for each server transaction request. We do not derive from CHttpServerContext, so we
cannot easily have variables for individual transactions. Because different IIS threads can
manage transactions and we have to perform synchronization for any data members of our
CHttpServer class or global variables. We have already seen the use of the StartContent,
EndContent, and WriteTitle functions of the CHttpServer class plus the overloaded >>
operator.
59. What are the classes are there to play multimedia files?
• CSoundIn is a wrapper class that lets us to retreive sound from the soundcard. The
main functions are Start() and Stop()
• CSoundOut is a wrapper class that will lets us to play sound on the soundcard. The
main functions are Start() and Stop()
• CSoundFile is a wrapper class of a single wave file, it can either be a file reader or a
file writer object. See the constructor.
• CSoundBase is a very small class that encapsulates the wave format.
• CBuffer is a very small class that encapsulates a simple one dimentional buffer.
60. Write a Program to play mp3 and AVI files.
This program plays files of mp3 and avi format. This program is an illustration to use
MCIWnd class. The main function or API is MCIWndCreate(). The MCIWndCreate function
registers the MCIWnd window class and creates an MCIWnd window for using MCI services.
MCIWndCreate can also open an MCI device or file (such as an AVI file) and associate it
with the MCIWnd window.
HWND m_Video;
m_Video = NULL;
if(m_Video == NULL)
{
/*The MCIWndCreate function registers the MCIWnd window class
and creates an MCIWnd window for using MCI services.*/
m_Video = MCIWndCreate(this->GetSafeHwnd(),
AfxGetInstanceHandle() ,WS_CHILD |
WS_VISIBLE|MCIWNDF_NOMENU,m_Path);
}
else
{
MCIWndHome(m_Video); // go to the start
}
MCIWndPlay(m_Video); // play the file
Similarly we can use MCIWndPause(m_Video)
MCIWndResume(m_Video) to resume the file.
BOOL Pause;
if(Pause)
{
MCIWndResume(m_Video);
Pause = FALSE;
}
else
{
MCIWndPause(m_Video);
Pause = TRUE;
}
for
pausing
or
the
function
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertising