Paper - X Visual Programming
Paper - X Visual Programming
(PRIDE)
PERIYAR UNIVERSITY
SALEM - 636 011.
1
Prepared by :
S. ARANGANAYAGI, M.C.A.
S.G.Lecturer in Computer Science
J.K.K.Nataraja College of Arts & Science
Komarapalayam – 638 183
2
MASTER OF COMPUTER APPLICATIONS (MCA)
SECOND YEAR
PAPER – X : VISUAL PROGRAMMING
UNIT – 1
1. WINDOWS PROGRAMMING
GUI concept
Hungarian Notation
Data types
Handles
THE WINMAIN() FUNCTION
Message Driven Architecture
Message Loop
GDI
Keyboard handling
Mouse handling
Displaying Text and Graphics
Dialog Boxes and Controls
Files
Clipboard
Printers
DDE
DLL
OLE
COM
UNIT –II
2. VC++
2.1 Microsoft Foundation Classes (MFC)
2.2 Messages and Events
2.2.1 Windows Messages
2.2.2 Command Messages
2.2.3 Keyboard Messages
2.2.4 Mouse Messages
2.2.5 Conditional Messages
3
2.3 Windows Resources
2.3.1 Creating resources
2.3.2 Overview of icons
2.3.3 Menus
2.3.4 Introduction to Toolbars
2.3.5 Introduction to Accelerators
2.3.6 Shortcuts
2.3.7 Accelerator table
2.3.8 Version
2.3.9 Cursor
2.3.10 String Tables
UNIT-III
3.1 Dialog Box
3.1.1 The Mfc Wizard For A Dialog-Based Application
3.1.2 Properties Of A Dialog Box
3.1.3 Dialog Box Methods
3.2 Controls Fundamentals
3.3 Controls
3.4 MFC Control Classes
3.4.1 Static Control
3.4.2 Button Control
3.4.3 Edit Box
3.4.4 Combobox
3.4.5 Radio Button
3.4.6 Check Box
3.4.7 Group Box
3.4.8 Tree Control
3.4.9 List Box
3.4.10 Slider Control
3.4.11 Progress Bar Control
3.4.12 Image List
3.5 Common Dialog Controls
3.6 Active X
3.7 Data Base Applications
4
UNIT –IV
4. VISUAL BASIC
4.1 Introduction
4.2 Features of Visual Basic
4.3 Integrated Development Environment
4.4 Controls
4.4.1 Working With A Control
4.5 Variables
4.5.1 Declaring Variables
4.5.2 Assignment Statements
4.6 Data Types
4.7 Constants
4.8 Converting Data Type
4.9 Arrays
4.10 Control Structures
4.11 Functions And Procedures
4.12 Built-In Function
4.12.1 String Function
4.12.2 Numeric Functions
4.12.3 Date Function
4.12. 4 Other Financial Functions
4.13 Forms
4.14 Properties
4.15 MDI Forms
UNIT - V
5.1 Events
5.1.1 Event Driven Programming
5.1.2 Key Events
5.2 Menus
5.3 Common Dialog Control
5.4 RichTextBox Control
5.5 Input Boxes
5.6 Message Box
5.7 The Flex Grid Control
5
5.8 Data Grid
5.9 Introduction To Graphics
5.9.1 Fundamentals Of Graphics
5.9.2 Screen Scales
5.9.3 The Line And Shape Controls
5.9.4 Graphics Via Code
5.9.5 Lines And Boxes
5.9.6 Filled Boxes
5.9.7 Circles, Ellipses And Pie Charts
5.10 Database
5.11. Building Your Own Activex Controls
6
UNIT - I
1. WINDOWS PROGRAMMING
INTRODUCTION:
Microsoft Windows is a multi-tasking operating system that allows
multiple applications also refereed as processes. Every process in Windows is
given a certain amount of time, called a time slice, where the application is
given the right to control the system without being interrupted by the other
processes. The runtime priority and the amount of time allocated to a process
are determined by the scheduler. The scheduler is, simply put, the manager of
this multi-tasking operating system, ensuring that each process is given the time
and the priority it needs depending on the current state of the system. Windows
is what is known as an event-driven operating system. This means that each
process is executed based on the events they receive from the operating system.
For instance, an application may sit at idle and wait for the user to press a key.
When that key is pressed Windows will register an event to the application that
the key is down.
1.1 GRAPHICAL USER INTERFACE (GUI)
DEFINITION
A GUI interface allows the users to navigate and interact with
information on their computer screen by using a mouse to ‘point’, ‘click’ and
‘drag’ the icons and other data on the screen instead of typing in words and
phrases. Example of GUI is Windows operating system.
Advantages of GUI
very user friendly
Requires less human intervention and more machine work.
Cost effective
Background printing
Multiple programs running
Advanced built-in utilities
Text Based System Vs GUI
Text Based System Graphical User Interface
Based only on characters Includes both characters and graphics
7
Terms Used in GUI:
Icon:
A small image, usually symbol, used to graphically represent a software
program file or function on a computer screen. Icon makes it easier to recognise
and locate these things.
Click or (Single click):
Click or single click is operating the left side of the mouse button once.
Double Click:
Double click is the operation of clicking the left side button of the
mouse two times.
Right Click:
Right Click is the operation of clicking the right side button of the
mouse.
Drag and Drop:
Using Mouse, the user can make a single click on the object , moves it
to the preferred location by pulling it and putting it.
Mouse Pointers:
Pointers used to point and make a click on the icons.
1.2 HUNGARIAN NOTATION:
Microsoft’s Chief Architect Dr.Charles Simonyi introduced an identifier
naming convention that adds a prefix to the identifier name to indicate the
functional type of the identifier. This system is widely used in Microsoft. This
method is known as Hungarian Notation.
Advantages of the conventions:
The following naming conventions provide a very convenient
framework for generating names that satisfy the above criteria. The basic idea
is to name all quantities by their types.
i) The names are mnemonic.
ii) The names will be suggestive. We will be able to map any name
into the type of the quantity hence obtaining information about the
shape and the use of the quantity.
iii) The names will be consistent because they have produced by the
same rules.
iv) The decision on the name will be mechanical, thus speedy.
v) Expressions in the program can be subjected to consistency checks.
8
pX Pointer to X
9
stored in a fixed location in memory, whereas that pointer points to
a movable block. If applications start form the handle whenever they
access the block the operating system can perform memory
management tasks such as garbage collection without affecting the
applications.
2. Any token that an application can use to identify and access an
object such as device, a file, a window or a dialog box.
User defined handles permit developers to design handles that are
meaningful to the application. A user defined handle can be defined in a type
declaration not in a function declarator.
When the remote procedure has a user defined handle as a parameter or
as an implicit handle the client stubs call the binding routine after the remote
call.
1.5 THE WINMAIN() FUNCTION
The WinMain() function is the entry point to your program, i.e, the
execution of the program starts with WinMain().
int WINAPI WinMain (
HINSTANCE hInstance,
HINSTANCE hprevInstance,
LPCTSTR lpCmdLine,
int nCmdShow);
Parameters:
hInstance
Handle to the current instance of an application.
hPrevInstance
Handle to the previous instance of the application. For a win32 based
application this parameter is NULL.
lpCmdLine
Pointer to a null terminated string specifies the command line for the
application, excluding the program name. To retrieve the entire command line
use GetCommandLine function.
nCmdShow
Specifies how the window is to be shown. Values of this parameter is
given below:
Value Meaning
SW_HIDE Hides the window and activates another window
SW_MINIMIZE Minimizes the specified window and activates the
top-level window in the system’s list
10
SW_RESTORE Activates and displays a window. The
window is restored to its original size
SW_SHOW Activates a window and displays it in its
current size and position
SW_SHOWMAXIMIZED Activates a window and displays it as
maximized window
SW_SHOWMINIMIZED Activates a window and displays it as
minimized window
SW_SHOWMINNOACTIVE Displays a window as an icon. The active
window remains active.
SW_SHOWNORMAL Activates and displays a window. If the
window is maximized or minimized
restored to its original size and position.
Return values:
If the function succeeds, terminating when it receives a WM_QUIT
message it should return the exit value contained in that message’s wparam
parameter. If the function terminates before entering the message loop it should
return
The WinMain function must
1. Define a window class
2. Register the class (RegisterClassEx)
3. Create Window (CreateWindowEx)
4. Display Window (ShowWindow)
5. Get the message loop running(while(GetMessage(...)))
Register Window Classes:
The graphical screen displyed is known as window. Each program with
a box around it, each button, each text box are all called windows. This must
mean that there are a large number of options and customizations available in
order to get things as different as textboxes and scroll bars from the same
method. Each window has an associated "Window Class" that needs to be
registered with the system, to specify the different properties of the window.
This is done by following 2 steps:
1. Fill in the fields of the WNDCLASS data object
2. Pass the WNDCLASS object to the RegisterClass function.
Also, there is an "extended" version of this procedure, that can be
followed with similar results:
1. Fill in the fields of the WNDCLASSEX object
2. Pass the WNDCLASSEX object to the RegisterClassEx function.
11
Either of these methods can be used to register the class, but the -Ex version
has a few more options.Once the class is registered, you can discard the
WNDCLASS structure, because you don't need it anymore.
Structure of WNDCLASS:
typedef struct {
UINT style;
WNDPROC lpfnWndProc;
int cbClsExtra;
int cbWndExtra;
HINSTANCE hInstance;
HICON hIcon;
HCURSOR hCursor;
HBRUSH hbrBackground;
LPCTSTR lpszMenuName;
LPCTSTR lpszClassName;
} WNDCLASS, *PWNDCLASS;
Create Windows:
Creating Windows can be done with the CreateWindow or the
CreateWindowEx functions. Both perform the same general task, but again, the
-Ex version has more options. You pass some specifics to the CreateWindow
function, such as the window size, the window location (the X and Y
coordinates), the window title, etc. CreateWindow will return a HWND data
object, that is a handle to the newly created window. Next, most programs will
pass this handle to the ShowWindow function, to make the window appear on
the screen.
The Window Procedure:
A window procedure may be named anything you want, but the general
prototype for one is as follows:
LRESULT CALLBACK WinProc (HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam);
An LRESULT data type is a generic 32-bit data object, that can be
type-casted to contain any 32-bit value (including a pointer). The hwnd
parameter is a handle to the window itself. The msg data value contains the
current message from the operating system, and the WPARAM and LPARAM
values contain the arguments for that message. For instance, if a button is
pressed on the keyboard, the msg field will contain the message
12
WM_KEYDOWN, and the WPARAM field will contain the actual letter
pressed ('A' for instance), and the LPARAM field will contain information on
whether or not the CTRL, ALT, or SHIFT buttons are down, and whether the
type-matic repeat function has been triggered. Several macros have been
defined that are very useful in separating out the WPARAM and LPARAM
into different sized chunks:
Example of a general Window Procedure:
LRESULT CALLBACK MyWinProc (HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc (hwnd, msg, wParam, lParam);
}
return 0;
}
Most window procedures only contain a simple loop that searches for
particular messages from the system, and then acts on them. In this example,
we are only looking for the WM_DESTROY message, which is the message
that the kernel sends to the window when the window needs to close. In
response to the WM_DESTROY message, the window calls the
PostQuitMessage function, which puts a WM_QUIT message into the message
queue. When the message loop (described above) gets the WM_QUIT
message, it breaks from the loop, and returns the value from the
PostQuitMessage function.
Any message that is not handled by the loop should be (must be) passed
to the DefWindowProc function. DefWindowProc will perform some default
actions based on the messages received, but it won't do anything interesting. If
you want your program to do something, you should not pass all your messages
to DefWindowProc.
1.6 MESSAGE DRIVEN ARCHITECTURE
MESSAGE
A structure or set of parameters used for communicating information or
a request. Messages can be passed between the operating system and an
application, different applications, threads within an application, and windows
within an application.
13
Applications written for Micro Soft Windows are “message driven”. In
response to events such as mouse clicks, keystrokes, window movements and
so on. Window sends messages to the proper window framework applications
process Windows messages like any other applications for windows. The
framework also provides some enhancements that make processing messages
easier more maintainable and better encapsulated.
The message loop in the Run member function of class CWinApp
retrieves queued messages generated by various events. For example when the
user clicks the mouse, Windows sends several mouse-related messages, such as
WM_LBUTTONDOWN when the left mouse button is pressed and
WM_LBUTTONUP when the left mouse button is released. The framework’s
implementation of the application message loop dispatches the message to the
appropriate window.
There are three main categories:
1. Windows messages
This includes primarily those messages beginning with the WM-
prefix, except for WM_COMMAND. Windows and views handle
Windows messages. These messages often have parameters that is
be used in determining how to handle the message.
2. Control notifications
This includes WM_COMMAND notification messages form
controls and other child windows to their parent windows. For
Example, an edit control sends its parent WM_COMMAND
message containing the EN_CHANGE control notification code
when the user has taken an action that may have altered text in the
edit control. The windows handler for the message responds to the
notification message in some appropriate way such as retrieving the
text in the control. The framework routes control notification
messages like other WM_ messages. One Exception is the
BN_CLICKED control notification message, this message is treated
specially as a command message and routed like other commands.
3. Command Messages
This includes WM_COMMAND notification messages from user
interface objects: menus, tool bar buttons and accelerator keys. The
framework processes commands differently from other messages
and they can be handled by more kinds of objects.
1.7 MESSAGE LOOP
When no windows messages are being processed the framework calls
CWinApp member function OnIdle. Override OnIdle to perform background
tasks. The default version updates the states of user interface objects such as
tool bar buttons and performs clean up of temporary objects created by the
framework in the course of its operations. A program loop is the one that
14
retrieves messages from a thread’s message queue and dispatches them to the
appropriate window procedures.
yes
Availabl Get/translate/Dispatch
e
message
no
Idle
Processing
yes
Availabl
e
message
no
yes
More
idle
tasks
no
Sleep
Until
Message
MESSAGE MAP:
A mechanism to route Window messages and commands to the
windows, documents, views and other objects in MFC application. Each
framework class that can receive messages or commands has its own “message
map”. The framework uses message maps to connect messages and commands
to their handler functions.
15
Edit Clear All menu
item selected
ID_EDIT_CLEAR_ALL
Document Object
OnEditClearAll()
When windows messages are being processed, the framework calls the
CWinApp member function Run member function. A framework application
spends most of its time in the rum member function of class CWinApp. After
initialization, WinMain calls Run to process the message loop.
A simple message loop consists of one function call to each of the three
functions, GetMessage, TranslateMessage and DispatchMessage.
MSG msg;
While(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
The GetMessage function retrieves a message form the queue and
copies it to a structure of type MSG. It returns a nonzero value unless it
encounters the WM_QUIT message, in which case it returns FALSE and ends
the loop. In a single threaded application, ending the message loop is often the
first step in closing the application. An application can end its own loop by
using the PostQuitMessage function, typically in response to the
WM_DESTROY message in the window procedure of the application’s main
window.
16
A thread’s message loop must include translateMessage if the thread is
to receive character input from the keyboard. The system generates virtual key
messages( WM_KEYDOWN and WM_KEYUP) each time the user presses a
key. A virtual key message contains a virtual key code that identifies which key
was pressed, but not its character value. To retrieve this value the message loop
must contain TranslateMessage, which translates the virtual key message into a
character message(WM_CHAR) and places it back into the application
message queue. The character message can then be removed upon a subsequent
iteration of the message loop and displayed to a window procedure.
The DispatchMessage function sends a message to the window
procedure associated with the window handle specified in the MSG structure. If
the window handle is NULL, DispatchMessage does nothing with the message.
An application’s main thread starts its message loop after initializing the
applications and creating atleast one window. Once started the message loop
continues to retrieve messages from the thread’s message queue and to dispatch
them to the appropriate windows. The message loop ends when the
GetMessage function removes the WM_QUIT message from the message
queue. When no window messages are being processed, the framework calls
the member function OnIdle.
Messages:
WM_CREATE
Your window receives this message only once, when it is first created.
Use this message to perform tasks that need to be handled in the beginning,
such as initializing variables, allocating memory, or creating child windows
(buttons and textboxes).
WM_PAINT
This message indicates that it is time for the program to redraw itself.
Use the graphical functions to redraw whatever is supposed to be on the
window.
WM_COMMAND
This is a general message that indicates that the user has done
something on your window. Either the user has clicked a button, or the user has
selected a menu item, or the user has pressed a special "Accelerator" key
sequence. The WPARAM and LPARAM fields will contain some descriptions
on what happened, so you can find a way to react to this. If you do not process
the WM_COMMAND messages, the user will not be able to click any buttons,
or select any menu items, and that will be very frustrating indeed.
WM_CLOSE
The user has decided to close the window, so the kernel sends the
WM_CLOSE message. If the WM_CLOSE message is passed to the
DefWindowProc, then the window will receive the WM_DESTROY message.
WM_CLOSE means that the window should disappear, and the
17
WM_DESTROY message means that the window should be closed completely,
and unloaded from memory. If you do not want the window to be destroyed
when "X" button is pressed, then you should handle the WM_CLOSE message,
and have it not destroy the window. As we mentioned earlier, the
WM_DESTROY message can send the WM_QUIT message, which will exit
the program. It is a bad idea to quit the program without first destroying the
window, because then the kernel will need to clean up the memory, and that
will take more time.
1.8 GRAPHIC DEVICE INTERFACE (GDI) :
Applications draw to an output device by calling Graphic Device
Interface (GDI) functions. The GDI library gdi.dll calls device drivers. The
device drivers perform specific operations on the actual physical hardware.
The graphical component of the Microsoft Windows graphical environment is
the graphic device interface. It communicates between the application and the
device driver.
In the GDI environment there are two working spaces, logical and
physical. Logical space is inhibited by applications whereas physical space is
the real world of devices with limited color, different output formats and
drawing capabilities.
The objects in the GDI are pen, brushes, fonts, palettes and bitmaps.
Objects are converted from logical objects to physical objects using the
realization process.
Graphic object Associated Attributes
Bitmap size in bytes, dimensions, in pixels, color
format, compression schemes and so on.
Brush style, color, pattern and origin
Palette Colors and size
Font Typeface name, width, height, weight,
character set and so on
Path shape
Pen style, width and color
Region Location and dimensions
Brush:
Brushes are used to fill the interior of drawing objects. A brush is
created by CreateBrushIndirect function. This function accepts a pointer to
LOGBRUSH structure which specifies the brush style, color and pattern.
A brush pattern can be based on bitmap. In order to provide a smooth
appearance it is necessary to align the origin of a brush bitmap. Applications
can explicitly specify the origin through SetBrushOrgEx. The brush origin is a
pair of coordinates with respect to the upper left corner of the window’s client
18
area. Additional functions assisting in the creation of brushes are
CreateSolidBrush, CreatePatternBrush and CreateHatchBrush.
Pen:
Pens are used to draw lines, curves and the contours of other shapes. A
pen is created using the CreatePen function. When calling CreatePen
applications specify the pen’s width, style and color. The LOGPEN structure
defines the pen’s width, color and style.
Font:
Before displaying an output text, select a logical font for text output.
Logical fonts are created by calling the CreateFont function.This function takes
a LOGFONT structure as a parameter.
Icon:
Icons and cursors are like images but have attributes that distinguish
them from images. When we create a new icon or cursor, the graphics editor
first creates an image for VGA. The image is initially filled with the screen
color. If the image is a cursor, the hot spot is initially the upper left corner.
Menu:
A menu is a list of available options. A menu is probably the most
important part of the consistent user interface that windows programs offer and
adding a menu in the program. A list of options from which a user can make a
selection in order to perform a selected action such as choosing a command or
applying particular format or part of a document.
A windows menu bar is displayed immediately below the caption bar.
This menu bar is sometimes called as a main menu. Items listed in the top level
menu, usually invokes drop down menu which are also called as “popup
menu”.
1.9 KEYBOARD HANDLING
All Win-32 based applications should accept user input from the
keyboard as well as from the mouse. A Win-32 based application receives
keyboard input in the form of messages posted to its windows.
Keyboard Input Model:
When a key is pressed on the keyboard, the signal travels into the
computer, where the kernel gets it. These signals, or "keycodes" as they are
called, are raw data that needs to be translated into ASCII characters. The
kernel performs this conversion, as well as obtaining other information about
the keystroke. The system provides device-independent keyboard support for
applications by installing a keyboard device driver appropriate for the current
keyboard. The system provides language independent keyboard support by
using the language specific keyboard layout currently selected by the user or
the application. The keyboard device driver receives scan codes from the
19
keyboard which are sent to the keyboard layout where they are translated into
messages and posted to the appropriate windows in our application.
Assigned to each key on a keyboard is a unique value called a scan
code, a device independent identifier for the key on the keyboard. A Keyboard
generates two scan codes when the user types a key, one when the user presses
the key and another when the user releases a key.
The keyboard device driver interprets a scan code and translates it to a
virtual key code, a device independent value defined by the system that
identifies the purpose of a key. After translating a scan code the keyboard
layout creates a message that includes the scan code the virtual key code and
other information about the keystroke and then places the message in the
system message queue. The system removes the message from the system
message queue and posts it to the message queue of the appropriate thread.
Eventually the thread’s message loop removes the message and passes it to the
appropriate window procedure for processing. The pictorial representation of
keyboard input model is given below.
keyboard
Scan code
KeyStroke messages:
Pressing a key, results in a WM_KEYDOWN or
WM_SYSKEYDOWN message being place in the thread message queue
associated with the window that has the keyboard focus. Releasing a key,
results in a WM_KEYUP or WM_SYSKEYUP messages being placed in the
queue. Keyup and keydown messages occur in pairs but if the user holds down
a key long enough to start the keyboard’s automatic repeat feature, the system
generates a number of WM_KEYDOWN or WM_SYSKEYDOWN messages
in a row. It then generates a single WM_KEYUP or WM_SYSKEYUP
message when the user releases the key.
1.10 MOUSE HANDLING
The mouse is an important but optional user input device for win-32
applications. A win-32 application receives mouse input in the form of
messages that are sent and posted to its windows.
20
Mouse Cursor:
When the user moves the mouse, the system moves a bitmap on the
screen called the mouse cursor. The mouse cursor contains a single point called
the hot spot, appoints that the system tracks and recognizes the position of the
cursor. When a mouse event occurs, the window that contains the hot spot
typically receives the mouse message resulting from the event.
Mouse Messages:
The mouse generates an input event whenever the user moves the
mouse or presses or releases a mouse button. The system converts mouse input
events into messages and posts them to the appropriate thread’s message queue.
When mouse messages are posted faster than a thread can process them, the
system discards all but the most recent mouse message.
A window receives a mouse message when a mouse event occurs while
the cursor is within the borders of the window or window captured the mouse.
Mouse messages are divided into two groups, client area messages and non-
client area messages.
Client area mouse messages:
A window receives a client area mouse message when a mouse event
occurs within the window’s client area. The system posts one of the following
messages when the user presses or releases a mouse button while the cursor is
within the client area.
Message meaning
WM_LBUTTONCLICK The left mouse button was double clicked
WM_LBUTTONDOWN The left mouse button was pressed
WM_LBUTTONUP The left mouse button was released
WM_MBUTTONDBLCLK The middle mouse button was double
clicked
WM_MBUTTONDOWN The middle mouse button was pressed
WM_MBUTTONUP The middle mouse button was released
WM_RBUTTONDBLCLK The right mouse button was double
clicked
WM_RBUTTONDOWN The right mouse button was pressed
WM_RBUTTONUP The right mouse button was released
Non-client area mouse messages:
A window receives a non client area mouse message when a mouse
event occurs in any part of a window except the client area. A window’s non
client area consists of its border, menu bar, title bar, scroll bar, window menu,
minimize button and maximize button. For example moving the cursor in the
non client area generates a WM_NCMOUSEMOVE message.
21
1.11 DISPLAYING TEXT AND GRAPHICS
TEXT OUTPUT
Text output is the most common type of graphics output found within
the client area of win-32 based application. The Win-32 API provides a
complete set of functions to format and draw text in an application’s client area
and on a page of printer paper. The text functions falls in two categories: format
the text and to draw the text. The formatting functions align text, set the
intercharacter spacing, set the text and text background colors and justify text.
The drawing functions draw individual characters or entire strings of text.
Formatting text
The formatting functions can be divided in to three categories:
Those that retrieve or set the text formatting attributes for a device
context
Those that retrieve character widths
Those that retrieve string widths and heights
Text formatting Attributes
The text formatting functions are
* SetBkColor
* SetBkMode
* SetTextAlign
* SetTextCharacterExtra
* SetTextColor
* SetTextJustification.
The functions to retrieve the current text formatting attributes for any device
context are
* GetBkColor
* GetBkMode
* GetTextAlign
* GetTextCharacterExtra
* GetTextColor
* GetTextExtentPoint32
Applications need to retrieve character width of the data when they
perform tasks such as fitting strings of text to page or column widths. In
addition to this, applications need to retrieve the width and height of the entire
strings. The functions used to retrieve string’s width and height are
GetExtentPoint32 and GetTabbedTextExtent
22
DRAWING TEXT
After setting the required formatting options the user can draw the
characters and symbols using the text-output functions. The text output
functions DrawText and TabbedtextOut are part of window manager and found
in the library USER.DLL, and the ExtTextOut and TextOut functions are in the
library GDI.DLL. When an application calls one of these functions, the
operating system passes the call to the graphics engine, which in turn passes the
call to the appropriate device driver.
At the device driver level all of these calls are supported by one or more
calls to the driver’s own ExtTextOut or TextOut function. An application will
receive the fastest execution by calling the ExtTextOut call for the device. But
for some instance it is necessary to call the other three functions directly, for
example, to draw multiple lines of text within the borders of a specified
rectangular region, it is more efficient to call the DrawTxt function. To create
multicolumn table with justified columns of text it is more effective to call the
TabbedTextOut function.
DrawText Function:
int DrawText{
HDC hDC, // handle to device context
LPCTSTR lpString, //pointer to string to draw
int nCount, //string length in characters
LPRECT lpRect, //pointer to struct with formatting
dimensions
UINT uFormat //text formatting flags
};
TabbedText function:
Long TabbedTextOut{
HDC hDC, // handle to device context
int X, // X- coordinate of staring position
int Y, // Y-coordinate of staring position
LPCTSTR lpString //pointer to string
int nCount // number of characters in string
int nTabPositions //number of table in array
LPINT lpnTabStopPositions // pointer to array for tab positions
int nTaborigin // x-coordinate for tab position
};
23
ExtTextOut Function:
BOOL ExtTextOut{
HDC hDC, // handle to device context
int X, // X- coordinate of reference point
int Y, // Y-coordinate of reference point
UINT fuOptions // text output options
CONST RECT *lprc //optional clipping and/or opaquing
rectangle.
LPCTSTR lpString //pointer to string
UINT cbCount // number of characters in string
CONST INT *lpdx //pointer to array of intercharacter spacing
};
TextOut Function:
BOOL TextOut{
HDC hDC, // handle to device context
int X, // X- coordinate of starting position
int Y, // Y-coordinate of starting position
LPCTSTR lpString //pointer to string
int cbString //number of characters in string
};
DRAWING GRAPHICS
DEVICE CONTEXTS
A device context is a structure that defines a set of graphic objects and
their associated attribute and the graphic modes that affect output. The graphic
objects include a pen for line drawing, a brush for printing and printing, a
bitmap for copying or scrolling parts of the screen, a palette for defining the set
of available colors, a region for clipping and other operations and path for
painting and drawing operations.
Device Context Types:
There are four types of device contexts: display, printer, memory and
information. Each type serves a specific purpose as described in the following
table.
Device Context Description
Display Supports drawing operations on a video display
Printer Supports drawing operations on a printer or plotter
Memory Supports drawing operations on a bitmap
24
Information Supports the retrieval of device data
Displaying Bitmaps:
A bitmap is a graphical object used to create, manipulate and store
images as files on a disk.
A bitmap is a structure that contains the following elements
* A header that describes the relation of the device on which the rectangle
of pixels was created, the dimensions of the rectangle, the size of the
array of bits and so on.
* A logical palette
* An array of bits that defines the relationship between pixels in the
bitmapped image and entries in the logical palette.
A bitmap size is related to the type of image it contains. Bitmap images
can be either monochrome or color. In an image, each pixel corresponds to one
or more bits in a bitmap. Monochrome images have a ratio of one bit per pixel.
Color imaging is more complex. The number of colors that can be displayed by
a bitmap is equal to 2 times the number of bits per pixel. A 256 color bitmap
requires 8 bits per pixel.
There are two classes of bitmaps: Device independent bitmaps and
device dependent bitmap. The bitmap structure defines the type, width, height,
color format and bit values of a bitmap.
Typedef struct tagBITMAP{
LONG bmType;
LONG bmWidth;
LONG bmHeight;
LONG bmWidthBytes;
WORD bmPlanes;
WORD bmBitsPixel;
LPVOID bmBits;
}BITMAP;
Drawing Filled Shapes:
Filled Shapes are geometric shapes that are outlined by using the current
pen and filled by using the current brush. There are five filled shapes; ellipse,
chord, pie, polygon and rectangle.
Ellipse:
The Ellipse function draws an ellipse. The center of the ellipse is the
center of the bounded rectangle.
BOOL Ellipse(HDC hdc, int nLeftRect, int nTopRect, int nRightRect,
int nBottomRect);
25
Drawing Chord:
The chord function draws a chord.
BOOL Chord(
HDC hdc,
int nLeftRect,
int nTopRect,
int nRightRect,
int nBottomRect
int nXRadial1,
int nYRadial1,
int nXRadial2,
int nYRadial2);
Drawing Pie:
The Pie function draws a pie shaped wedge bounded by the intersection
of an ellipse and two radials. The pie is outlined by using the current pen and
filled by using the current brush.
BOOL Pie(
HDC hdc,
int nLeftRect,
int nTopRect,
int nRightRect,
int nBottomRect
int nXRadial1,
int nYRadial1,
int nXRadial2,
int nYRadial2);
Drawing a Polygon:
The Polygon function draws a polygon consisting of two or more
vertices connected by straight lines. The polygon is outlined by using the
current pen and filled by current brush and polygon fill mode.
BOOL Polygon (HDC hdc, CONST POINT *lpPoints, int nCount);
1.12 DIALOG BOX CONTROLS
A dialog box is a temporary window an application creates to retrieve
user input. An application typically uses dialog boxes to prompt the user for
additional information for commands. A dialog box usually contains one or
26
more controls (child windows) with which the user enters text, chooses options,
or directs the action of the command.
Win32 API provides many functions, messages and controls to create
and manage the dialog box and thus makes it easy to develop the user interface
for an application. Dialog box is one of the way to get the input from the user.
For example, File open Command requires the name of the file to open so an
application should use a dialog box to prompt the user for the name of the file.
In general there are two types of dialog boxes, such as
1. Model and
2. Modeless
A Modal dialog box requires the user to supply information or cancel
the dialog box before allowing the application to continue. A modeless dialog
box allows the user to supply the information and return to the previous task
without closing the dialog box.
The dialog box can be created using either the DialogBox or
CreateDialog function. DialogBox creates a modal dialog box. CreateDialog
creates a modeless dialog box.
DialogBox Function:
The DialogBox macro creates a modal dialog box from a dialog box
template resource. Dialog box does not return control until the specified
callback function terminates the modal dialog box by calling the EndDialog
function. The DialogBox macro uses the DialogBoxParam function.
int DialogBox(
HINSTANCE hinstance,
LPCTSTR lpTemplate,
HWND hwndParent,
DLGPROC lpDialogFunc);
CreateDialog Function:
The CreateDialog macro creates a modeless dialog box from a dialog
box template resource. This uses the CreateDialogParam Function
HWND CreateDialpg(
HINSTANCE hinstance,
LPCTSTR lpTemplate,
HWND hwndParent,
DLGPROC lpDialogFunc);
MESSAGE BOX
A message box is a special dialog box that an application can use to
display messages and prompt for simple input. A message box typically
27
contains a text message and one or more buttons. An application creates the
message box by using the MessageBox or MessageBoxEx function. The
MessageBoxEx function allows the user to specify the language.
MessageBox Function:
This function creates, displays and operates a Message Box. The
message box contains an application defined message and title, combination of
predefined icons and push buttons.
int MessageBox(
HWND hwnd,
LPCTSTR lpText,
LPCTSTR lpCaption,
UINT uType);
MessageBoxEx Function:
In addition to the above specification this function has wLanguageid
parameter specifies the set of language resources.
int MessageBoxEx(
HWND hwnd,
LPCTSTR lpText,
LPCTSTR lpCaption,
UINT uType,
WORD wLanguageid);
1.13 FILES
The traditional concept of file is a block of data on a storage device
identified by a file name. A file is the basic unit of storage that enables a
computer to distinguish one set of information from another.
Files are stored on storage media, such as disk, tapes and can be
organized into groups called directories. The file I/O functions enable
applications to create, open, modify and delete file.
Creating and Opening file:
The Create File function can create a new file or open an existing file.
HANDLE CreateFile(
LPCTSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisPoint,
28
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
When an application creates a file, it must specify the operations on file
such as whether it will read from the file or write into the file or both, and also
it must specify the action to be taken when the file does not exist. In general
when the create file function is used if the specified file does not exist it will
create a new one or if the file exists it overwrites the contents of it.
CreateFile also enables the user to specify whether it wants to share the
file for reading, writing, both or neither. A file that is not shared can not be
opened more than once by the first application nor by another application until
the first application has closed the file.
The operating system assigns a unique identifier called a file handle to
each file that is opened or created. Application can use the file handle in all file
operations. It is valid until the file is closed using CloseHandle function, which
closes the file and flushes the buffer.
Reading And Writing:
Every opened file has a file pointer that specifies the next byte to be
read or the location of the next byte to be written. When a file is opened for the
first time, the file pointer is positioned at the beginning of the file. For each
read or write operation the file pointer is advanced. The filepointer can be
moved to certain position by using SetFilePointer function.
The Read and Write operation is carried out by using ReadFile and
WriteFile functions respectively. These functions read and write a specified
number of bytes at the location indicated by the file pointer. The data is read
and written exactly as specified but do not format the data.
An application can truncate or extend the file using SetEndOfFile
function. If two applications write to the same location in the file at the same
time, to prevent this the application should lock the area of the file by using the
LockFile() function.
When application completes the write operation, it unlocks the region of
the file using UnlockFile() function. All locked regions of a file should be
unlocked before closing a file.
FILE I/O functions
Function meaning
CreateFile Creates or opens a file
CreateFileMapping Create a named or unnamed file mapping object
for a file
CreateDirectory Creates a new directory
CopyFile Copies an existing file to a new file
29
DeleteFile Deletes a file
GetFileSize retrieves the size of the file
LockFile Locks a region of a file
MoveFile Moves a file or a directory and its contents
ReadFile Read data from a file
UnlockFile Unlock a region in an open file
WriteFile Writes data to a file.
1.14 CLIPBOARD
The clipboard is a set of functions and messages that enable Win32
based applications to transfer data. Because all applications have access to the
clipboard, data can be easily transferred between applications or within an
application. The ClipBoard is a standard windows method of transferring data
between a source and a destination. It is very useful in OLE operations. It is a
system device shared by the entire windows session, so it does not have a
handle or class of its own. A window procedure transfers information to or
from the clipboard in response to the WM_COMMAND message. The
clipboard is user driven. A window must not use the clipboard to transfer data
without the user’s knowledge.
Creating ClipBoard Viewer Window:
A clipboard viewer window displays the current content of the
clipboard and receives messages when the clipboard content changes. To create
a clipboard viewer do the following
Add the window to the clip board viewer chain
Process the WM_CHANGECBCHAIN message
Process the WM_DRAWCLIPBOARD message
Remove the window from the clip board viewer chain before it is
displayed.
The OpenClipboard function opens the clipboard for examination and
prevents other applications from modifying the clipboard content. The
CloseClipboard function closes the clipboard. The GetClipboardData
function retrieves data from the clipboard in a specified format. The clipboards
must have been opened previously. The SetClipboardData function places
data on the clipboard in a specified format.
1.15 PRINTERS
Printing is one of the most complex tasks in window based application.
Printing from our application involves these three components:
The code in our application, which starts the printing process.
The printer drivers installed on both our system and the systems of users
of our application.
30
The capabilities of the printers available to users of our application.
The code in our application determines the type and quality of print
output available from our application. One of the chief features of Microsoft
Win32 printing functions is their support of device independence. Instead of
issuing device-specific commands to draw output on a particular printer or
plotter an application calls high level functions from the graphics device
interface (GDI).
RETRIEVING A PRINTER DEVICE CONTEXT
When the user selects the print option in the file menu, we can call the
printDlgEx function to display the print property sheet. The property sheet
enables the user to provide information about the print job. For example, the
user can specify a range of pages to print, the number of copies and so on.
printDlgEx can retrieve a handle to a device context for a selected printer. The
PrintDlgEx function is available on Windows 2000 or later.
1.16 DYNAMIC DATA EXCHANGE (DDE)
The Win32 API provides several methods for transferring data between
applications. One method is to use the DDE protocol. The DDE protocol is a
set of messages and guidelines. It sends messages between applications that
share data and uses shared memory to exchange data between applications. The
DDEML is a dynamic Link Library that win32 based applications can use to
share data. Instead of sending, posting and processing DDE messages directly,
an application uses the DDEML functions to manage DDE conversations. A
DDE conversation is the interaction between client and server applications. The
DDEML also provides a facility for managing the strings and data that DDE
applications share.
To initiate a DDE conversation the client sends a WM_DDE_INITIATE
message. Usually the client broadcasts this message by sending the
SendMessage with -1 as the first parameter. Once a DDE conversation has
been established the client can either retrieve the value of a data item from the
server by issuing the WM_DDE_REQUEST message or submit a data item
value to the server by issuing WM_DDE_POKE.
WM_DDE_EXECUTE message allows the application to execute a
certain command or series of commands. To terminate a conversation either
client or server uses a WM_DDE_TERMINATE command.
1.17 DYNAMIC LINK LIBRARIES (DLL)
A dynamic link library (DLL) is an executable file that acts as a shared
library of functions. Dynamic linking provides a way for a process to call a
function that is not part of its executable code. The executable code for the
function is located in DLL, which contains one or more functions that are
compiled, linked and stored separately from the processes that use them. DLL
also facilitate the sharing of data and resources. Multiple applications cam
simultaneously access the contents of a single copy of a DLL in memory.
31
In static linking, the linker gets all the referenced functions from the
static link library and places it in the code itself. Whereas the dynamic linking,
links the referecnced file only during the run. Thus it reduces the size of the
executable file. Several applications share the same DLL and this saves the disk
space in memory.
Advantages of DLL:
Saves memory and reduce swapping
Saves disk space
Upgrades to the DLL are easier
Supports Multilanguage programs
Provides mechanism to extend the MFC library classes
A potential disadvantage of using DLL is that the application is not self
contained, it depends on the existence of a separate DLL module.
1.18 OBJECT LINKING AND EMBEDDING (OLE)
Object Linking and Embedding, a technology for transferring and
sharing information among applications. When an object such as an image file
created with paint application is linked to a compound document, such as
spread sheet or a document created with a word processing application the
document contains only a reference to the object; any changes made to the
contents of a linked object are seen in the compound document. When an object
is embedded in a compound document, the document contains the copy of the
object, any changes made to the contents of the original object are not seen in
the compound document unless the embedded object is updated.
OLE is a mechanism that allows the users to create and edit documents
containing items or objects created by multiple applications. OLE incorporates
many different concepts such as
Linking and Embedding:
Linking and Embedding are the two methods for storing items created
inside an OLE document that were created in another application.
In-Place Activation:
Activating an embedded item in the context of the container document
is called in-place activation or visual editing.
Automation:
Automation allows one application to drive another application. The
driving application is an automation client or automation controller, and the
application being driven is known as an automation server or automation
component.
32
Compound Files:
Compound files provide a standard file format that simplifies structured
storing of compound documents for OLE applications.
Uniform Data transfer:
Uniform Data transfer (UDT) is a set of interfaces that allow data to be
sent and received in a standard fashion, regardless of the actual method chosen
to transfer the data.
Drag and Drop:
This is an easy to use, direct manipulation technique to transfer data
between applications, between windows within an application or even within a
single window in an application.
Component Object Model:
Component Object Model provides the infrastructure used when OLE
objects communicate with each other.
1.19 COMPONENT OBJECT MODEL (COM)
The Component Object Model (COM) is a platform independent,
distributed, object oriented system for creating binary software components that
can be interact. The Component Object Model(COM) is a component software
architecture that allows applications and systems to be built from components
supplied by different software vendors.
These services provide distinctly different functionality to the user,
however they share a fundamental requirement for a mechanism that allows
binary software components supplied by different software vendors, to connect
to and communicate with each other in a well defined manner.
COM a component software architecture that
Defines a binary standard for component interoperability
Is programming language independent
Is provided on multiple platforms
Provides for robust evolution of component based applications and
systems
Is extensible
In addition COM provides mechanisms for the following
Communications between components even across process and network
boundaries
Shared memory management between components
Error and status reporting
Dynamic loading of components
33
COM fundamentals:
The Component Object Model defines several fundamental concepts
that provide the model’s structural underpinnings. These include:
A binary standard for function calling between components
A provision for strongly typed groupings of functions into interfaces
A base interface providing
i) A way for components to dynamically discover the
interfaces implemented by other components.
ii) Reference counting to allow components to track their
own life time and delete themselves when appropriate
A mechanism to uniquely identify components and their interfaces.
A “component loader” to set up component interactions and additionally
in the cross process and cross-network cases to help manage component
interactions.
34
NOTES
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
35
UNIT – II
VC++
2.1 Microsoft Foundation Classes (MFC):
Microsoft Foundation Classes (MFC) is a framework for developing
Windows applications in C++. MFC is more than a frame work; it provides a
C++ facade to the C-based Win32 API. The MFC library consists of over 200
C++ classes. Most of these classes are organized into a single inheritance
hierarchy rooted by the CObject base class.
MFC provides a message class called MSG that is analogous to Simple
Application’s Framework's(SAF) Message class, MFC provides a CCmdTarget
class derived from CObject that is analogous to SAF's AppObject class, and
MFC provides a CWinApp class derived from CWinThread that is analogous to
SAF's Dispatcher class.
MFC classes are not system classes, they are pre-defined application
classes. MFC doesn't replace the Win32 API, it simply hides it. Applications
refer to system objects using identification numbers called handles rather than
pointers. In fact, most MFC objects encapsulate handles referencing
corresponding system objects. For example, every instance of CWnd, the class
of all window objects, encapsulates an HWND handle that identifies a
corresponding system object that represents a "real" window:
class CWnd : public CCmdTarget
{
public:
HWND m_hWnd;
// etc.
};
Many MFC member functions simply call a corresponding Win32 API
global function and pass their encapsulated handles as a parameter:
2.2 MESSAGES AND EVENTS
An application is made of various objects. Mostly more than one
application is running on the computer. These two scenarios mean that the
operating system is constantly asked to perform some assignments. Because
there can be so many requests presented unpredictably, the operating system
leaves it up to the objects to specify what they want, when they want it, and
what behavior or result they expect.
The Microsoft Windows operating system cannot predict what kinds of
requests one object would need to be taken care of and what type of assignment
another object would need. To manage all these assignments and requests, the
objects send messages, one message at a time, to the operating system. For this
reason, Microsoft Windows is said to be a message-driven operating system.
Once a control has composed a message, it must send it to the right
target which could be the operating system. In order to send a message, a
36
control must create an event. It is also said to fire an event. To make a
distinction between the two, a message's name usually starts with WM_ which
stands for Window Message. The name of an event usually starts with On
which indicates an action. The message is what needs to be sent and the event
is the action of sending the message.
Message map:
#include <afxwin.h>
class CSimpleFrame : public CFrameWnd
{
public:
CSimpleFrame();
……
DECLARE_MESSAGE_MAP()
};
The DECLARE_MESSAGE_MAP macro should be provided at the
end of the class definition. To implement the messages, we should create a
table of messages that our program is using. The message table begins and ends
with two delimiting macros such as BEGIN_MESSAGE_MAP and
END_MESSAGE_MAP. The BEGIN_MESSAGE_MAP macro takes two
arguments, the name of the class derived and the base MFC class which is used
to derive the class.
BEGIN_MESSAGE_MAP(CSimpleFrame, CFrameWnd)
Operating system receives various categories of messages. Messages
may come from the keyboard, from the mouse or from various other origins.
For example, some messages are sent by the application itself while some other
messages are controlled by the operating system.
2.2.1 Windows Messages
Creating Windows:
WM_CREATE: When an object, called a window, is created, the
frame that creates the objects sends a message identified as
ON_WM_CREATE. Its syntax is:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
This message calls the CFrameWnd::Create() method to create a
window. Argument to this message is a pointer to a CREATESTRUCT class.
The CREATESTRUCT class provides all the information needed to create a
window. It is defined as follows:
typedef struct tagCREATESTRUCT {
LPVOID lpCreateParams;
HANDLE hInstance;
37
HMENU hMenu;
HWND hwndParent;
int cy;
int cx;
int y;
int x;
LONG style;
LPCSTR lpszName;
LPCSTR lpszClass;
DWORD dwExStyle;
} CREATESTRUCT;
This class provides the same types of information as the WNDCLASS
object. The creation of window can be checked by the returned value of the
OnCreate() message from the parent class. If the message returns 0, the
window was created. If it returns -1, the class was not created or it would
simply be destroyed.
Example:
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
// Create the window and make sure it doesn't return -1
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
// else is implied
return 0;
}
To use this message, in the class definition, type its syntax. In the
message table, type the name of the message ON_WM_CREATE():
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
END_MESSAGE_MAP()
WM_SHOWWINDOW: After creating a window, it needs to be displayed. To
show or hide a window, ON_WM_SHOWWINDOW message is used. The
syntax of the message is:
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
38
bShow is a Boolean argument determines the state of the window. If it
is TRUE, the window needs to be displayed. If it is FALSE, the window must
be hidden.
nStatus is a positive integer that can have one of the following values:
Value description
Value Description
WA_ACTIVE Used to activate a window without using the
mouse, may be by pressing Alt + Tab
39
void CMainFrame::OnActivate(UINT nState, CWnd* pWndOther, BOOL
bMinimized)
{
CFrameWnd::OnActivate(nState, pWndOther, bMinimized);
// TODO: Add your message handler code here
}
WM_PAINT: The window created must be displayed. To display the window,
the operating system needs its location (left and top measures) and its
dimension (width and height). This is because the window must be painted.
Also, if the window was hidden somewhere such as behind another window or
was minimized, when it comes up, the operating system needs to paint it. To do
this, the window that needs to be painted must send a message called
ON_WM_PAINT. This message does not return anything but in its body, you
can define what needs to be painted and how you want the job to be done. The
syntax of this message is :
afx_msg void OnPaint()
WM_SIZE: When using an application, one of the actions a user can perform
on a window is to change its size, provided the window allows this. If the
window can be minimized, maximized or restored, the operating system must
keep track of the size of a window. When the size of a window has changed,
the window sends the ON_WM_SIZE message. Its syntax is:
afx_msg void OnSize(UINT nType, int cx, int cy);
The nType argument specifies what type of action to take. It can have
one of the following values:
Value Description
The cx argument specifies the new width of the client area of the
window
The cy argument specifies the new height of the client area of the
window.
40
Implementation in the parent class before implementing the behavior
is,
void CAnyWindow::OnSize(UINT nType, int cx, int cy)
{
CParentClass::OnSize(nType, cx, cy);
Value Description
WMSZ_BOTTOM Bottom edge
41
The second argument, lpRect, is the new rectangle that will enclose the
window after the window has been moved, resized, or restored.
WM_MOVE: When a window has been moved, the operating system
needs to update its location. Therefore, the window sends a message called
ON_WM_MOVE. Its syntax is:
afx_msg void OnMove(int x, int y);
The first argument of this message specifies the left horizontal location
of the left border of the window after the window has been moved. The second
argument represents the vertical position of the top border of the window after
the window has been moved.
WM_MOVING: While the user is moving a window, the window sends an
ON_WM_MOVING message. Its syntax is:
afx_msg void OnMoving( UINT nSide, LPRECT lpRect );
The first argument, nSide, is the edge of the window that is being
moved. It is the same as for the ON_MOVE message.
The lpRect is the target dimension of the window that is being moved.
That is, it contains the new dimensions of the window as it is being moved.
WM_DESTROY: Once the window has been used and the user has closed it,
the window must send a message to the operating system to destroy it. The
message sent is called ON_WM_DESTROY and its syntax is:
afx_msg void OnDestroy( );
This message takes no argument but you can use its body to do any last
minute assignment as needed. For example, you can use it either to prevent the
window from being closed or you can enquire whether the user really wants to
close the window.
42
2.2.2 Command Messages
One of the main features of a graphical application is to present
Windows controls and resources that allow the user to interact with the
machine. Examples of controls are buttons, list boxes, combo boxes, etc. Such
controls and resources can initiate their own messages when the user clicks
them. A message that emanates from a Windows control or a resource is called
a command message. For example to associate the method OnLetItGo() to the
control, declare a framework such as
afx_msg void OnLetItGo();
And the method should be defined as
void CMainFrame::OnLetItGo()
{
// Something to do here
}
The framework allows you to associate a member function to a
command message. This is done using the ON_COMMAND macro. Its syntax
is
ON_COMMAND(IDentifier, MethodName)
The first argument, IDentifier, of this macro must be the identifier of the
menu item or Windows control to be associated with a method.
The second argument, MethodName, must be the name of the member
function that will implement the action of the menu item or Windows control
such as a button.
For example assume that we have a menu item identified as
ID_ACTION_LETITGO. To link the OnLetItGo() method to this menu item,
use the ON_COMMAND macro as follows:
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_COMMAND(ID_ACTION_LETITGO, OnLetItGo)
END_MESSAGE_MAP()
2.2.3 Keyboard Messages
A keyboard is a hardware object attached to the computer. By default, it
is used to enter recognizable symbols, letters, and other characters on a control.
Each key on the keyboard displays a symbol, a letter, or a combination of
those, to give an indication of what the key could be used for. The user
typically presses a key, which sends a signal to a program. The signal is
analyzed to find its meaning. If the program or control that has focus is
equipped to deal with the signal, it may produce the expected result. If the
program or control cannot figure out what to do, it ignores the action.
Each key has a code that the operating system can recognize.
43
KeyDown:
When we think of the keyboard, the first thing that comes in mind is to
press a key. When a keyboard key is pressed, a message called
WM_KEYDOWN is sent.. Its syntax is:
afx_msg void OnKeyDown( UINT nChar, UINT nRepCnt, UINT
nFlags );
The first argument, nChar, specifies the virtual code of the key that was
pressed.
The second argument, nRepCnt, specifies the number of times counted
repeatedly as the key was held down.
The nFlags argument specifies the scan code, extended-key flag,
context code, previous key-state flag, and transition-state flag.
Key Up:
When we think of the keyboard, the first thing that comes in mind might
refer to typing, which consists of pressing a key and releasing it immediately.
As this is done, a key is pressed down and brought back up. When the user is
releasing a key a WM_KEYUP message is sent. Its syntax is:
afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT
nFlags);
The first argument, nChar, is the code of the key that was pressed.
The second argument, nRepCnt, specifies the number of times counted
repeatedly as the key was held down.
The nFlags argument specifies the scan code, extended-key flag,
context code, previous key-state flag, and transition-state flag.
2.2.4 Mouse Messages
The mouse is another object that is attached to the computer allowing
the user to interact with the machine. The mouse and the keyboard can each
accomplish some tasks that are not normally available on the other and both can
accomplish some tasks the same way. The mouse is used to select a point or
position on the screen. Once the user has located an item, which could also be
an empty space, a letter or a word, he or she would position the mouse pointer
on it. To actually use the mouse, the user would press either the left, the middle
(if any), or the right button.
Mouse down messages:
Imagine the user has located a position or an item on a document and
presses one of the mouse buttons. While the button is pressed and is down, a
button-down message is sent, depending on the button that was pressed.
If the left mouse button was pressed, an
ON_WM_LBUTTONDOWN message is sent. The syntax of this message is:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
44
If the right mouse button was pressed, an
ON_WM_RBUTTONDOWN message is sent. Its syntax is:
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
The first argument, nFlags, specifies what button is down or what
keyboard key and what mouse button are down. It is a constant integer that can
have one of the following values:
Value Description
MK_CONTROL A Ctrl key is held down
MK_LBUTTON The left mouse button is down
MK_MBUTTON The middle mouse button is down
MK_RBUTTON The right mouse button is down
MK_SHIFT A Shift key is held down
The point argument specifies the measure from the left and the top
borders of the window to the mouse pointer.
Mouse-Up Messages:
After pressing a mouse button, the user usually releases it. While the
button is being released, a button-up message is sent and it depends on the
button, left or right, that was down.
If the left mouse is being released, the ON_WM_LBUTTONUP
message is sent. Its syntax is:
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
If the right mouse is being released, the ON_WM_TBUTTONUP
message is sent. Its syntax is:
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
The first argument, nFlags, specifies what button, right or middle, is
down or what keyboard key and what mouse button were down. It is a constant
integer that can have one of the following values:
Value Description
MK_CONTROL A Ctrl key was held down
45
The point argument specifies the measure from the (0, 0) origin of the
window to the mouse pointer.
Double-Click Message:
Instead of pressing and simply releasing a mouse button, a classic action
the user can perform with the mouse is to double-click an object. When this is
done, a double-click message is sent. The message to consider actually depends
on the button that was double-pressed.
If the double-click was performed using the left mouse button, the
WM_LBUTTONDBLCLK message is sent and its syntax is:
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
If the action was performed using the right mouse button, the
WM_RBUTTONDBLCLK message would be sent. Its syntax is:
afx_msg void OnRButtonDblClk(UINT nFlags, CPoint point);
In both cases the nFlags argument specifies the button that was double-
clicked. This argument can have one of the following values:
Value Description
MK_CONTROL A Ctrl key was held down when the user double-
clicked
46
Value While the mouse is moving
MK_CONTROL A Ctrl key is held down
MK_LBUTTON The left mouse button is down
MK_MBUTTON The middle mouse button is down
MK_RBUTTON The right mouse button is down
MK_SHIFT A Shift key was held down
The point argument specifies the current location of the mouse pointer
in x (horizontal) and y (vertical) coordinates at the time the message is
captured.
2.2.5 Conditional Messages
The messages we have used so far belong to specific events generated
at a particular time by a window. Sometimes in the middle of doing something,
we may want to send a message regardless of what is going on. This is made
possible by a function called SendMessage(). Actually, there are two
SendMessage() versions available.
The Win32 API version of the SendMessage() function has the
following syntax:
LRESULT SendMessage(HWND hWnd, UINT Msg, WPARAM
wParam, LPARAM lParam);
The MFC version is defined as follows:
LRESULT SendMessage(UINT Msg, WPARAM wParam, LPARAM
lParam);
Because the Win32 version is considered global, if you want to use it,
you must precede it with the scope access operator "::" as in:
::SendMessage(WhatToDo);
The hWnd argument is the object or control that is sending the message.
The Msg argument is the message to be sent.
The wParam and the lParam values depend on the message that is
being sent.
The advantage of using the SendMessage() function is that, when
sending this message, it would target the procedure that can perform the task
and this function would return only after its message has been processed.
Sending Messages:
In order to send a message using the SendMessage() function, you must
know what message you are sending and what that message needs in order to
47
be complete. For example, to change the caption of a window at any time, you
can use the WM_SETTEXT message. The syntax to use would be:
SendMessage(WM_SETTEXT, wParam, lParam);
Obviously you would need to provide the text for the caption you are
trying to change. This string is carried by the lParam argument as a null-
terminated string. For this message, the wParam is ignored.
2.3 WINDOWS RESOURCES
A resource is a text file that allows the compiler to manage such objects
as pictures, sounds, mouse cursors, dialog boxes, etc. Microsoft Visual C++
makes creating a resource file particularly easy by providing the necessary tools
in the same environment used to program, without using an external application
to create or configure this file.
Although an application can use various resources that behave
independently of each other, these resources are grouped into a text file that has
the .rc extension. It is possible to create it manually. To do this, you add or
create one resource at a time when designing it. After saving a resource, it is
automatically added to the .rc file. To make your resource recognizable to the
other files of the program, you must also create a header file usually called
resource.h. This header file must provide a constant integer that identifies each
resource and makes it available to any part that needs it. All the resources will
be represented by an identifier.
An identifier is a constant integer whose name usually starts with ID.
Although in Win32 programming the name of a resource is used as a string, in
MFC applications, resources are usually referred by their identifier. To make an
identifier name (considered a string) recognizable to an MFC (or Win32)
function, the macro called MAKEINTRESOURCE is used. Its syntax is:
LPTSTR MAKEINTRESOURCE(WORD IDentifier);
This macro takes the identifier of the resource and returns a string that is
given to the function that called it.
In the strict sense, after creating the resource file, it must be compiled to
create a new file that has the extension .res. But Visual C++ automatically
compiles the file and links it to the application.
2.3.1 Creating resources
Because resources are different entities, they are created one at a time.
They can also be imported from existing files. Most resources are created by
selecting the desired one from the Add Resource dialog box
The Add Resource dialog box provides an extensive list of resources to
accommodate almost any need. Still, if the resource we need is not found in the
resources then we can add it manually to the .rc file before executing the
program.
48
2.3.2 Overview of icons
An icon is a small picture used on a window. It is used in two main
scenarios. On a window's frame, it display on the left side of the window name
on the title bar. In Windows Explorer, on the Desktop, in My Computer, or in
the Control Panel windows, an icon is used to represent an application:
2.3.3 Menus
A menu is a list of actions the user can perform on an application. Each
item of the list is primarily a word or a group of words on a line. Different
menu items are used for different reasons. For example, some menu items
simply display a word or a group of words. Some other items display a check
mark. This indicates that the item toggles the availability or disappearance of an
object.
When a menu item is only meant to lead to a sub-menu, such a menu
item is call a popup menu. There are two types of popup menus. If the menu
displays on top of a window, which is the type of menu under the title bar, the
word on top, which represents a category of menu, is a popup menu. If a menu
item is equipped with an arrow in its right ,
which means the menu item has a submenu, such a menu item is also a popup
menu. Popup menus are used only to represent a submenu. No inherent action
is produced by clicking them, except that, when placed on top, such menu items
allow opening the submenu.
To create menus that belong to a group, menu items are separated by a
horizontal line called a separator.
There are two primary types of menus in most applications: a main
menu and a popup menu.
Main Menu:
A menu is considered a main menu, when it carries most or all of the
actions the user can perform on an application. Such a menu is positioned on
the top section of the main window in which it is used. A main menu is divided
in categories of items and each category is represented by a word. Here is an
example:
On the Visual Studio IDE, the categories of menus are File, Edit, View,
Project, etc. To use a menu, the user first clicks one of the words that displays
on top. Upon clicking, the menu expands and displays a list of items that
belong to that category.
Main Menu Design:
There are two ways to create a main menu. In the Win32 approach,
create or open your .rc file and create a section as follows:
49
IDR_MAINFRAME MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "&New", IDM_FILENEW
MENUITEM "&Open", IDM_FILEOPEN
MENUITEM SEPARATOR
MENUITEM "E&xit", IDM_FILEEXIT
END
POPUP "&Help"
BEGIN
MENUITEM "&About", IDM_HELPABOUT
END
END
50
toolbar, it is equipped with a gray button. Design the button, once you start
designing a button, a new one is added. If the designed button is not needed
any more delete it and drag it away from the toolbar. The space between two
buttons is called a separator. To put a separator between two buttons, drag one
away from the other just a little. A toolbar can be equipped with various types
of controls.
2.3.5 Introduction to Accelerators
An access key is a letter that allows the user to perform a menu action
faster by using the keyboard instead of the mouse. This is usually faster
because the user would not need to position the mouse anywhere, which
reduces the time it takes to perform the action.
The most basic accelerator keys allow the user to access each item of
the menu with a key. To do this, the user must first give focus to the menu. This
is done by press the F10 function key or Alt. Once the menu has focus, you can
provide a unique letter that the user can press to active the menu. Each main
popup menu must have a unique letter that serves as access key. The letter is
underlined to show that it the access key for that particular menu. To create an
access key, type an ampersand "&" on the left of the menu item.
2.3.6 Shortcuts
A shortcut key is a key or a combination of keys the user presses to
perform an action that would otherwise be done on a menu item. Most shortcuts
are made of the Ctrl key simultaneously pressed with a letter key. Examples are
Ctrl + N, Ctrl + O, or Ctrl + D.
To create a shortcut, on the right side of the string that makes up a menu
caption, type \t followed by the desired combination.
1. In the Resource View, click Category, right-click Parent, and click
Properties
2. In the Caption box, click to right side of Parent, type \tCtrl+R
51
3. In the same way, set the shortcut of Child to Ctrl+D
52
In the same way, create an accelerator item for the Child menu:
53
2.3.8 Version
The version of a computer program allows having some information
about the product such as it official name, a release number, the person or
company that owns its copyright, the year of the current release, etc.
To create the pieces of information that make up the version
information, you can use the Version Information Editor.
2.3.9 Cursor
A cursor is a small picture that represents the position of the mouse on a
Windows object. Because Windows is a graphic intensive operating system,
when it installs, it creates a set of standard or regularly used cursors. These can
be seen by opening the Control Panel window and double-clicking the Mouse
icon. This opens the Mouse Properties dialog box where you can click the
Pointers tab to see a list of standard cursors installed by Windows:
Creating Cursors:
Microsoft Windows installs a wide array of cursors for various
occasions. Like all other resources, a cursor is identified by a constant integer
that can be communicated to other files that need it.
54
Essentially, a cursor uses only two colors, black or white. This is
because a cursor is only used as an indicator of the presence or position of the
mouse pointer on the screen. The minimum you can give a cursor is a shape.
This can be a square, a rectangle, a circle, an ellipse, a triangle, or any shape of
your choice. You can make the cursor fully black by painting it with that color.
Between the black and white colors, two gray degrees are provided to
you. In reality these two colors are used to give a transparency to the cursor so
the background can be seen when the mouse passes over a section of the
document.
After designing a cursor, you should define its hot spot. A cursor's hot
spot is the point that would be used to touch the specific point that the mouse
must touch to perform the action expected on the mouse. The hot spot must be
an area, namely a spot, on the cursor but it could be anywhere on that cursor.
You should specify the hot spot in the most intuitive section of the cursor. In
other words, the user should easily identify it since it is not otherwise visible.
If you do not want to show a cursor, you can use the Wind32 API
ShowCursor() function. Its syntax is:
int ShowCursor(BOOL bShow);
To hide a cursor, specify the argument as FALSE.
2.3.10 String Tables
A string table is a list of all object strings that are part of an application.
It allows any part of the program to refer to that table when a common string is
needed. The advantage of a string table is that it can be used as a central place
when to store or retrieve strings that any other objects of the application may
need. These can include the titles or captions of Windows controls, the
formatting strings used inside of functions or controls.
Creating and Using a String Table:
When you install Microsoft Visual C++, it also installs a lot of strings
that are readily available for your applications. To create a string table, from the
Add Resource dialog box, click String Table and click New. Each item of the
table is made of three sections: an identifier, a constant natural number, and a
caption. To add a new item, you can right-click in the String Table window and
click New String. You can also double-click the last empty row in the window.
You can also press Insert. Either case, the String Properties window would
display:
55
You can either type a new ID or select an existing ID from the ID
combo box. Then type the associated string in the Caption box. Continually,
you would have created a String Table:
The identifier, ID, is the same type of ID used when creating the
resources earlier. In fact, most of the IDs used on a string table are shared
among resources, as we will learn when reviewing the
CFrameWnd::LoadFrame() method. The value column contains a constant
LONG integer for each identifier. You will not need to specify this number
when using the String Table window; Visual C++ automatically and
independently creates and manages those numbers.
56
In the Resource Symbols window, to create a new string, click the
New... button to display the New Symbol dialog box:
You can then type an IDentifier in the Name edit box and the desired
number in the Value edit box. Over all, you should only use numbers between
101 and 127 and avoid numbers over 57344.
To edit an item from the String Table window, double-click the row
needed to display the String Properties window with the selected item.
Window Registration and Standard Resources:
The CFrameWnd::Create() method we have used so far provides a
quick mechanism to create a window. Unfortunately, it is not equipped to
recognize custom resources. In reality, this method is only used to create a
window, not to receive resources. Its first argument, lpszClassName is used to
get a window that has been built, that is, a window whose resources have been
specified. If you do not specify these resources, that is, if you pass the
lpszClassName argument as NULL, the compiler would use internal default
values for the window. These default are: a window that can be redrawn when
the user moves or resizes it, a white background for the main area of the
window, the arrow cursor, and the Windows "flat" icon, called
IDI_APPLICATION.
To use your own resources, you must first create then register them. To
register the resources, you can call the AfxRegisterWndClass() global
function. Its syntax is:
57
LPCTSTR AFXAPI AfxRegisterWndClass(UINT nClassStyle,
HCURSOR hCursor = 0,
HBRUSH hbrBackground = 0,
HICON hIcon = 0);
This function is used to register, the window style, a cursor, a color for
the background, and an icon. Only the window style is required. After
registering the window's style or the style and the resources, this function
returns a (constant) string that can be passed as the first argument of the
CFrameWnd::Create() method.
58
NOTES
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
59
UNIT – III
3.1 DIALOG BOX
A dialog box is a rectangular window whose main role is to host or hold
other Windows controls. For this reason, a dialog box is referred to as a
container. It is the primary interface of user interaction with the computer. By
itself, a dialog box means nothing. The controls it hosts accomplish the role of
dialog between the user and the machine.
A dialog box has the following characteristics
It is equipped with the system Close button . As the only system
button, this button allows the user to dismiss the dialog and ignore
whatever the user would have done on the dialog box.
It cannot be minimized, maximized, or restored. A dialog box does not
have any other system button but Close.
It is usually modal. The user is usually not allowed to continue any
other operation until the dialog box is dismissed.
It provides a way for the user to close or dismiss the dialog. Most dialog
boxes have the OK and the Cancel buttons, although this depends on the
application developer. When the dialog has the OK and the Cancel
buttons, the OK button is configured to behave as if the user had
pressed Enter. In that case, whatever the user had done would be
acknowledged and transferred to the hosting dialog box, window, or
application. Pressing Esc applies the same behavior as if the user had
clicked Cancel.
Dialog Box Creation:
When using Win32 to create an application, a dialog is created using a
text file called a resource file. The file has the extension .rc. Microsoft Visual
C++ makes it particularly easy to create a dialog box and, behind the scenes, it
creates the appropriate section for a dialog box. To create a dialog box, from
the Add Resources dialog box, select the Dialog node and the object is ready.
After creating a "physical" dialog box, you should create its class so that
other objects of the application can use this control.
Creating a Dialog Box:
1. To create a dialog box, on the main menu, click Project -> Add
Resource...
60
Fig – 3.1 Add Resource Dialog Box
2. In the Add Resource dialog box, click Dialog and click
New
3. To save the dialog box and the new resource, on the
61
}
BOOL CExerciseApp::InitInstance()
{
CExoDialog Dlg;
m_pMainWnd = &Dlg;
Dlg.DoModal();
return TRUE;
}
CExerciseApp theApp;
3.1.1 The MFC Wizard for a Dialog-Based Application
Microsoft Visual C++ provides an easier way to create an application
that is mainly based on a dialog box. To use this technique, start a new project
and specify that you want to create an MFC Application.
Steps to create a dialog box:
1. On the main menu, click File -> New -> Project...
2. In the New Project dialog box, in the Templates list, click MFC Application
3. Set the Project Name to ExoDialog2.
3.1.2 Properties of a Dialog Box
Like every resource, a dialog box is recognized throughout the program
by an identifier. By default, the first dialog box is identified as
IDD_DIALOG1. In this name, ID stands for IDentifier. The second D stands
for Dialog. In most cases, you should give an explicit identifier to each
resource. For example, if a dialog box is used as an employment application,
you can identify it as IDD_EMPL_APP or something like that.
Dialog box contains the title bar. The caption of the title bar can be
changed at the design time using properties window. At run time, to change the
caption, call the CWnd::SetWindowText() method and provide the necessary
string as argument.
Example:
BOOL CExoDialog2Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
SetWindowText("Sample Dialog Box”");
return TRUE; // return TRUE unless you set the focus to a control
}
62
By convention, a dialog box is equipped with only the system Close
button on its title bar. The Minimize and Maximize buttons are omitted. If
you want to add the Minimize button , at design time, set the Minimize Box
property to True or checked. If you want the Maximize button , set its
property to True or checked. Setting one of these properties to True or checked
and not the other would disable the other system button. Therefore, here are the
combinations you can get:
i)System Menu = False There is no system button
ii) System Menu = True
Minimize Box = False The Minimize button is disabled
Maximize Box = True
iii)System Menu = True
Minimize Box = True The Maximize button is disabled
Maximize Box = False
iv) System Menu = True
Minimize Box = True Both the Minimize and Maximize buttons
are enabled
Maximize Box = True
v) System Menu = True
Minimize Box = False Only the Close button is available
Maximize Box = False
A window is referred to as child if its appearance is dependent of the
appearance of another window. All of the Windows controls that we will be
placing on our dialog boxes are child controls.
A window is called overlapped if it has the following characteristics:
* It has a title bar equipped with a caption and at least one of the system
buttons
* It has borders
The Child, Popup, and Overlapped characteristics can be set at design
time using the Style property.
Because a dialog box follows these rules, it qualifies as an overlapped
window.
By design, a dialog box has thick borders and cannot be resized from its
borders or corners, even if the system buttons are available. This characteristic
of dialog boxes is controlled by the Border property. The default border of a
dialog box is Dialog Frame. If you want the user to be able to resize a dialog
box, set its Border value to Resizing. A Thin value gives a thin border to the
dialog box. If you do not want borders at all on the object, set its Border value
to None. This also removes the title bar and thus the system buttons:
63
3.1.3 Dialog Box Methods
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);
The default constructor, CDialog() can be use to create a variable whose
behavior is not yet known or, for one reason or another, cannot yet be defined.
The resources in MFC have an identifier that allows them to be
recognized by other others of an application. This identifier can be used as the
first argument, nIDTemplate, of a CDialog() constructor to create a dialog box
from an existing resource. If you are using a Win32 template to create a dialog
box, pass the name of this template as a string to a CDialog() constructor,
lpszTemplateName. The second argument of the last two constructors allow us
to specify "who" owns the dialog box you are creating. If the dialog box has a
parent, which is usually a CWnd type, specify its name as the pParentWnd
argument. Otherwise, leave this argument at its default, which is NULL, letting
the application own the dialog box.
There are two types of dialog boxes: modal and modeless. A Modal
dialog box is one that the user must first close in order to have access to any
other framed window or dialog box of the same application:
The Paragraph dialog box of WordPad is a modal dialog box: when it is
displaying, the user cannot use any other part of WordPad unless he or she
closes this object first. After creating a dialog box, to display it as modal, call
the DoModal() method. Its syntax is:
virtual int DoModal();
This method by itself does nothing more than displaying a dialog box as
modal.
A modeless dialog box allows the user to access the main application or
any other possible object of the application even if this dialog box is displaying.
The user can decide to close it when the object is not needed anymore or the
user can keep it on as long as necessary.
Example:
The Find dialog box of WordPad is an example of a modeless dialog
box. Although it is displaying on this picture, the user can still click and
activate any of the windows in the background.
Because a modeless dialog box is closed as the user judges it necessary,
making it possible to forget, the operating system needs to make sure that this
object closes when its parent application closes so its memory resource can be
64
freed and made available to other applications. Thus creating a modeless dialog
is little different. First create a dialog resource and associate a class to it. To
formally create a modeless dialog box and make it part of the application, you
can use the Create() method of the CDialog class. The MFC provides two
syntaxes that are:
BOOL Create(UINT nIDTemplate, CWnd* pParentWnd = NULL);
BOOL Create(LPCTSTR lpszTemplateName, CWnd* pParentWnd =
NULL);
As done with the CDialog constructor, the nIDTemplate parameter is
the identifier you used when visually creating the dialog resource. If you are
using a dialog box from a template, specify its name as the lpszTemplateName
argument. In order to effectively use a modeless dialog box, it must be called
from another window. Otherwise you can just create a regular dialog box. The
object from which you will be calling the dialog box is also responsible for
closing it (or "cleaning" it). Therefore, the class that calls the modeless dialog
box "owns" it. This means that you can specify it as the pParentWnd
argument.
When creating a modeless dialog box, declare a pointer to its class.
Then call the Create() method, passing the identifier or the template being
used.
CDialog5Dlg::CDialog5Dlg(CWnd* pParent /*=NULL*/)
: CDialog(CDialog5Dlg::IDD, pParent)
{
CCoolMode* Cool = new CCoolMode();
Cool->Create(IDD_DLG_MDLS,this);
}
To display the dialog box set the visible property to true at the design
time or call the CWnd::ShowWindow() method. Its syntax is:
BOOL ShowWindow(int nCmdShow);
This method is used to display or hide any window that is a descendent
of CWnd. Its argument, nCmdShow, specifies what to do with the appearance
or disappearance of the object. Its possible values are:
Value Description
SW_SHOW Displays a window and makes it visible
SW_SHOWNORMAL Displays the window in its regular size. In
most circumstances, the operating system
keeps track of the last location and size a
window such as Internet Explorer or My
Computer had the last time it was
65
displaying. This value allows the OS to
restore it.
SW_SHOWMINIMIZED Opens the window in its minimized state,
representing it as a button on the taskbar
SW_SHOWMAXIMIZED Opens the window in its maximized state
SW_SHOWMINNOACTIVE Opens the window but displays only its
icon. It does not make it active
SW_SHOWNA As previous
SW_SHOWNOACTIVATE Retrieves the window's previous size and
location and displays it accordingly
SW_HIDE Used to hide a window
SW_MINIMIZE shrinks the window and reduces it to a
button on the taskbar
SW_RESTORE If the window was minimized or
maximized, it would be restored to its
previous location and size
To use one of these constants, pass it to the ShowWindow() method.
For example, to minimize a window, you would use code as follows:
ShowWindow(SW_SHOWMINIMIZED);
After creating a dialog box, to initialize it (or the objects it is hosting),
use the OnInitDialog() method. Its syntax is:
virtual BOOL OnInitDialog( );
To programmatically change a dialog's property, access the
OnInitDialog() event and call the SetWindowText() as follows:
BOOL CDialog2aDlg::OnInitDialog()
{
CDialog::OnInitDialog();
...
// TODO: Add extra initialization here
this->SetWindowText("Personal Information");
return TRUE; // return TRUE unless you set the focus to a control
}
To create a modeless dialog box, in the OnInitDialog() event of the
main dialog box type the following:
BOOL CDialog2aDlg::OnInitDialog()
{
CDialog::OnInitDialog();
66
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING,
IDM_ABOUTBOX, strAboutMenu);
}
}
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
this->SetWindowText("Personal Information");
CSecondDlg *Floater = new CSecondDlg;
Floater->Create(IDD_DLG_FLOATER, this);
Floater->ShowWindow(SW_SHOW);
return TRUE; // return TRUE unless you set the focus to a control
}
3.2 CONTROLS FUNDAMENTALS
A Windows control is an object that displays or is part of an application
and allows the user to interact with the computer. There are various types of
controls such as
a text-based control is an object whose main function is to display to, or
request text from, the user
A list-based control displays a list of items
A progress control is used to show the evolution of an action
a static control can be used to show colors, a picture or something that
does not regularly fit in the above categories
67
Controls can be added to the application either at the design time or at
the run time.
The Parent-Child Window Relationship:
There are two types of windows or controls you will deal with in your
applications. The type is defined by the relationship a window has with regards
to other windows that are part of an application:
• Parent: a window is referred to as a parent when there are or there can
be other windows that depend on it. For example, if you look at the toolbar of
Visual C++, it is equipped with the buttons. The toolbar is a parent to the
buttons.The most regular parents you will use are forms and dialog boxes.
• Child: A window is referred to as child when its existence and
especially its visibility depend on another window called its parent. When a
parent is created, made active, or made visible, it gives existence and visibility
to its children. When a parent gets hidden, it also hides its children. If a parent
moves, it moves with its children, the children keep their positions and
dimensions inside the parent. When a parent is destroyed, it also destroys its
children. All of the Windows controls you will use in your applications are
child controls. A child window can also be a parent of another control. For
example, the Standard toolbar of Visual Studio is the parent of the buttons on it.
If you close or hide the toolbar, its children disappear. At the same time, the
toolbar is a child of the application's frame. If you close the application, the
toolbar disappears, along with its own children. In this example, the toolbar is a
child of the frame but is a parent for its buttons.
• The CButton class is based on CWnd. Therefore, CWnd is the parent
class of CButton .
When a button is placed on a form, the form, which is based on CView
(indirectly) is the window parent of the button and not its parent class.
Parent Controls:
An object is referred to as a parent or container when its main job is to
host other controls. This is done by adding controls to it. The most commonly
used parent control is the dialog box. Besides the WNDCLASS structure, the
Win32 library also offers the WNDCLASEX structure used to create an
application. Besides all of the characteristics of WNDCLASS, the
WNDCLASSEX structure requires that you specify the size of the structure
and it allows you to set a small icon for your application. This can be done as
follows:
const char *WndName = "Windows Fundamentals";
LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM
wParam, LPARAM lParam);
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE
hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
68
{
MSG Msg;
WNDCLASSEX WndClsEx;
WndClsEx.cbSize = sizeof(WNDCLASSEX);
WndClsEx.style = CS_HREDRAW | CS_VREDRAW;
WndClsEx.lpfnWndProc = WndProc;
WndClsEx.cbClsExtra = 0;
WndClsEx.cbWndExtra = 0;
WndClsEx.hInstance = hInstance;
WndClsEx.hIcon = LoadIcon(NULL, IDI_ASTERISK);
WndClsEx.hCursor = LoadCursor(NULL, IDC_ARROW);
WndClsEx.hbrBackground = (HBRUSH)COLOR_ACTIVECAPTION;
WndClsEx.lpszMenuName = NULL;
WndClsEx.lpszClassName = ClsName;
WndClsEx.hIconSm = LoadIcon(NULL, IDI_ASTERISK);
RegisterClassEx(&WndClsEx);
while( GetMessage(&Msg, NULL, 0, 0) )
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
Besides the CreateWindow() function, the Win32 library provides the
CreateWindowEx() function you can use to create a window. The
CreateWindowEx() function has the followsing syntax:
HWND CreateWindowEx(
DWORD dwExStyle,
LPCTSTR lpClassName,
LPCTSTR lpWindowName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
69
HWND hWndParent,
HMENU hMenu,
HINSTANCE hInstance,
LPVOID lpParam
);
3.3 CONTROLS
Controls are objects that users can interact with to enter or manipulate
data. They commonly appear in dialog boxes or on toolbars. There are three
main types of controls namely,
Windows common controls, including owner-drawn controls
ActiveX Controls
Other control classes supplied by the Microsoft Foundation Class
Library (MFC)
Windows Common Controls
The Windows operating system has always provided a number of
Windows common controls. These control objects are programmable, and the
Visual C++ dialog editor supports adding them to your dialog boxes. The
Microsoft Foundation Class Library (MFC) supplies classes that encapsulate
each of these controls. Class CWnd is the base class of all window classes,
including all of the control classes.
ActiveX Controls
ActiveX controls, formerly known as OLE controls, can be used in
dialog boxes in your applications for Windows, or in HTML pages on the
World Wide Web.
70
Fig 3.2 Visual C++ 7 Controls
Other MFC Control Classes
In addition to classes that encapsulate all of the Windows common
controls and that support programming your own ActiveX controls (or using
ActiveX controls supplied by others), MFC supplies the following control
classes of its own:
CBitmapButton
CCheckListBox
CDragListBox
The second option used to add a control to an application consists of
programmatically creating it. All visible controls of the MFC library are based
on the CWnd class. This class is equipped with all the primary functionality
that a regular window object needs. As the parent of all visible window classes,
it provides the other controls with properties and methods to implement their
appearance and behavior. To use the CWnd class:
You can directly derive a class from CWnd
You can use one of the CWnd-derived classes (CView, CFrameWnd,
etc)
You can derive a class from one of the CWnd-derived classes; for
example you can create a class based on CStatic
You can directly declare a CWnd variable in your application and
initialize it the class of your choice .
71
To create a control using a known class, you must declare a variable of
the class on which the control is based. Every control is based on a specific
class, and that class is directly or indirectly derived from CWnd. An example
of such a declaration would be:
void CParentLoader::TodaysMainEvent()
{
CStatic Label;
}
You can also declare the variable as a pointer. In this case, make sure
that you initialize the class using the new operator. An example would:
void CParentLoader::TodaysMainEvent()
{
CStatic *Label = new CStatic;
}
Based on the rules of inheritance and polymorphism, you can also
declare the pointer as CWnd but initialize it with the desired class. Here is an
example:
void CParentLoader::TodaysMainEvent()
{
CWnd *Panel = new CStatic;
}
You can also use the CWnd::Create() method to create a control. The
syntax of this method is:
virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR
lpszWindowName,
DWORD dwStyle, const RECT& rect, CWnd* pParentWnd,
UINT nID, CCreateContext* pContext = NULL);
The availability of a child window to other parts of a program is defined
by the scope in which the control is created. If you create a control in an event
or a method of a parent class, it can be accessed only inside of that event.
Trying to access it outside would produce an error. If you want to access a child
or dependent window from more than one event or method, you must create it
globally. This is usually done by declaring the variable or pointer in the class of
the parent.
After declaring the variable, to initialize it, call its Create() method.
The syntax of this method depends on the window you are trying to create.
After initializing the window, it may become alive, depending on the style or
properties you assigned to it.
72
The other technique you can use is to derive a class from the control
whose behavior and appearance can serve as a foundation for your control. For
example, you can derive a control as follows:
class CColoredLabel : public CStatic
{
public:
CColoredLabel();
virtual ~CColoredLabel();
DECLARE_MESSAGE_MAP()
};
Such a class as the above CColoredLabel gives you access to the
public and protected properties and methods of the base class. To use the new
class in your application, declare a variable from and call the Create() method.
The window name is a default string that displays on the control when
the control comes up. In the previous lessons, we saw that this string displays
as caption on the title bar of a window frame or a dialog box. This property is
different for different controls.
When designing a static control using the Static Text button , to set
the window name, change the text of the Caption field.
To set the default text of a control, you can either do this when creating
the control or change its text at any time. Again, this can depend on the control.
To set the default text when programmatically creating the control, pass a string
value as the lpszWindowName argument of the Create() or CreateEx()
method.
void CSecondDlg::OnThirdControl()
{
// TODO: Add your control notification handler code here
CWnd *Memo = new CWnd;
Memo->Create("EDIT", "Voice Recorder", );
}
Many (even most) controls do not use a window name. Therefore, you
can pass it as NULL
A style is a characteristic that defines the appearance and can set the
behavior of a control. The styles are varied from one control to another
although they share some of the characteristics common to most Windows
controls.
73
Fig 3.3 – Genearal property window of control
74
Second->Create(NULL, NULL, WS_CHILD, );
}
void CSecondDlg::OnThirdControl()
{
// TODO: Add your control notification handler code here
CWnd *Memo = new CWnd;
Memo->Create("EDIT", "Voice Recorder", WS_CHILD, );
}
void CSecondDlg::OnFourthControl()
{
// TODO: Add your control notification handler code here
CStatic *Label = new CStatic;
Label->Create("United Nations", WS_CHILD, );
}
Visibility
If you want to display a control to the user when the parent window
comes up, at design time, set the Visible property to True. If you are
programmatically creating the control, add the WS_VISIBLE property.
void CSecondDlg::OnSecondControl()
{
// TODO: Add your control notification handler code here
CWnd *Second = new CWnd;
Second->Create(NULL, NULL, WS_CHILD | WS_VISIBLE, );
}
If you do not set the Visible property to True or do not add the
WS_VISIBLE property, the control would be hidden (but possibly available)
when its parent window comes up. Later on, you can display the control by
calling the CWnd::ShowWindow() method. Remember that this method is
used to either hide or to reveal a control by passing the appropriate constant,
SW_HIDE to hide and SW_SHOW to display it. Here is an example that
displays a control that missed the WS_VISIBLE property when it was created:
void CSecondDlg::OnFirstControl()
{
// TODO: Add your control notification handler code here
CWnd *First = new CWnd;
75
CString StrClsName = AfxRegisterWndClass(CS_VREDRAW |
CS_HREDRAW, LoadCursor (NULL, IDC_CROSS), (HBRUSH) Get Stock
Object (BLACK_BRUSH), LoadIcon(NULL, IDI_WARNING));
First->Create(StrClsName, NULL, WS_CHILD);
First->ShowWindow(SW_SHOW);
}
When the ShowWindow() method is called with the SW_SHOW
value, if the control was hidden, it would become visible; if the control was
already visible, nothing would happen. In the same way, when this method is
called with the SW_HIDE argument, the control would be hidden, whether it
was already hidden or not. If you want to check the visibility of a control before
calling this method, you can call the CWnd::IsWindowVisible() method. Its
syntax is:
BOOL IsWindowVisible() const;
This method returns TRUE if the control that called it is already visible.
If the control is hidden, the method returns FALSE.
3.4 MFC CONTROL CLASSES
Control MFC class Description
animation CAnimateCtrl Displays successive frames of an AVI
video clip
76
long operation
77
for it. Remember that you can still add both types of variables if necessary. You
can also programmatically create a label by declaring a variable or a pointer to
CStatic using its constructor. To initialize it, call its Create() method. Here is an
example:
BOOL CLabelDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
CStatic *Label = new CStatic;
Label->Create("Saint Lucia", WS_CHILD | WS_VISIBLE,
CRect(10, 40, 160, 60), this, 0x188);
return TRUE;
}
In the create method the first parameter is the prompt to be displayed,
second parameter is the style followed by the rect size, parent object and the
identifier.
Probably the most important property of a label is the text it displays.
This is set at design time by changing the value of the Caption field. If you
want to change the caption of the control, you can call the
CWnd::SetWindowText() method. Here is an example:
BOOL CLabelDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
m_Label.SetWindowText("Testing text for static control”);
return TRUE;
}
A static text control displays its caption using the system dialog box,
which could be MS Sans Serif or other font depending on your programming
environment. Such a font is applied to all controls on a dialog box or a form. If
you want to use a different font for your static control, you must first create the
font, then select it for the static control by calling the CWnd::SetFont() method.
Here is an example:
BOOL CLabelDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
CFont *m_Font1 = new CFont;
78
m_Font1->CreatePointFont(160, "Garamond");
m_Label.SetFont(m_Font1);
m_Label.SetWindowText("Frederick Randt");
CStatic *Label = new CStatic;
Label->Create("Saint Lucia", WS_CHILD | WS_VISIBLE,
CRect(10, 40, 200, 100), this, 0x188);
CFont *m_Font2 = new CFont;
m_Font2->CreatePointFont(240, "Verdana");
Label->SetFont(m_Font2);
return TRUE;
}
To display its caption, the static control starts on the top-left corner of
the allocated rectangle. To control the horizontal alignment of text, select the
desired value from the Align Text combo box. A static control can also have its
text changed in response to user's action.
3.4.2 Button Control
A button control is a small, rectangular child window that can be
clicked on and off. Buttons can be used alone or in groups and can either be
labeled or appear without text. A button typically changes appearance when the
user clicks it. Typical buttons are the check box, radio button, and pushbutton.
A CButton object can become any of these, according to the button style
specified at its initialization by the Create member function.
In addition, the CBitmapButton class derived from CButton supports
creation of button controls labeled with bitmap images instead of text. A
CBitmapButton can have separate bitmaps for a button's up, down, focused,
and disabled states. You can create a button control either from a dialog
template or directly in your code. In both cases, first call the constructor
CButton to construct the CButton object; then call the Create member
function to create the Windows button control and attach it to the CButton
object. Construction can be a one-step process in a class derived from
CButton. Write a constructor for the derived class and call Create from within
the constructor. To handle Windows notification messages sent by a button
control to its parent (usually a class derived from CDialog), add a message-map
entry and message-handler member function to the parent class for each
message.
Messages
Each message-map entry takes the following form:
ON_Notification( id, memberFxn )
79
where id specifies the child window ID of the control sending the
notification and memberFxn is the name of the parent member function you
have written to handle the notification.
The parent's function prototype is as follows:
afx_msg void memberFxn( );
Potential message-map entries are as follows:
Initialization
Create Creates the Windows button control and attaches it to the CButton
object.
Operations
80
GetIdealSize Retrieves the ideal size of the button control.
GetState Retrieves the check state, highlight state, and focus state of
a button control.
81
: CDialog(CExerciseDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CExerciseDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
pButton = new CButton;
}
Button Styles:
BS_3STATE - Same as a check box, except that the box can be
dimmed as well as checked. The dimmed state typically is used to show
that a check box has been disabled.
BS_AUTO3STATE - Same as a three-state check box, except that the
box changes its state when the user selects it.
BS_AUTOCHECKBOX - Same as a check box, except that a check
mark appears in the check box when the user selects the box; the check
mark disappears the next time the user selects the box.
BS_AUTORADIOBUTTON - Same as a radio button, except that
when the user selects it, the button automatically highlights itself and
removes the selection from any other radio buttons with the same style
in the same group.
BS_BITMAP - Specifies that the button displays a bitmap.
BS_BOTTOM - Places text at the bottom of the button rectangle.
BS_CENTER - Centers text horizontally in the button rectangle.
BS_CHECKBOX - Creates a small square that has text displayed to its
right (unless this style is combined with the BS_LEFTTEXT style).
BS_DEFPUSHBUTTON - Creates a button that has a heavy black
border. The user can select this button by pressing the ENTER key. This
style enables the user to quickly select the most likely option (the
default option).
BS_FLAT - Specifies that the button is two-dimensional; it does not
use the default shading to create a 3-D image.
BS_GROUPBOX - Creates a rectangle in which other buttons can be
grouped. Any text associated with this style is displayed in the
rectangle's upper-left corner.
BS_ICON - Specifies that the button displays an icon.
BS_LEFT - Left aligns the text in the button rectangle. However, if the
button is a check box or radio button that does not have the
82
BS_RIGHTBUTTON style, the text is left aligned on the right side of
the check box or radio button.
BS_LEFTTEXT - When combined with a radio-button or check-box
style, the text appears on the left side of the radio button or check box.
BS_MULTILINE - Wraps the button text to multiple lines if the text
string is too long to fit on a single line in the button rectangle.
BS_NOTIFY - Enables a button to send BN_DBLCLK,
BN_KILLFOCUS, and BN_SETFOCUS- notification messages to its
parent window. Note that buttons send the BN_CLICKED- notification
message regardless of whether it has this style.
BS_OWNERDRAW - Creates an owner-drawn button. The
framework calls the DrawItem member function when a visual aspect
of the button has changed. This style must be set when using the
CBitmapButton class.
BS_PUSHBUTTON Creates a pushbutton that posts a
WM_COMMAND message to the owner window when the user
selects the button.
BS_PUSHLIKE - Makes a button (such as a check box, three-state
check box, or radio button) look and act like a push button. The button
looks raised when it isn't pushed or checked, and sunken when it is
pushed or checked.
BS_RADIOBUTTON - Creates a small circle that has text displayed
to its right (unless this style is combined with the BS_LEFTTEXT
style). Radio buttons are usually used in groups of related, but mutually
exclusive, choices.
BS_RIGHT - Right aligns the text in the button rectangle. However, if
the button is a check box or radio button that does not have the
BS_RIGHTBUTTON style, the text is right aligned on the right side of
the check box or radio button.
BS_RIGHTBUTTON - Positions a radio button's circle or a check
box's square on the right side of the button rectangle. Same as the
BS_LEFTTEXT style.
BS_TEXT - Specifies that the button displays text.
BS_TOP - Places text at the top of the button rectangle.
BS_USERBUTTON Obsolete, but provided for compatibility with
16-bit versions of Windows. Win32-based applications should use
BS_OWNERDRAW instead.
BS_VCENTER Places text in the middle (vertically) of the button
rectangle
83
Example:
Write a program in Visual C++ to display a message when the user
clicks the button.
Solution:
class CExerciseDlg : public CDialog
{
// Construction
public:
CButton *pButton;
CExerciseDlg(CWnd* pParent = NULL); ...
}
CExerciseDlg::CExerciseDlg(CWnd* pParent /*=NULL*/)
: CDialog(CExerciseDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CExerciseDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
pButton = new CButton;
}
CExerciseDlg message handlers
BOOL CExerciseDlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
// TODO: Add extra initialization here
pButton->Create("&Submit", WS_CHILD | WS_VISIBLE,
CRect(150, 20, 250, 43), this, 0x302);
return TRUE; }
3.4.3 Edit Box
An edit box is a control used to either display text, to request text, or to
do both. It is provided as a rectangular control with a sunken white background
and 3-D borders. To add an edit box and click the desired area on a form or
a dialog box.
84
CEdit inherits significant functionality from CWnd. To set and
retrieve text from a CEdit object, use the CWnd member functions
SetWindowText and GetWindowText, which set or get the entire contents of an
edit control, even if it is a multiline control. Text lines in a multiline control are
separated by '\r\n' character sequences. Also, if an edit control is multiline, get
and set part of the control's text by calling the CEdit member functions
GetLine, SetSel, GetSel, and ReplaceSel.
Messages
To handle Windows notification messages sent by an edit control to its
parent (usually a class derived from CDialog), add a message-map entry and
message-handler member function to the parent class for each message.
Each message-map entry takes the following form:
ON_Notification( id, memberFxn )
where id specifies the child window ID of the edit control sending the
notification, and memberFxn is the name of the parent member function you
have written to handle the notification.
The parent's function prototype is as follows:
afx_msg void memberFxn( );
Following is a list of potential message-map entries and a description of
the cases in which they would be sent to the parent:
ON_EN_CHANGE The user has taken an action that may have altered
text in an edit control. Unlike the EN_UPDATE notification message,
this notification message is sent after Windows updates the display.
ON_EN_ERRSPACE The edit control cannot allocate enough memory
to meet a specific request.
ON_EN_HSCROLL The user clicks an edit control's horizontal scroll
bar. The parent window is notified before the screen is updated.
ON_EN_KILLFOCUS The edit control loses the input focus.
ON_EN_MAXTEXT The current insertion has exceeded the specified
number of characters for the edit control and has been truncated. Also
sent when an edit control does not have the ES_AUTOHSCROLL style
and the number of characters to be inserted would exceed the width of the
edit control. Also sent when an edit control does not have the
ES_AUTOVSCROLL style and the total number of lines resulting from
a text insertion would exceed the height of the edit control.
ON_EN_SETFOCUS Sent when an edit control receives the input
focus.
ON_EN_UPDATE The edit control is about to display altered text.
Sent after the control has formatted the text but before it screens the text
so that the window size can be altered, if necessary.
85
ON_EN_VSCROLL The user clicks an edit control's vertical scroll bar.
The parent window is notified before the screen is updated.
Construction and Initialization
Create Creates the Windows edit control and attaches it to the CEdit object.
CEdit Attributes
GetMargins Gets the left and right margins for this CEdit.
86
current selection in an edit control.
SetCueBanner Sets the text that is displayed as the text cue, or tip, in
an edit control when the control is empty and does not
have focus.
SetHandle Sets the handle to the local memory that will be used
by a multiple-line edit control.
SetMargins Sets the left and right margins for this CEdit.
CEdit Operations
LimitText Limits the length of the text that the user may enter into
an edit control.
LineFromChar Retrieves the line number of the line that contains the
specified character index.
87
SetPasswordChar Sets or removes a password character displayed in an
edit control when the user enters text.
Clear Deletes (clears) the current selection (if any) in the edit control.
Copy Copies the current selection (if any) in the edit control to the
Clipboard in CF_TEXT format.
Cut Deletes (cuts) the current selection (if any) in the edit control and
copies the deleted text to the Clipboard in CF_TEXT format.
Paste Inserts the data from the Clipboard into the edit control at the
current cursor position. Data is inserted only if the Clipboard
contains data in CF_TEXT format.
Besides this the important concept that lies behind the edit control is the
DDV(Dialog Data Validation) and DDX(Dialog Data Exchange) mechanism.
The MFC framework provides an efficient mechanism for transferring and
validating data in a dialog box through the DDX and DDV routines. Dialog
Data Exchange (DDX) is an easy way to initialize the controls in a dialog box
and gather data input by the user. Dialog Data Validation (DDV) is an easy way
to validate data entry in a dialog box.
To exchange the data from edit box to a variable and from a variable to
editbox the UpdateData(Boolean) is used.
88
1. If UpdateData(true) is used then the value from the edit box is
exchanged to a variable.
2. If UpdateData(false) is used then the value from the variable is
exchanged to a edit box.
Points to Remember:
1. To perform CEdit operations, create a member variable for the edit
control under the category as control which takes CEdit as the base
class.
2. To perform other Operations, create a member variable for the edit
control under the category as value which takes CString as the base
class.
Example:
To limit the text and to set password character.
1. Create a member variable for the edit box control.
2. In the OnInitDialog function user can include the following segment.
m_tt.SetLimitText(10);
m_tt.SetPasswordChar('*');
Example : For example to change from lower case to uppercase.
Create a member variable for the edit box control.
2. In the button click member function user can include the following
segment.
m_t2.MakeUpper();
89
3.4.4 Combobox
Combobox provides the functionality of a Windows combo box. A
combo box is a Windows control that holds a list of items. Each item can be a
null-terminated string or it can be made of a bitmap and a string. A combo box
shares a lot of characteristics with a list but there are more variances of a
combo box.
As far as looks are concerned, there are two types of combo boxes. The
most regularly used combo box is made of two sections. The main part is an
edit box. On the right of the edit box, there is a button with a down pointing
arrow.
A combo box consists of a list box combined with either a static control
or edit control. The list-box portion of the control may be displayed at all times
or may only drop down when the user selects the drop-down arrow next to the
control.
The currently selected item (if any) in the list box is displayed in the
static or edit control. In addition, if the combo box has the drop-down list style,
the user can type the initial character of one of the items in the list, and the list
box, if visible, will highlight the next item with that initial character.
In the Drop down list combobox the edit box is non editable area. This
is where the user can only select the text and cannot type any letter in the edit
area. This is the difference between the Dropdown combo and dropdown list
combo.
The following table compares the three combo-box styles.
90
Each message-map entry takes the following form:
ON_Notification( id, memberFxn )
where id specifies the child-window ID of the combo-box control
sending the notification and memberFxn is the name of the parent member
function you have written to handle the notification.
The parent's function prototype is as follows:
afx_msg void memberFxn( );
The order in which certain notifications will be sent cannot be
predicted. In particular, a CBN_SELCHANGE notification may occur either
before or after a CBN_CLOSEUP notification.
Potential message-map entries are the following:
ON_CBN_CLOSEUP (Windows 3.1 and later.) The list box of a
combo box has closed. This notification message is not sent for a combo
box that has theCBS_SIMPLE style.
ON_CBN_DBLCLK The user double-clicks a string in the list box of a
combo box. This notification message is only sent for a combo box with
the CBS_SIMPLE style. For a combo box with the CBS_DROPDOWN
or CBS_DROPDOWNLIST style, a double-click cannot occur because a
single click hides the list box.
ON_CBN_DROPDOWN The list box of a combo box is about to drop
down (be made visible). This notification message can occur only for a
combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST
style.
ON_CBN_EDITCHANGE The user has taken an action that may have
altered the text in the edit-control portion of a combo box. Unlike the
CBN_EDITUPDATE message, this message is sent after Windows
updates the screen. It is not sent if the combo box has the
CBS_DROPDOWNLIST style.
ON_CBN_EDITUPDATE The edit-control portion of a combo box is
about to display altered text. This notification message is sent after the
control has formatted the text but before it displays the text. It is not sent
if the combo box has the CBS_DROPDOWNLIST style.
ON_CBN_ERRSPACE The combo box cannot allocate enough
memory to meet a specific request.
ON_CBN_SELENDCANCEL (Windows 3.1 and later.) Indicates the
user's selection should be canceled. The user clicks an item and then
clicks another window or control to hide the list box of a combo box.
This notification message is sent before the CBN_CLOSEUP
notification message to indicate that the user's selection should be
ignored. The CBN_SELENDCANCEL or CBN_SELENDOK
notification message is sent even if the CBN_CLOSEUP notification
91
message is not sent (as in the case of a combo box with the
CBS_SIMPLE style).
ON_CBN_SELENDOK The user selects an item and then either
presses the ENTER key or clicks the DOWN ARROW key to hide the list
box of a combo box. This notification message is sent before the
CBN_CLOSEUP message to indicate that the user's selection should be
considered valid. The CBN_SELENDCANCEL or CBN_SELENDOK
notification message is sent even if the CBN_CLOSEUP notification
message is not sent (as in the case of a combo box with the
CBS_SIMPLE style).
ON_CBN_KILLFOCUS The combo box is losing the input focus.
ON_CBN_SELCHANGE The selection in the list box of a combo box
is about to be changed as a result of the user either clicking in the list box
or changing the selection by using the arrow keys. When processing this
message, the text in the edit control of the combo box can only be
retrieved via GetLBText or another similar function. GetWindowText
cannot be used.
ON_CBN_SETFOCUS The combo box receives the input focus.
If you create a CComboBox object within a dialog box (through a
dialog resource), the CComboBox object is automatically destroyed when the
user closes the dialog box.
Construction
Initialization
InitStorage Preallocates blocks of memory for items and strings in the list-
box portion of the combo box.
General Operations
92
Cut Deletes (cuts) the current selection, if any, in
the edit control and copies the deleted text
onto the Clipboard in CF_TEXT format.
93
GetItemDataPtr Retrieves the application-supplied 32-bit value
associated with the specified combo-box item
as a pointer (void*).
LimitText Limits the length of the text that the user can
enter into the edit control of a combo box.
94
SetHorizontalExtent Sets the width in pixels that the list-box
portion of the combo box can be scrolled
horizontally.
String Operations
AddStri Adds a string to the end of the list in the list box of a
ng combo box or at the sorted position for list boxes with the
CBS_SORT style.
FindStri Finds the first string that contains the specified prefix in
ng the list box of a combo box.
FindStri Finds the first list-box string (in a combo box) that
95
ngExact matches the specified string.
ResetCo Removes all items from the list box and edit control of a
ntent combo box.
SelectSt Searches for a string in the list box of a combo box and, if
ring the string is found, selects the string in the list box and
copies the string to the edit control.
Example : To retrieve the text from a combbox and assign it to a Edit box.
1. Add a combobox and add a member variable under control category.
Eg :m_cb1
2. To initialize the items of a Combobox
* Initialize it in the OnInitDialog member function
* String is added as
m_cb1.AddString(“C”);
m_cb1.AddString(“C++”);
m_cb1.AddString(“Java”);
m_cb1.AddString(“VC++”);
3. Add a member function for combo box
Notification : CBN_SELCHANGE
m_cb1.GetLBText(m_cb1.GetCurSel(),m_t1);
UpdateData(false);
In the example the GetCurSel returns the index value of the currently
selected item. The GetLBText function returns the text of the currently selected
item and it is assigned to a string variable. Here it is assigned to edit box.
3.4.5 Radio Button
A radio button is a Windows control made of two sections: a round box
O and a label. The label informs the user as to what the control is used for. The
user makes his or her decision by selecting or clicking the round box. In
practical usage, a radio button is accompanied by one or more other radio
buttons that appear and behave as a group. The user decides which button is
valid by selecting only one of them. When the user clicks one button, its round
box fills with a (big) dot. When one button in the group is selected, the other
round buttons of the (same) group are empty. The user can select another
96
button by clicking a different choice, which empties the previous selection.
This technique of selecting is referred to as mutually-exclusive.
97
3. After making sure the TODO line is deleted, from the Toolbox,
click the Group Box and click on the dialog box to add it. Set its caption to
Calculation
4. Add three Static Text controls inside the Calculation group box.
Set their captions to Number &1:, Number &2: and Result, respectively.
5. Add three Edit Box controls to the right side of the existing
labels. Set their IDs to IDC_OPERAND1, IDC_OPERAND2, and
IDC_RESULT, respectively. Optionally, to add a line between the operands
and the result, from the Toolbox, click the Picture control; on the dialog box,
drag a line from the left side between Number 2 and Result and to the right.
6. Add another Group Box control to the right side of the existing
one on the dialog. Set its Caption to Operations
7. From the Toolbox, click the Radio Button control and click
inside the Operations group box. Set the radio button's ID to
IDC_ADDITION, set its Caption to &Addition, and check its Group check
box (make sure it displays a check mark; in the .NET environment select True
in the Group Combo Box)
98
2. Click the Member Variables property page. Double-click each control
and add the following variables:
99
Number1 = 0;
else
Number1 = atof(m_Operand1);
if( m_Operand2.IsEmpty() )
Number2 = 0;
else
Number2 = atof(m_Operand2);
Find out what radio button the user clicked. This is done considering
that the radio buttons are stored in an array.
The selected radio button can be identified by its ordinal position
based on the m_Operation integer.
switch(m_Operation)
{
case 0:
Result = Number1 + Number2;
break;
case 1:
Result = Number1 - Number2;
break;
case 2:
Result = Number1 * Number2;
break;
case 3:
Result = Number1 / Number2;
break;
}
// Now that a result is available, display it in the Result edit box
m_Result.Format("%.2f", Result);
UpdateData(FALSE);
}
9. From the ResourceView tab of the Workspace, display the dialog box
and uncheck the Group check box of the Addition radio button to make
it empty
10. Press Ctrl + W to get back to the MFC ClassWizard.
100
11. Click the Message Maps property sheet. Click the Object ID of each
radio control then, in the Messages list box, double-click
BN_CLICKED, accept the function name, and click OK
12. Click Edit Code and simply call the Calculate function every time the
user clicks one of the radio buttons. Implement them as follows:
void COperations1Dlg::OnAddition()
{
Calculate();
}
void COperations1Dlg::OnSubtraction()
{
Calculate();
}
void COperations1Dlg::OnMultiplication()
{
Calculate();
}
void COperations1Dlg::OnDivision()
{
Calculate();
}
13. From the ResourceView tab of the Workspace, display the dialog box
and check (put a check mark on) the Group check box of the Addition
radio button.
3.4.6 Check Box
A check box is a Windows control that allows the user to set or change
When this empty square is clicked, it gets marked by a check symbol S. These
two states control the check box as checked or unchecked .
Like the radio button, the check box doesn't indicate what it is used for.
Therefore, it is usually accompanied by a label that displays an explicit and
useful string. The label can be positioned on either part of the square box,
depending on the programmer Who implemented it.
Unlike the radio buttons that implement a mutual-exclusive choice, a
check box can appear by itself or in a group. When a check box appears in a
group with other similar controls, it assumes a completely independent
behaviour and it must be implemented as its own entity. This means that
clicking a check box has no influence on the other controls.
101
Check Box Properties
To provide a check box to an application, on the Controls toolbox,
click the Check Box button and click the desired area on the dialog box or
form. If you require more than one check box, you can keep adding them as
you judge necessary.
Like the radio button, a check box is a button with just a different style.
Therefore, it shares the same characteristics as the radio button.
Like the radio button, the accompanying label of the check box can
appear on the left or the right side of the square box. Also, you can control the
horizontal and the vertical alignments of its label using the Horizontal
Alignment or the Vertical Alignment properties.
As a radio button can appear as a regular command button with 3-D
borders, so can a check box. When a check box with the Push-Like property is
up and then clicked, it stays down until it is clicked again, regardless of the
appearance of the other controls. Remember that a check box behaves
independently of the other controls even if it appears in a group.
A check box can be checked or unchecked. The check box as a control
adds a third state for its appearance. Instead of definitely appearing as checked
or unchecked, a check box can appear “half-checked”. This is considered as a
third state. To apply this behavior to a check box, set its Tri-State property to
True or add the BS_3STATE style to it:
102
BS_CHECKBOX value. If you want the control to display or hide a check
mark when it gets clicked, create it with the BS_AUTOCHECKBOX style.
BOOL CCheckBoxes::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
CButton *chkDay[2];
chkDay[0] = new CButton;
chkDay[0]->Create("&Monday", WS_CHILD | WS_VISIBLE |
BS_AUTOCHECKBOX | BS_LEFTTEXT,
CRect(20, 40, 140, 55), this, 0x11);
chkDay[1] = new CButton;
chkDay[1]->Create("&Tuesday", WS_CHILD | WS_VISIBLE |
BS_AUTOCHECKBOX | BS_LEFTTEXT,
CRect(20, 60, 140, 75), this, 0x12);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
As it is mentioned already, that a check box can assume one of three
states: checked, unchecked, or dimmed. If you want to apply one of the states to
such a check box, that is, to programmatically check, uncheck, or dim it, you
can call the CWnd::CheckDlgButton() method whose syntax is:
void CheckDlgButton(int nIDButton, UINT nCheck);
The nIDButton argument is the identifier of the check box whose state
you want to modify. The nCheck argument is the value to apply. It can have
one of the following values:
State Description
BST_UNCHECKED The check mark will be completely removed
BST_CHECKED The button will be checked
BST_INDETERMINATE A dimmed checked mark will appear in
the control’s square. If the Tri-State property is not set or the BS_3STATE
style is not applied to the control, this value will be ignored
To get the current state of a check box, you can call the
CWnd::IsDlgButtonChecked() method. If a check mark appears in the square
box, this method will return 1. If the square box is empty, this method returns
0. If the check box control has the BS_3STATE style, the method can return 2
to indicate that the check mark that appears in the square box is dimmed.
103
Check Box Events
Like all other MFC buttons, the check box can natively send only the
click and the double-click messages. These messages respectively are
BN_CLICKED and BN_DOUBLECLICKED which originate when the user
clicks or double-clicks the control. If you need to, you can use either the events
of the parent window or hand code the messages yourself.
3.4.7 Group Box
A group box is a static control used to create "physical" limits or
sections on a dialog box or a form. It belongs to the family of MFC static
controls.
To create a group box, from the Controls toolbox, click the Group Box
button and click the desired area on the dialog box or the form. Because this
is a CStatic object, if you plan to refer to it in your code, you must change its
ID from IDC_STATIC to something else.
Properties of a Group Box
The most significant property of a group box is probably the text it is
displaying. This is set using the Caption field. If you are programmatically
creating the control, the first argument of the CStatic::Create() method allows
you to set its caption. At run time, to change this text, call the
CWnd::SetWindowText() method.
The text of a group box can be aligned to the left, the center, or the
right sides of its allocated rectangle. This is specified at design time using the
Horizontal Alignment combo box.
Instead of using its own caption, you may want to display a check box
that would validate or invalidate the content of the group box. To do this, after
adding the group box, delete its caption. Then add a Check Box control
where the caption was:
104
Group Box Messages
If you plan to send message from the group box itself (not the controls
inside of it), check the Notify check box or set it to True. This is equivalent to
adding the SS_NOTIFY style when dynamically creating the button.
3.4.8 Tree Control
A tree control is an object that displays a hierarchical list of items
arranged as a physical tree but a little upside down. The items display in a
parent-child format to show those that belong to interrelated categories, such as
parent to child and child to grandchild, etc; or folder to subfolder to file. The
starting item of the tree is sometimes called the root and represents the
beginning of the tree. While most tree list have one root.
Creation of a Tree Control
The concept of a tree list is implemented in the MFC library by the
CTreeCtrl class. To create a tree list on a dialog box or a form, at design time,
on the Controls toolbox, click the Tree Control button and click the desired area
on a dialog box or a form:
Alternatively, to programmatically create a tree list, declare a variable
or a pointer to CTreeCtrl. To initialize the control, call its Create() method.
Here is an example:
1. Create a tree control object. Create in the corresponding dialog
header file private:
CTreeCtrl *TreeSoft;
2. Initialize the object in the constructor
CTree1Dlg::CTree1Dlg(CWnd* pParent /*=NULL*/)
: CDialog(CTree1Dlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CTree1Dlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
TreeSoft = new CTreeCtrl;
}
BOOL CTree1Dlg::OnInitDialog()
{ CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
// TODO: Add extra initialization here
105
TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER
| WS_TABSTOP, CRect(10, 10, 240, 280), this, 0x1221);
return TRUE; // return TRUE unless you set the focus to a
control
}
Tree List Properties
As mentioned already, a tree list is meant to display items in a list
driven by a root and followed by one or more leaves. The items are mainly
made of text. Optionally, to display a check box on the left side of the text, set
the Check Boxes property to True or add the TVS_CHECKBOXES style.
To guide the user with the tree items, the control uses tool tips. If you
will need access to the information stored in tool tips, set the Info Tip property
to True or add the TVS_INFOTIP style. If you do not want to display tool tips,
set the Tool Tips property to False or create it with the TVS_NOTOOLTIPS
style.
When a node has children or leaves, to show this, you may want to
display lines connecting these relationships. To do this at design time, set the
Has Lines property to True.
If you are programmatically creating the control and you want to
display lines among related nodes, add the TVS_HASLINES style.
106
A node that has dependent children can display or hides them. To
display its leaves, a node must be expanded. To hide its leaves, a node must
collapse. These operations must be obvious to the user but something should
indicate whether a node has dependent or not. This can be illustrated by a
button that accompanies such a node. To add these buttons to the control, at
design time, set the Has Buttons property to True. This is equivalent to
dynamically creating a tree list with the TVS_HASBUTTONS style. Unless
you have a reason to do otherwise, it is usually a good idea to combine either
the Has Buttons (or TVS_HASBUTTONS) and the Has Lines (or
TVS_HASLINES) styles:
To show which item is the root, or which items play the roles of roots,
of the tree list, you can display a line from the root(s) to the child(ren). To do
this, at design time, set the Lines at Root property to True or add the
TVS_LINESATROOT style. The line from the root(s) to to the child(ren) can
display only if the control has the Has Lines property set to True or the
TVS_HASLINES style.
When using the list, the user typically selects an item by clicking it. If
you want the mouse cursor to turn into a pointer finger and to underline the
item when the mouse is over the node, set the Track Select property to True or
create the control with the TVS_TRACKSELECT style. Once the mouse
pointer is on top of the desired item, the user can click to select it.
107
When the user clicks another control or another application, the
node that was selected would lose its selection as the tree control would have
lost focus. If you want the tree to always show the selected item even if the
control loses focus, set its Show Selection Always property to True or create
the control with the TVS_SHOWSELALWAYS style.
Besides selecting an item, when a node has children, to expand it, the
user can double-click the node or click its button if available. Simply selecting
the node does not expand it. If you want the selected node to automatically
expand without the user having to double-click or click its button, set its Single
Expand property to True or create it with the TVS_SINGLEEXPAND style.
When the items of a tree control display or when the nodes expand, they
may span beyond the allocated rectangle of the control. When this happens, a
vertical and/or a horizontal scroll bars may automatically display. This is
because, by default, the Scroll property is set to True. If you do not want any
scroll bar, set the Scroll property to False or create the control with the style
TVS_NOSCROLL.
Another operation the user can perform on a node consists of changing
its text. If you want to allow this, set the control’s Edit Labels to True or add
the styleTVS_EDITLABELS.
A user can be allowed to add items to the list by drag-n-drop operations.
If you want to prevent this, set the Disable Drag Drop property to True or
create the control with the TVS_DISABLEDRAGDROP style.
Tree Controls Methods:
After adding or creating a tree control, you may want to fill it with the
necessary items. Each node of the control is an HTREEITEM object. To
create a new node, call the CTreeCtrl::InsertItem() method. It comes in
various versions. One of them is:
HTREEITEM InsertItem(LPCTSTR lpszItem,
HTREEITEM hParent = TVI_ROOT,
HTREEITEM hInsertAfter = TVI_LAST );
The easiest way to add an item consists of calling the InsertItem()
method with a null-terminated string as argument because this is the only
required argument of this version.
108
Example:
BOOL CTree1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER |
WS_TABSTOP, CRect(10, 10, 240, 280), this, 0x1221);
TreeSoft->InsertItem("Office Production");
return TRUE; // return TRUE unless you set the focus to a control
}
In this case, the item would appear as the root. You can add as many
nodes like that and each would appear as a root:
BOOL CTree1Dlg::OnInitDialog()
{ CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER |
WS_TABSTOP, CRect(10, 10, 240, 280), this, 0x1221);
TreeSoft->InsertItem("Office Production");
TreeSoft->InsertItem("Company Management");
TreeSoft->InsertItem("Software Development");
TreeSoft->InsertItem("Human Interaction");
return TRUE; // return TRUE unless you set the focus to a control
}
When calling this version of the InsertItem() method, if you do not
pass the second argument, the node is created as root. This is because the root
item has an HTREEITEM value of TVI_ROOT, which is passed as default.
You can also pass the second argument as NULL, which would produce the
same effect.
The InsertItem() method returns an HTREEITEM value. You can use
this value as a parent to a leaf item. This is done by passing it as the second
argument when creating a leaf. Here is an example:
BOOL CTree1Dlg::OnInitDialog()
109
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
TreeSoft->Create(WS_CHILD | WS_VISIBLE | WS_BORDER |
WS_TABSTOP | TVS_HASLINES | TVS_HASBUTTONS |
TVS_LINESATROOT | TVS_SINGLEEXPAND |
TVS_SHOWSELALWAYS | TVS_TRACKSELECT,
CRect(10, 10, 200, 240), this, 0x1221);
HTREEITEM hTree, hCompany;
hTree = TreeSoft->InsertItem("Software Production", TVI_ROOT);
hCompany = TreeSoft->InsertItem("Microsoft", hTree);
TreeSoft->InsertItem("Office", hCompany);
TreeSoft->InsertItem("Visual Studio", hCompany);
TreeSoft->InsertItem("Servers", hCompany);
hCompany = TreeSoft->InsertItem("Jasc", hTree);
TreeSoft->InsertItem("Paint Shop Pro", hCompany);
TreeSoft->InsertItem("Animation Shop", hCompany);
hCompany = TreeSoft->InsertItem("Lotus", hTree);
TreeSoft->InsertItem("Notes", hCompany);
TreeSoft->InsertItem("Smart Office", hCompany);
hCompany = TreeSoft->InsertItem("Macromedia", hTree);
TreeSoft->InsertItem("Flash", hCompany);
return TRUE;
}
110
Fig 3.11 – Tree control Example
When using the InsertItem() method as we have done so far, the
items are added in the order of their appearance. Besides creating new nodes,
the InsertItem() method also allows you to control the order in which to insert
the new item. The new leaf can be added as the first or the last child of a node.
To do this, pass a third argument to this version of the InsertItem() method
and give it the TVI_FIRST to be the first child or TVI_LAST to be the last
child of the current parent node.
}
Tree Control Messages:
Most messages of the tree controls are notification messages that are
sent to its parent window. For example, the NM_CLICK message is sent to the
dialog box or the form, that acts as the parent, that the tree control has been
clicked. If the click was done with the right mouse button, the NM_RCLICK
message is sent instead. In the same way, if the user double-clicks the control
an NM_DBLCLK message is sent. If the user double-clicked with the right
mouse button, the NM_CDBLCLK message is sent.As mentioned already, the
user has the ability to expand a node that has at least one child. When the user
initiates an action that would expand a node, the tree control sends a
TVN_ITEMEXPANDING. After the item has expanded, the control sends the
TVN_ITEMEXPANDED message.
3.4.9 List Box
A list box displays a list of items, such as filenames, that the user can
view and select.
In a single-selection list box, the user can select only one item. In a
multiple-selection list box, a range of items can be selected. When the user
selects an item, it is highlighted and the list box sends a notification message to
the parent window.
111
You can create a list box either from a dialog template or directly in
your code. To create it directly, construct the CListBox object, then call the
Create member function to create the Windows list-box control and attach it to
the CListBox object. To use a list box in a dialog template, declare a list-box
variable in your dialog box class, then use DDX_Control in your dialog box
class's DoDataExchange function to connect the member variable to the
control. (this is done for you automatically when you add a control variable to
your dialog box class.)
Construction can be a one-step process in a class derived from
CListBox. Write a constructor for the derived class and call Create from
within the constructor.
If you want to handle Windows notification messages sent by a list box
to its parent (usually a class derived from CDialog), add a message-map entry
and message-handler member function to the parent class for each message.
Each message-map entry takes the following form:
ON_Notification( id, memberFxn )
where id specifies the child window ID of the list-box control sending
the notification and memberFxn is the name of the parent member function you
have written to handle the notification.
The parent's function prototype is as follows:
afx_msg void memberFxn( );
Following is a list of potential message-map entries and a description
of the cases in which they would be sent to the parent:
ON_LBN_DBLCLK The user double-clicks a string in a list box.
Only a list box that has the LBS_NOTIFY style will send this
notification message.
ON_LBN_ERRSPACE The list box cannot allocate enough memory
to meet the request.
ON_LBN_KILLFOCUS The list box is losing the input focus.
ON_LBN_SELCANCEL The current list-box selection is canceled.
This message is only sent when a list box has the LBS_NOTIFY style.
ON_LBN_SELCHANGE The selection in the list box has changed.
This notification is not sent if the selection is changed by the
CListBox::SetCurSel member function. This notification applies only to
a list box that has the LBS_NOTIFY style. The LBN_SELCHANGE
notification message is sent for a multiple-selection list box whenever
the user presses an arrow key, even if the selection does not change.
ON_LBN_SETFOCUS The list box is receiving the input focus.
ON_WM_CHARTOITEM An owner-draw list box that has no
strings receives a WM_CHAR message.
112
ON_WM_VKEYTOITEM A list box with the
LBS_WANTKEYBOARDINPUT style receives a WM_KEYDOWN
message.
Construction
Initialization
Create Creates the Windows list box and attaches it to the CListBox
object.
InitStorage Preallocates blocks of memory for list box items and strings.
General Operations
113
GetTextLen Returns the length in bytes of a list-box item.
GetTopIndex Returns the index of the first visible string in a list box.
SetHorizontalExtent Sets the width in pixels that a list box can be scrolled
horizontally.
SetItemData Sets the 32-bit value associated with the list-box item.
Single-Selection Operations
Multiple-Selection Operations
GetCaretIndex Determines the index of the item that has the focus
rectangle in a multiple-selection list box.
114
GetSelItems Returns the indices of the strings currently selected in a
list box.
SetCaretIndex Sets the focus rectangle to the item at the specified index
in a multiple-selection list box.
String Operations
115
Example :
To create a list box, you can use the List Box button from the
Controls toolbox.
Example:
1. Start Microsoft Visual C++
2. On the main menu, click File -> New.
3. Decide to create a Dialog Based application called ListOfCountries with
a title as List of Countries
4. While designing the dialog box, place a List Box control on it. Change
the identifier of the list box to IDC_LIST_COUNTRIES
5. Double-click IDC_LISTCOUNTRIES to Add a Variable
6. Set the Member Variable Name to m_ListCountries
7. In the Category combo box, select Control
116
Fig 3.13 – Member Variable window
8. Click OK
Adding Items to a List Box
In the OnInitDialog() function of the dialog box, initialize the list box as
follows:
// TODO: Add extra initialization here
m_ListCountries.AddString("Afghanistan");
Select an Item Using its Position
To set the 4th item in the list box as selected, under the last AddString()
function in the OnInitDialog, add the following line.
m_ListCountries.SetCurSel(3);
Add an Item to a Specific Position in the List
void CListOfCountriesDlg::OnBtnInsert3()
{
UpdateData();
m_ListCountries.InsertString(2, m_Insert3);
UpdateData(FALSE);
}
Delete an Item in the List Using its Position - Item No. 5
m_ListCountries.DeleteString(4);
117
Delete the Selected Item on the List
m_ListCountries.DeleteString(m_ListCountries.GetCurSel());
Delete/Clear the Whole List
m_ListCountries.ResetContent();
Get the Number of Items in the List
m_ListCount = m_ListCountries.GetCount();
3.4.10 Slider Control
A slider is a Windows control equipped with a small bar, also called a
thumb, that slides along a visible line. There are two types of sliders: horizontal
and vertical:
To use the slider control, the user can drag the thumb in one of two
directions. If the slider is horizontal, the user can drag the thumb left or right.
The thumb of a vertical slider can be dragged up or down. This changes the
position of the thumb. The user can also click the desired position along the line
to place the thumb at the desired location. Alternatively, when the slider has
focus, the user can also use the arrow keys of the keyboard to move the thumb.
A slider is configured with a set of values from a minimum to a
maximum. Therefore, the user can make a selection included in that range.
Optionally, a slider can be equipped with small indicators called ticks:
Slider Properties:
After placing a slider control on a form or other host, by default, its
assumes a horizontal direction. If you want a vertical slider, change the value of
the Orientation property. If you are dynamically creating the control, its
default orientation would be horizontal, whose style is TBS_HORZ. If you
want a vertical slider, apply the TBS_VERT style:
The thumb of a slider can assume one of three shapes. By default, it
appears as a rectangular box. Alternatively, you can convert one of its shorter
borders to appear as an arrow. The shape of the thumb is controlled at design
time by the Point property. Its default value is Both, which gives it a
rectangular shape. You can get this same shape by omitting or adding the
TBS_BOTH value.
The ticks are positioned on the side the thumb is pointing. If the slider is
created with the Both value for the Point property or the TBS_BOTH style,
the ticks would appear on both sides the thumb.
The thumb of a slider is used to scroll from one minimum value to
another. The range of these extreme values can be divided in regular increments
that can further guide the user with value selection. To display where these
increments are set, at design time, set the Auto Ticks property to True or add
the TBS_AUTOTICKS style to a dynamic slider.
While the slider control is selected on the dialog box, on the Properties
window, change its ID to IDC_SLIDER
118
Check its Auto Ticks check box or set it to True
Check its Tick Marks check box or set it to True
Add a CSliderCtrl Control variable for the slider and name it
m_CarSlider
Slider Methods
The slider control is based on the CSliderCtrl class. Therefore, we saw
that we can dynamically create a slider by declaring pointer to CSliderCtrl and
call its Create() method to initialize it.
A slider is a control that provides a range of values between which the
user can navigate using the control’s thumb or by clicking on the slider’s line.
Usually, the first aspect you may need to configure on your control is to specify
its limit values. To specify the minimum value of a slider control, you can call
the CSliderCtrl::SetRangeMin() method.
Its syntax is:
void SetRangeMin(int nMin, BOOL bRedraw = FALSE);
The nMin value is the new minimum value that the slider can assume.
The control is typically redrawn once the new value has been set. If you don't
want the control to be redrawn, pass a second argument with the FALSE value.
If the lowest value of the control has already been set and you want to find out
what that value is, you can call the CSliderCtrl::GetRangeMin() method. Its
syntax is:
int GetRangeMin() const;
This method simply returns the lowest value that the slider can assume
when the user has dragged the thumb to the extreme left or bottom.
To set the highest value of a slider control, you can call the
SliderCtrl::SetRangeMax() method.
Its syntax is:
void SetRangeMax(int nMax, BOOL bRedraw = FALSE);
The nMax argument holds the new maximum value for the control.
If the maximum value of the control had previously been set, you can find it out
by calling the SliderCtrl::GetRangeMax() method. Its syntax is:
int GetRangeMax() const;
This method returns the highest value that the slider control can have.
To set both the minimum and the maximum values of the slider with one line of
code, you can call the CSliderCtrl::SetRange() method.
Its syntax is:
void SetRange(int nMin, int nMax, BOOL bRedraw = FALSE);
The nMin and the nMax arguments hold the lowest and the highest respective
values of the control.
119
At startup or at any time, you can set a specific position for the thumb.
This can be done by calling the CSliderCtrl::SetPos() method. Its syntax is:
void SetPos(int nPos);
The nPos argument holds the new position of the slider
When the position of the thumb has change and you want to find out what it is,
call the CSliderCtrl::GetPos() method whose syntax is:
int GetPos() const;
If the slider control was specified to let the user select a range, you can
define your own selected range at any time by callin the
CSliderCtrl::SetSelection() method. Its syntax is:
void SetSelection(int nMin, int nMax);
When calling this method, make sure you specify the nMin and the
nMax values so that this nMin is greater than the minimum value of the slider
and this nMax is less than the highest possible value of the slider.
Furthermore, the value of this nMin must be less than that of nMax. This
relationshipd can be illustrated as follows:
Minimum <= nMin < nMax <= Maximum
If a selected range has been performed on the slider, if you want to get
the minimum and the maximum values of the selection, you can call the
CSliderCtrl::GetSelection() method whose syntax is:
void GetSelection(int& nMin, int& nMax) const;
This method returns two values, the minimum as nMin and the maximum as
nMax.If the slider control is configure to displays ticks, you can specify their
frequncy with a call to the CSliderCtrl::SetTicFreq() method. Its syntax is:
void SetTicFreq(int nFreq);
Slider Events:
On its own, the slider controls can send three notification messages:
The NM_OUTOFMEMORY message is sent when the slider has run
out of memory and could not complete a task
The NM_RELEASECAPTURE message is sent when the user releases
the mouse on the slider
The NM_CUSTOMDRAW message is used if you want to draw
something on the slider or you want to customize the appearance of the
slider beyond what Visual C++ proposes
For its functionality, the slider highly relies on its parent. When the user
clicks the thumb or any part of the slider, which causes it to slide, a scroll event
is fired. If the slider is horizontal, the CWnd::OnHScroll() event is sent. If the
slider is vertical, the CWnd::OnVScroll() event is sent.
120
3.4.11 Progress Bar Control
The Progress control is used to display the evolution of an activity,
especially for a long operation. Like a label control, a progress control is used
only to display information to the user who cannot directly change it.
Progress Bar Properties:
To create a progress control, on the Controls toolbox, you can click the
Progress button and click the desired area on the parent window. The
progress control is based on the CProgressCtrl class which can help you
dynamically create the control.
After adding a progress control to a host, it assumes a horizontal
orientation by default. If you want the progress control to be vertical, check its
Vertical property or set it to True. If you are dynamically creating the control
and you want it vertical, add the PBS_VERTICAL style to it.
A progress bar displays regular small rectangles inside a longer or taller
rectangle. This outside rectangle serves as their border. If you do not want the
border that delimits the control, uncheck its default checked Border property or
set it to False. The small rectangles appear distinct from one another. If you do
not want the small rectangles visible, you can create a smooth progress bar by
checking the Smooth property or setting it to True. This is equivalent to adding
the PBS_SMOOTH style.
Progress Control Methods and Events:
We mentioned already, an MFC progress bar is based on the
CProgressCtrl class. Therefore, to dynamically create a progress bar, you can
declare a variable or a pointer to CProgressCtrl using its constructor. To
initialize it, call its Create() method and set the necessary characteristics. Here
is an example:
BOOL CDlgProgress1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); SetIcon(m_hIcon, FALSE);
CProgressCtrl *Progress = new CProgressCtrl;
Progress->Create(WS_CHILD | WS_VISIBLE, CRect(10, 10, 288,
35), this,0x16);
return TRUE; }
To express its evolution, a progress bar uses values from a minimum to
a maximum. These limit values are set using the CProgressCtrl::SetRange()
or the CProgressCtrl::SetRange32() methods. Their syntaxes are:
void SetRange(short nLower, short nUpper);
void SetRange32(int nLower, int nUpper);
121
The nLower argument sets the minimum value for the control. The
nUpper argument is the maximum value of the control. Here is an example:
BOOL CDlgProgress1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); SetIcon(m_hIcon, FALSE);
CProgressCtrl *Progress = new CProgressCtrl;
Progress->Create(WS_CHILD | WS_VISIBLE, CRect(10, 10,
288, 35), this,0x16);
Progress->SetRange(1, 100);
return TRUE; }
If the range of values has already been set and you want to find it out,
you can call the CProgressCtrl::GetRange() method. Its syntax is:
void GetRange(int& nLower, int& nUpper);
This member function returns two values: nLower is the current
minimum value of the control while nUpper is returned as its maximum value.
Once a progress control has been created and when it comes up, it
assumes its minimum value. While the control is working, it keeps changing its
value by stepping to the next value. By default, its next value is set to 10. If you
want to specify a different incremental value, call the
CProgressCtrl::SetStep() method whose syntax is:
int SetStep(int nStep);
The nStep argument is the value set to increment the position of the
progress control. Once this value is set, when the control is progressing, it
increments its value by that value to get to the next step. If you want to
explicitly ask it to step to the next incremental value, call the
CProgressCtrl::StepIt() method. Its syntax is:
int StepIt( );
Although the user cannot directly modify it, you can change the value of
a progress bar by calling the CProgressCtrl::SetPos() method whose syntax
is:
int SetPos(int nPos);
This method can be called either to set the initial value of the control or
to simply change it at any time. Here is an example:
BOOL CDlgProgress1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
122
SetIcon(m_hIcon, TRUE); SetIcon(m_hIcon, FALSE);
CProgressCtrl *Progress = new CProgressCtrl;
Progress->Create(WS_CHILD | WS_VISIBLE, CRect(10, 10, 288,
35), this,0x16);
Progress->SetRange(1, 100);
Progress->SetPos(38);
return TRUE}
While the control is working, if you want to find out the value it is
holding, you can call the CProgressCtrl::GetPos() method. Its syntax is:
int GetPos( );
This method returns the current position of the progress control.
3.4.12 Image List
An image list, represented by class CImageList, is a collection of same-
sized images, each of which can be referred to by its index. Image lists are used
to efficiently manage large sets of icons or bitmaps. Image lists are not
themselves controls since they are not windows; however, they are used with
several different types of controls, including list controls (CListCtrl), tree
controls (CTreeCtrl), and tab controls (CTabCtrl).
Types of Image Lists :
There are two types of image lists (CImageList): nonmasked and
masked. A "nonmasked image list" consists of a color bitmap that contains one
or more images. A "masked image list" consists of two bitmaps of equal size.
The first is a color bitmap that contains the images, and the second is a
monochrome bitmap that contains a series of masks — one for each image in
the first bitmap.
ImageList Functions:
1. The Replace member function replaces an image in an image list
(CImageList) with a new image.
2. The SetImageCount function dynamically changes the number of
images stored in the image list. If you increase the size of the image list,
call Replace to add images to the new image slots. If you decrease the
size of the image list, the images beyond the new size are freed.
3. The Remove member function removes an image from an image list.
The Copy member function can copy or swap images within an image
list. This function allows you to indicate whether the source image
should be copied to the destination index or the source and destination
images should be swapped.
4. You can write the image information to an archive by calling the Write
member function, and read it back by calling the Read member
function.
123
5. Use the SetBkColor member function to set the background color of
the image list to the same color as the destination.
6. The GetImageInfo member function fills an IMAGEINFO structure
with information about a single image, including the handles of the
image and mask bitmaps, the number of color planes and bits per pixel,
and the bounding rectangle of the image within the image bitmap.
7. The GetImageCount member function retrieves the number of images in
an image list.
8. You can create an icon based on an image and mask in an image list by
using the ExtractIcon member function. The function returns the handle
of the new icon.
To make Windows controls available to your users, you will add them
to their host object, which can be a dialog box or a form. To do this, you mostly
click the desired control from the Controls toolbox and click the desired area on
the host. You can keep adding controls on the dialog box as necessary.
If you want to add a control over and over again, press and hold Ctrl.
Then click the control on the Controls toolbox. Then click in the desired area
on the host. Every time you click, the control would be added to the form or
dialog box. Once you have added enough controls, click the control again on
the Controls toolbox to deselect it. You can also press Esc.
You cannot select more than one control to add on a host.
3.5 COMMON DIALOG CONTROLS
Microsoft Windows provides a series of objects called Common Dialog
boxes. One of them is intended for file processing. The beauty of these dialog
boxes is that they are highly configured to handle their intended job but you can
still customize them as you see fit.
The File Dialog box is a control used to open or save a file. To use a
File Dialog, you can first declare a CFileDialog variable using its constructor
whose syntax is:
CFileDialog(BOOL bOpenFileDialog,
LPCTSTR lpszDefExt = NULL,
LPCTSTR lpszFileName = NULL,
DWORD dwFlags = OFN_HIDEREADONLY |
FN_OVERWRITEPROMPT, LPCTSTR lpszFilter = NULL,
CWnd* pParentWnd = NULL );
The CFileDialog constructor requires one argument: the
bOpenFileDialog.
The second argument, lpszDefExt, is the default extension that should
be used or applied on the file.
The dwFlags parameter specifies the options to use on the dialog box.
124
The lpszFilter string specifies the types of files that will be dealt with.
The pParentWnd parameter is a pointer to the parent of the dialog box,
if the dialog box has one.
File Saving:
One of the operations you can allow a user to perform on a file is to
save it, either after creating it or after saving. If you want to save a file, pass the
first argument of the CFileDialog constructor as FALSE.
File Opening:
As opposed to saving a file, you can allow the user to open one. To
create a File Dialog box that the user can use to open a file, pass the first
argument of the CFileDialog constructor as TRUE.
File Dialog Properties:
The only member variable that the File Dialog has is called m_ofn. It is an
object derived from a Win32 class (or structure) called OPENFILENAME.
The OPENFILENAME class is defined as follows:
typedef struct tagOFN {
DWORD lStructSize;
HWND hwndOwner;
HINSTANCE hInstance;
LPCTSTR lpstrFilter;
LPTSTR lpstrCustomFilter;
DWORD nMaxCustFilter;
DWORD nFilterIndex;
LPTSTR lpstrFile;
DWORD nMaxFile;
LPTSTR lpstrFileTitle;
DWORD nMaxFileTitle;
LPCTSTR lpstrInitialDir;
LPCTSTR lpstrTitle;
DWORD Flags;
WORD nFileOffset;
WORD nFileExtension;
LPCTSTR lpstrDefExt;
LPARAM lCustData;
LPOFNHOOKPROC lpfnHook;
LPCTSTR lpTemplateName;
125
#if (_WIN32_WINNT >= 0x0500)
void * pvReserved;
DWORD dwReserved;
DWORD FlagsEx;
#endif // (_WIN32_WINNT >= 0x0500)
} OPENFILENAME, *LPOPENFILENAME;
File Dialog Operations:
In order to use a File Dialog box, the user must open it. This can be done by
calling the CFileDialog::DoModal() method. When it comes up, the File
Dialog displays two buttons regularly available on a normal dialog box. If the
file is being opened, the buttons are Open and Cancel. If the user is saving a
file, the buttons are Save and Cancel. After using the dialog box, either to open
or to save a file, the user can click Open/Save or Cancel. If the user clicks Open
or Save, the dialog box is (partly) equipped to validate the operation. For
example, if the user clicks Open, the dialog box is configured to make sure that
the user selected a file. If the user clicks Save, he or she should have given a
name to the file. To dismiss the dialog box without continuing with the
intended operation, the user can click Cancel. If the user clicks Cancel, the
dialog box throws a CommDlgExtendedError.
After displaying the File Dialog box, in other to effectively perform an
intended operation, the user must provide a name for the file. To find out what
name the user provided, you can call the CFileDialog::GetFileName() method.
Its syntax is:
CString GetFileName( ) const;
A file name is indeed made of various sections. In the strict sense, the
file name is a long string that starts from its drive all the way to its "normal"
name. This is also referred to as its path. To get the path of the being dealt with,
you can call the CFileDialog::GetPathName() method. Its syntax is
CString GetPathName( ) const;
In the traditional sense, the name of a file ends with 2, 3, or 4 characters known
as its extension. For example, the extension of a Microsoft Word file is doc.
The extension of a Perl file is pl. After the user has dealt with a file or while
dealing with it, to find out the extension of that file, you can call the
CFileDialog::GetFileExt() method. Its syntax is: CString GetFileExt( )
const;
Example
1. Create a New Dialog Based application named FileProc.
2. Place an Edit Control and Open and Save button
3. Include the following segments to perform file operations
void CFileProc1Dlg::OnSaveBtn()
126
{
// TODO: Add your control notification handler code here
this->UpdateData();
CFile f;
char strFilter[] = { "BCR Files (*.bcr)|*.bcr|All Files (*.*)|*.*||" };
CFileDialog FileDlg(FALSE, ".bcr", NULL, 0, strFilter);
if( FileDlg.DoModal() == IDOK )
{
f.Open(FileDlg.GetFileName(), CFile::modeCreate |
CFile::modeWrite);
CArchive ar(&f, CArchive::store);
ar << m_Make << m_Model << m_Year << m_Mileage << m_Owner;
ar.Close();
}
else
return;
f.Close();
}
void CFileProc1Dlg::OnOpenBtn()
{
// TODO: Add your control notification handler code here
this->UpdateData();
CFile f;
char strFilter[] = { "BCR Files (*.bcr)|*.bcr|All Files (*.*)|*.*||" };
CFileDialog FileDlg(TRUE, ".bcr", NULL, 0, strFilter);
if( FileDlg.DoModal() == IDOK )
{
if( f.Open(FileDlg.GetFileName(), CFile::modeRead) == FALSE )
return;
CArchive ar(&f, CArchive::load);
ar >> m_Make >> m_Model >> m_Year >> m_Mileage >> m_Owner;
ar.Close();
}
else
127
return;
f.Close();
this->UpdateData(FALSE);
}
CColorDialog Control:
A CColorDialog object is a dialog box with a list of colors that are
defined for the display system. The user can select or create a particular color
from the list, which is then reported back to the application when the dialog box
exits.
To construct a CColorDialog object, use the provided constructor or
derive a new class and use your own custom constructor.
Once the dialog box has been constructed, you can set or modify any
values in the m_cc structure to initialize the values of the dialog box's controls.
The m_cc structure is of type CHOOSECOLOR. After initializing the dialog
box's controls, call the DoModal member function to display the dialog box
and allow the user to select a color. DoModal returns the user's selection of
either the dialog box's OK (IDOK) or Cancel (IDCANCEL) button.
If DoModal returns IDOK, you can use one of CColorDialog's
member functions to retrieve the information input by the user. You can use the
Windows CommDlgExtendedError function to determine whether an error
occurred during initialization of the dialog box and to learn more about the
error. CColorDialog relies on the COMMDLG.DLL file that ships with
Windows versions 3.1 and later. To customize the dialog box, derive a class
from CColorDialog, provide a custom dialog template, and add a message map
to process the notification messages from the extended controls. Any
unprocessed messages should be passed to the base class.
Example : To dynamically change the border color of a GDI object
void CFiledialogDlg::OnChangeColor()
{
// TODO: Add your control notification handler code here
CColorDialog dlg1;
COLORREF cr;
if(dlg1.DoModal() == IDOK)
{
CPen *rpen;
CClientDC mydc(this);
cr =dlg1.GetColor();
rpen =new CPen(PS_SOLID,3,cr);
mydc.SelectObject(rpen);
128
mydc.Rectangle(100,200,300,400);
}}
FontDialog Control:
A CFontDialog object is a dialog box with a list of fonts that are
currently installed in the system. The user can select a particular font from the
list, and this selection is then reported back to the application. To construct a
CFontDialog object, use the provided constructor or derive a new subclass and
use your own custom constructor. Once a CFontDialog object has been
constructed, you can use the m_cf structure to initialize the values or states of
controls in the dialog box. The m_cf structure is of type CHOOSEFONT. After
initializing the dialog object's controls, call the DoModal member function to
display the dialog box and allow the user to select a font. DoModal returns
whether the user selected the OK (IDOK) or Cancel (IDCANCEL) button.
If DoModal returns IDOK, you can use one of CFontDialog's member
functions to retrieve the information input by the user. You can use the
Windows CommDlgExtendedError function to determine whether an error
occurred during initialization of the dialog box and to learn more about the
error. CFontDialog relies on the COMMDLG.DLL file that ships with
Windows versions 3.1 and later.
To customize the dialog box, derive a class from CFontDialog, provide
a custom dialog template, and add a message-map to process the notification
messages from the extended controls. Any unprocessed messages should be
passed to the base class.
Construction
CFontDialog Constructs a CFontDialog object.
Operations
DoModal Displays the dialog and allows the user to make a selection.
GetCharFormat Retrieves the character formatting of the selected font.
GetColor Returns the color of the selected font.
GetCurrentFont Retrieves the name of the currently selected font.
GetFaceName Returns the face name of the selected font.
GetSize Returns the point size of the selected font.
GetStyleName Returns the style name of the selected font.
GetWeight Returns the weight of the selected font.
IsBold Determines whether the font is bold.
129
IsItalic Determines whether the font is italic.
IsStrikeOut Determines whether the font is displayed with strikeout.
3.5 ACTIVE X
ActiveX is an advanced form of OCX. Active X not only exchanges the
data between the applications but include an idea called the component object
model (COM). COM is a specification that defines a standard binary interface
between object modules. This interface defines a function-calling methodology,
standard structure-based data-passing techniques, and even a few standard
function calls. Using COM means that it doesn’t matter which language you
use to write an application module such as an OCX; the interface for that
module is the same at the binary level.
ActiveX Versus OCX Controls:
ActiveX and OCX controls are totally interchangeable. It is similar to
OCX but ActiveX control has to be able to work with the internet. The Internet
places some special challenges on the programming environment. You don’t
have the luxury of high-speed loading anymore. The size of an OCX becomes a
critical issue when used within the internet environment. Downloading a 60KB
OCX may test a user’s patience—trying to download a 200KB OCX will
probably result in the user stopping the download altogether. ActiveX controls
are small versions of OCXs.
Creating the ActiveX control:
Choose the ActiveX Control Wizard in the New Dialog box and assign
a new project name. In the class Dialog box select the base class needed for
your application. For example if you are going create an activeX control using
the Button Control, select the base class as BUTTON.
130
Fig 3.14 – MFC ActiveX control creation
131
Fig 3.16 - MFC ActiveX control creation- step2
Customize the About dialog box with the entries related to the new control.
Adding Properties and Events:
Two types of properties are available such as i) Stock property ii)
Custom property. A Stock property is the one that the parent class supports by
default. A custom property is the one which we need to add for a new activeX
control. Creating new property is simple. Just click the Add Property Dialog
box, the dialog box will pop up. The External Name Combo box lists all the
stock properties; you can select and add the properties needed. To create the
custom property just type the name of the property in the external name field
and select the data type in the type field. Similarly by clicking the Add Event
procedure the stock events can be selected in the external name field. Add the
necessary code in the events and test the control.
3.7 DATA BASE APPLICATIONS
Visual C++ provides several different options for enabling database
support in your application. The level of database support you choose depends
on the kind of application you’re creating.
None
Selecting this option means that you don’t want any database support.
Even non-database applications often make use of databases to store
configurations settings or other information. Game programs ware well known
132
for their extensive databases and you’ll find that there are few help desk
applications that get by without use of a database.
Header Files Only
This is the best option to choose if you think you’ll need database
support but really aren’t sure about the details. Visual C++ will add the
required header files to your application, but you’ll be required to create the
database classes yourself.
Database View without File Support
There are times when you don’t want the user to do anything
with files outside the ones that you make available. This option tells Visual
C++ to create all the classes required to access the ODBC data source that
you’ve provided, but not to make the menu entries required to open other files.
Database View with File Support
Utility programs will almost always use this option since it gives
the user the most amount of freedom. Not only will your application have
access to the data source you’ve designed into the application, but you can open
external files as well. Of course, the user’s ability to actually use this feature
depends on the capabilities you’ve built into the program itself.
Choosing a Recordset Type
Visual C++ offers several kinds of recordsets that you can use to
customize the way your application works. The fastest way to view these
various options involves speed versus features. The following list tells you
about the recordset options at your disposal.
Snapshot: The snapshot option tells Visual C++ to download the
entire query in one shot. There are three disadvantages to this approach.
First, you won’t see updates as they’re made by other people on the
network, which could mean that you’re basing a decision on old
information. Second, downloading all of these records at one time
means that you’ll pact a heavy burden on the network during the
download. Third, the user will end up waiting while the records are
downloaded, which will mean an increase in calls about slow network
performance. There are two advantages to this approach. First, once the
records are downloaded, the network will see little activity form the
workstation—freeing bandwidth for other requests. Overall, you’ll see
an improvement in network throughput. Second since all of the
requested records are on the user’s machine, the user will actually see
better overall application performance. You’ll probably want to restrict
the snapshot approach to smaller databases and use it for user
information requests rather than data editing sessions.
Dynaset: When using this option, Visual C++ creates an actual
pointer to each record you request. In addition, only the records you
actually need to fill the screen get downloaded from the server. The
133
benefits of this approach are obvious. You’ll see records onscreen
almost immediately. You’ll also see changes other users make to the
database. Finally, other users will see change that you make since the
dynaset gets uploaded to the server as you change records. Just as
obviously, this approach requires almost constant access to the server,
which will reduce overall network throughput and application
performance as well. This is the option of choice for creating
applications where the user will spend most of his or her toe editing
data. It’s also the best choice for large databases because you’ll
download only the information that the user actually needs.
Table: The table approach (Available only when using DAO)
places the contents of the query you made into a temporary table. Not
only does this reduce the amount of information downloaded from the
server, it means that you as the programmer have more flexibility
because you can manipulate the temporary table fields and records
directly.
To add a variable click Add Member Variable dialog box. Notice that
visual C++ has already added a value for you, usually the variable starts with
m_. If the project is a database applications we will get m_pSet-> . m_pSet is a
pointer to the object containing the current database record. If the table contains
the field like Name, rollno and class, then the variables listed in the combo box
will be m_pSet->Name, m_pSet->rollno, m_pSet->class.
Manipulating the Content of a Database:
m_pSet->AddNew() – Adds the Blank record
m_pSet->MoveNext() – Moves the pointer to the next record
m_pSet->MoveFirst() – Moves the pointer to the First record
m_pSet->MovePrev() – Moves the pointer to the previous record
m_pSet->MoveLast() – Moves the pointer to the Last record
m_pSet->Update() – Updates the record in the database
134
NOTES
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
135
UNIT - IV
VISUAL BASIC
4.1 INTRODUCTION
Visual Basic is an event driven programming language. The “Visual”
part refers method used to create the graphical user interface (GUI). Rather than
writing numerous lines of code to describe the appearance and location of
interface elements, you simply drag and drop pre built objects into place on the
screen. The advantage of such an approach was that there were fewer bugs and
lesser surprises. Building prototype became very easy. Once the interface was
developed, the programmers had to fill in the relevant functions.
Visual basic has evolved from the original BASIC language and now
contains several hundred statements, functions, and keywords, many of which
relate directly to the windows GUI. Visual Basic allows professionals to
accomplish anything that can be accomplished using any other windows
programming language.
Where Visual Basic can be used ?
1. To create a small utility for yourself,
2. An application for a department, work group, a large enterprise-wide
system,
3. Distributed applications spanning the globe via the internet.
Visual Basic has all the tools that user need. Beside there are a number
of third party developers who offer utilities for almost any thing under the sun.
4.2 FEATURES OF VISUAL BASIC
Data access features allow you to create databases and front – end
application for most popular database formats, including Microsoft SQL
server and other enterprise-level databases.
Active X™ technologies allow you to use the functionality provided by
other applications, such as Microsoft Word, Microsoft Excel
spreadsheet, and other windows applications. Or can even automate
applications and objects created using the professional or Enterprise
editions of Visual Basic.
Internet capabilities make it easy to provide access to documents and
applications across the internet from within your application. (ActiveX
Documents)
The finished application is a true exe file that uses a run–time dynamic-
link library (DLL) that is freely distributed. (Application Setup Wizard)
Windows became popular because of its easy and intuitive GUI or
Graphical User Interface. Visual Basic helps create applications that will have
the same GUI as windows. This makes it very easy for users to learn how to use
the software. The windows GUI are event driven. You have seen that unless the
136
user initiates an action noting happens. You have to click a button for
something to happen.
A critical look at any application will tell you that it consists of a
programs or procedures that perform various activities. For example, there is
one program that accepts text data entered by the user. There is another
program that verifies the numeric data or validates the data entered by the user.
There is another piece of code that picks up the data from a databases or a file
and displays it. There is another piece of code that locates a picture file and
shows it on the screen. Then there is a routine, which checks the options
selected by the user, another routine to update a file or database and so forth.
The people behind Visual Basic decided to create special routines that would
perform a specific task. Words like routines, procedures, programs were
discarded and they decided to call these special routines with a new name
called controls. Sounds more sophisticated. So you have a control that accepts
data, you have another control that display pictures, yet another control that
helps you draw lines, etc.
4.3 INTEGRATED DEVELOPMENT ENVIRONMENT
The Visual Basic Integrated Development Environment (IDE) consists
of the following elements.
Menu Bar
Context menus
Tool bars
Tool Box
Project explorer window
Properties window
Object browser
Form designer
Code editor window
Form layout window
Immediate locals and watch windows
Menu Bar
Displays the command we use with Visual Basic. In addition to the
standard File, Edit, View, Window and Help menus, menus are provided to
access functions specific to programming such as Project, format or Debug.
Context Menus
Contain shortcuts to frequently performed actions. To open a context
menu, click the right mouse button on the object you are using. The specific list
of shortcuts available from context menus depends on the part of the
environment where you click the right mouse button. When the right mouse
button is clicked on the object the context menu is opened.
137
Tool Bars
Provide quick access to commonly used commands in the programming
environment. You can click a button on the toolbar once to carry out the action
represented by that button. But default, the Standard Toolbar is displayed when
you start Visual Basic.
Tool Box
Tool Box contains the set of tools, which can be used at the design time.
In additions to the default toolbox, layouts by selecting Add Tab from the
context menu and adding controls to the resulting tab.
Project Explorer Window
This window lists the forms and modules in the current project. A
project is the collection of files used to build an application.
Properties Window
Property window lists the characteristics of the selected object. A
property is a characteristic of an object, such as size, caption, font, colour etc.
Object Browser
Lists objects available for use in the project and gives a quick way to
navigate through the code. You can use the Object Browser to explore objects
in Visual Basic and other applications, see what methods and properties are
available for those objects, and paste code procedures into your application.
Form Designer
The form added to the project is designed with the controls available in
the tool box. We can add controls and enhance the control by formatting it.
Each form in the application has its own form designer window.
Code Editor Window
A separate code editor window is created for each form or code module
in the application. The programmer can edit the applications code. The
programmer can change the font size of the code.
Form Layout Window
The Form Layout Windows allow you to position the forms in your
application using a small graphical representation of the screen.
Immediate, Locals, and Watch Windows
These additional windows are provided for debugging the application.
They are only available when the application is running within the IDE.
Font Properties
The Font properties for a Form include the following:
Font Name: Name of the font.
Font Bold: If set to True, the text will be displayed in bold.
138
Font Size : You can set the size of the text in points.
To access the Font property, you can scroll up or down till you reach
that property or you can press Ctrl+Shift+First letter of property. In this case
pressing Ctrl+Shift+f will take you directly to the Font property.
Position Properties
Properties like Left, Top, Height and Width can be set at design time as
well as at runtime to locate the form in the window.
StartUp Position
This property is set at design time, specifies the position of the form at
runtime.
Form Method
Forms have methods that are used in code to control their behaviour.
These methods change the appearance and behaviour of the form at runtime.
Move
The Move method for example, allows the programmer to position the
form at a desired location on the screen.
The syntax of the move method is as follows;
FormName.Move Left, [Top], [Width], [Height]
Options within the square braces are optional.
Graphics Methods
There are other properties for drawing lines, circle, clearing the form for
any drawing object. There are methods like getting the color of point at a
particular location.
Circle : to draw a circle(s).
Line : to draw a line(s).
Pset : to draw a point with a given color at a given location.
Point : returns the color of screen at the given location.
4.4 CONTROLS
In this section, the functionalities of the controls in the tool box are
discussed.
Text Box Control
The Text Box control is used to accept or display the user input like
name, course, age, etc. Editing of the text is permissible in this control. A Text
Box control is also called an edit field.
The Picture Box
A picture Box control can display a graphic or picture from a bitmap,
icon, or metafile, as well as enhanced metafile, JPEG, or GIF files. If the image
is larger than the control, the image will be clipped.
139
Label Box
As in text box the label control is used to display the text at run time.
But the user can not change the text at run time. This box is used to display the
titles, prompts etc.
Option Button
This button allows the user to display multiple choices from which the
user can choose one option.
Frame
It is allowed to have only one set of option buttons to a form. In order to
overcome this limitation, frame control can be used. Each group of control can
be placed on a different frame. The frame control allows creating graphical or
functional grouping controls. To group controls, draw the frame first, and then
draw controls inside the frame.
List Box
The List box control is used to display the list of items from which we can
choose one. The list can be scrolled if it has more items than it can be displayed
at one time.
Combo Box
The user can either choose an item from the list or enter a value in the
text box. The new value entered can be added to the existing data. The list Box
and the combo Box can be used to display the data from a database. The data
control is used in order to access data and to manipulate data in the list box and
combo box.
Data
Data control provides access to databases through controls in the form.
The data bound controls are used to display and access the data in the database.
Timer control
This control is used to activate the automatic alert by fixing the time
interval.
HScrollBar (horizontal scroll bar)
This control is a graphical tool for quickly navigating through a long list
of items or a large amount of information, for indicating the current position on
a scale, or as an input device or indicator of speed or quantity.
VScrollBar (vertical scroll bar)
VScrollBar is a graphical tool quickly navigating through a long list of
items or a large amount of information, for indicating the current position on a
scale, or as an input device or indicator of speed or quantity.
140
Command Button
This control creates a button, and this is used to carry out a command.
The computer performs the task associated with the button by clicking it.
Check Box
The Check Box creates a box, which the user can easily choose to
indicate if something is true or false, or to display multiple choices when the
user can choose more than one.
The Drive, Directory and File List Controls
These controls are used to display the available Drives, Directories and
Files in the system. By selecting a valid drive in the system, the user can see a
hierarchical structure of directories and files in the system.
The Line and Shape Controls
These controls are used to draw lines, squares, circles, etc.
The Image Control
This is very similar to the Picture Box Control. If the stretch property in
this control is set the image will be modified to the size of the control, whereas
in picture control the image is clipped or truncated.
OLE (Object Linking and Embedding)
This control allows linking the program to another object or program.
For example, it is possible to place a Word Pad file in the program directly and
edit it thorough the application. Using OLE it is possible to link Microsoft
Excel, Word or Ms- Paint.
141
Menu bar Tool bar
142
Fig -4.2 – Sample form with controls
4.5 VARIABLES
The various values used during computation are stored in what are
called variables. A variable must have a name. There are some naming
conventions or rules of nomenclature.
Rules to form variables are
i) It can be up to 255 characters long.
ii) First character must be a letter
iii) Must not have an embedded period or a special character
iv) Can have any combination of letters, numerals and underscore.
Valid Variable names:
Baseball
Net_pay1
Invalid Variable names:
1baseball
net&pay
143
4.5.1 Declaring Variables
In order to write a program we need to use variables. Before the
variable is used we need to inform the program that this particular word is a
variable. The process or method of providing this information is called
declaring a variable. Visual Basic, like most programming languages, uses
variables for storing values. Variables in VB are declared using the DIM
statement and the syntax is
Dim variablename [As type]
Example:
Dim TotalBillAmount[As type]
4.5.2 Assignment Statements
Assignment statements are used to assign a value to a variable. =
operator is an assignment operator.
Example:
Intrate = 0.5
The above statement assigns the value 0.5 to the variable Intrate. The variable
name always should on the left hand side of the equal sign and the expression
or value should be on the right side of the equal sign.
Thus the variables declared should be of specific data type, which
depend on the value to be stored on it and the life of the variable, Scope.
4.6 DATA TYPES
Variables must have a name and a data type. The data type of a variable
determines how the bits/bytes representing those values are stored in the
computer’s memory. When the variable is declared the data type also should be
specified. All variables have a data type that determines what kind of data they
store.
Visual Basic has a number of variable types to deal with various
programming requirements. One needs to use different types of variables for
different requirements in order to optimize speed, and memory requirements.
Data types apply to other things besides variables. When you assign a
value to a property, that value has a data type; arguments to functions also have
data types. In fact, just about anything in Visual Basic that involves data also
involves data types.
You can also declare arrays of any of the fundamental types.
Various data types are discussed below.
Integer : A numeric variable, holds numeric values -32,768,to
32,767
Long(Long Integer) : A numeric variable – holds a wider range of integers
than -2 147,483,648 to 2,147,483,647.
144
Single : A numeric variable which holds numbers with decimal
places.
-3.402823E38 to -1.401298E-45 For negative values.
1.401298E-45 to 3.402823E-38 For positive values.
Double : A numeric variable with a wider range than single.
1.79769313486232E308 to - 4.94065645841247E-324 For
negative values, 4.94065645841247E-324 to
1.79769313486232E308
Currency : For holding monetary values.
-922,337,203,685,477,5808 to 922,337,203,685,477,5807.
String : For Holding text or string values.
0 to approximately 2 billion for variable length.
1 to approximately 65,400 for fixed length.
Byte : A numeric variable, holding less than the value 255, 0 to
255
Boolean : For holding True or False values.
Date : For holding Date values inclusive of and between January 1,
100 to December 31, 9999.
Object : For holding references to objects in Visual Basic and other
application, any Object reference.
User–defined : Number required by elements. The range of each element is
the (using Type) same as the range of its data type.
Variant : A general – purpose variable that can hold most other types
of variables values (with number).
Any numeric value up to the range of the Double. With
Character values, it has the same range as for a variable –
length String.
We can see the data types in detail.
Integer
This data type is used to store whole numbers, and cannot be used in
calculations where decimals or fractions are involved. They can store
reasonably large numbers. The integer data type occupies only two bytes of
memory and is quite fast when used in calculations.
Long
It can hold much larger values, as you can see in the table. It occupies
twice as much space as the Integer. It must be used only where the calculations
involve very large numbers, and is much slower than the Integer.
145
Single
This is the equivalent of the Floating-Point number. It can store
fractions and provide precision to a fairly high level. It occupies 4 bytes of
memory space and should be used where very high precision is not a must. For
example if you want the value of say, 400000000 raised to power 50, then you
may not have the exact figure.
Double
This solves the problem of precision that the Single data type lacks. It
occupies 8 bytes of memory space and should be used in applications where the
requirement of precision is very high. This is not advisable for regular
commercial applications as it can be fairly slow compared to the Integer data
type and should be used when you want accuracy in calculations involving
figures beyond the fourth decimal point.
Currency
This data type is used for holding values related to item rate, payroll
details and other financial functions.
Byte
This data type can hold values from 0 to 255. I cannot hold negative
numbers or numbers larger than 255. Assigning negative values beyond 255
will result in a runtime overflow error. The Byte data type occupies only one
byte of memory.
Boolean
This data type accepts only True or False values. Since the default value
for all numeric data types is zero, the default value for a Boolean data type is
also zero. Zero value is interpreted as False and a non–zero value is interpreted
as True. The VB keywords True and False can be used to assign values to the
Boolean data type.
Date
This variable holds date and time data. It can hold time from January 1,
100 to December 31, 9999, and time from 00.00.00(midnight) to 23.59.59 (one
second before midnight) in one second increments. It occupies 8 bytes of
memory. The data is displayed as per the settings in your computer. You can
store it in British format or American format, or any other format that is
available or the Regional Settings on your control panel.
When other numeric data type are converted to Date, values to the left
of the decimal represent date information, while values to the right of the
decimal represent time. Midnight is 0, and midday is 0.5 Negative whole
numbers represent dates before December 30, 1899.
The String Data Type
Probably the most commonly used data type is the string. Every
application has details like Name, Address, Zip Code, Phone number etc. All
146
these are strings, although some of them will consist of numeric data. Declare
the variable with this data type if it will always contain a string and never a
numeric value. You can declare the variable as a variable-length string or a
fixed-length string. By default, a string variable or argument is a variable-
length string; the string grows or shrinks as when the value is assigned.
Dim ItemName As string * 30 \ a fixed-length string
Dim ItemDescription As String \ a Variable-length string
The string ‘ItemName’ is always be 30 characters long. If you assign a
string of fewer than 30 characters, ‘ItemName’ will be padded with enough
trailing spaces to total of 30 characters. If you assign a string that is too long for
the fixed-length string, Visual Basic simply truncates the characters. In order to
remove the trailing spaces while working with fixed-length string, use
functions like Trim and Rtrim.
Object Data Type
In Visual Basic, forms, controls, procedures and record sets, are all
considered as Objects. All programming activity revolves around these objects.
Since VB is an object based programming language, it is very natural to use
Object data types.
An Object variable refers to an object within the application or in some
other application. This object can be a text box or a form or a database.
A variable declared as an object is one that can subsequently be
assigned (using the set statement) to refers to any actual object recognized by
the application.
Dim objDb As database
Set objDb = opendatabase (“C:\test \ stu.mdb”)
A variable declared as an object occupies 4 bytes of storage.
The Variant Data Type
A variant data type is a variable that can change its type freely. It can
accept text, numeric data or byte data easily. If the data type is not mentioned
then the variable is assumed to be the variant data type by default.
Dim VarValue \ Variant by default.
VarValue = “100” \ VarValue contains “100” (a string).
VarValue = VarValue – 70 \ VarValue now contains the numeric value 30.
\ The ‘conversion is done automatically
VarValue = VarValue & “+” \ VarValue now contains the
string “30+”
For example, if you are reading a file and you are not sure if the data is
numeric or text, or if there is a null value, use this data type. The program will
throw up an error if you attempt to perform a mathematical operation or
function on a variant that does not contain a number. For example, you cannot
147
perform any arithmetic operations on the value ‘30+’, even though it contains a
numeric character, because the entire value is not a valid number. Is Numeric
function can be used to check whether the value is numeric or not before using
in any calculations or computation.
To perform concatenation you must make sure that the values in the
variants are string. It is better to use the “&” operator rather than the “+”
operator.
If both of the variants contain numbers, the + operator performs
addition. If both of the variants contain strings, than the + operator performs
string concatenation. However, if one of the values is numeric and the other is a
string, then you have a problem. Visual Basic first attempts to convert the
string into a number. If the conversion is successful, the + operator adds the
two values; if unsuccessful, it generates a type mismatch error.
What makes the variant data type so special is that it can contain values
that the other variables cannot handle. These values are
The Null Value
The Empty Value
The Error Value
The Null Value
Null is commonly used in database application to indicate unknown or
missing data. If you assign Null to a variable of any type other than variant, a
trappable error occurs. Assigning Null to a variant variable doesn’t cause an
error,
You can also assign Null with the Null keyword:
Z = Null
You can use the IsNull function to test if a variant variable contains
Null:
If IsNull (x) Then
Debug . print . . . . . .
End If
You can return Null from any function or procedure with a variant
return value. Variables are not set to Null unless you explicitly assign Null to
them, so if you don’t use Null in your application, you don’t have to write code
that tests for and handle it.
The Error Value
In a variant, Error is a special value used to indicate that an error
condition has occurred in a procedure. An error value is created by converting a
real number using the CVErr function. However, unlike other kinds of errors,
normal application level error handling does not occur. This allows you or the
application itself, to consider an alternative, based on the error value.
148
The Empty Value
A variant variable has the Empty value before it is assigned a value. The
empty value is a special value different from 0, a zero-length string (“”), or the
Null value. You can test for the Empty value with the IsEmpty function:
If IsEmpty (x) Then . . . . . . . .
A variant can be assigned the Empty value using the Empty keyword.
When a variant contains the Empty value, you can use it in expressions, where
it is treated as either 0 or a zero-length string, depending on the expression.
The Empty value disappears as soon as any value (including 0, a zero-
length string, or Null) is assigned to a variant variable.
A variant always takes up 16 bytes, regardless of data stored in it.
Object, string, and arrays are not physically stored in the variant. Four bytes of
the variant are used to hold either an object reference or a pointer to the string
or array. The actual data is stored elsewhere. Based on what has been discussed
above, use the actual data type only when required. It takes up space, it is slow,
and may also cause errors.
4.7 CONSTANTS
Visual basic’s named constant feature allows creating and then using
mnemonic names for values that never changes. Constants are declared similar
to variables. While performing calculations, you will need to work with figures
that are constants. In order to find the circumference of a circle the formula will
be
2*(22/7)*r
where ‘22/7 is “pi” and ‘r’ is the radius of the circle. The value of “pi” can
be represented as 3.14. This number can be assigned to a ‘Constant’ and can be
used in all calculations.
Constants store values like variables, but as the name implies, those
values remain constant throughout the execution of an application. Using
constants can make your code more readable by providing meaningful names
instead of numbers. There are a number of built-in constants in Visual Basic,
but you can also create your own.
Creating Your Own Constants
The syntax for declaring a constant is:
[Public|Private]Const constantname[As type]=expression
Constant name should be a valid name
As Type is the data type.
Expression is the numeric or string value that has to be assigned to the
constant.
The naming rules are the same as those for creating variable names.
149
The following piece of code will help to calculate the circumference of
Circle A.
Const conPi = 3.1415926
Dim IntRad = Val(Text1.Text)
CircumCircleA = 2 * conPi * intRad
Other than the user defined constants there are many intrinsic or system-
defined constants provided by applications and controls.
Scope of a Constant
By declaring a Constant in the declarations section of a form, standard,
or class module, rather than within a procedure, the Constant will be available
to all the procedure in the module. By declaring a Constant in Public
keyword, it is available throughout the application. Declaring a constant in
procedure will be available to that procedure only.
Circular References
Constants can be defined with reference to other constants. Consider the
following:
Public Const conA =ConB*1.414
Public Const conB =conA *2
Since both the constants are available throughout the application, Visual
Basic will generate an error. This method of defining constants where each is
defined in terms of the other is called Circular reference. Visual Basic will not
proceed with the execution of your program till this circular reference is
resolved.
1. A variable in the module cannot have the same name as any
procedure or type defined in the module.
2. A local variable can have the same name as public procedures, types,
or variables defined in other modules. If this variable is accessed from another
module, it must be qualified with the module name.
It is safer to have the names of variables different from procedure
names or controls in other modules.
4.8 CONVERTING DATA TYPE
The values entered through textbox will be stored as a string value.
Suppose if the application is inventory and the rate or qty entered by the user
will be accepted as a String. To process these values has to be converted in to
numeric values. The following table lists the conversion functions.
Conversion Functions Expression
CBool Boolean
CByte Byte
150
CCur Currency
CDate Date
CDbl Double
CInt Integer
CLng Long
CSng single
CStr String
CVar Variant
CVerr Error
4.9 ARRAYS
An array is a set of similar items. All items in an array have the same
name and are identified by an index. Array allows you to refer to a series of
variables by the same name and the location to identify the position.
Syntax
Dim Varname [([subscripts])] as[New] type[,varname…..]
Example:
Dim nums(10)as integer
Dim x(10 to 20) as integer.
In the first case, ‘nums’ is a set of 11 integers.
nums(0) is the first element of the array ‘nums’
nums(10) is the eleventh and the last element of the array.
In the second case, the first element is x(10) of the array ‘x’
The array that we have just declared is a Fixed-Sized array. There are
other types of arrays such as Dynamic arrays and Multidimensional array.
The scope of the array will depend upon the method of declaration
1. To create a local array, use the Private statement in a procedure to
declare the array.
DIM Counters (10) As Integer
2. To create a module-level array, use the Private statement in the
Declarations section of a module to declare the array.
Private Counters(10) As Integer
3. To create a public array, use the Public statement in the Declarations
section of a Form.
151
Public Counters (10) As Integer
In the case of fixed-sized arrays it is compulsory to enter the upper
bound of the array in the parenthesis; the upper bound is the upper limit for the
size of the array.
A declaration such as the following
Private Counters (10) As Integer
will result in an array of 11 elements. To specify the lower bound of an array,
provide it explicitly (as a Long data type) using the To Keyword.:
Dim Counter (1 to 10) as Integer
In the above declaration, the index numbers of Counter range from 1 to
10,
The Lbound is a function that returns the lower bound of an array. The
Ubound returns the upper bound of an array.
Example:
Dim sinarray (24)
X= Lbound(sinarray)
debug.print x
This will display 0 in the debug window.
4.9.1Multi-dimensional arrays
Arrays can have more than one dimension. A table of data will be
represented by a multidimensional array. For example, if you want to record the
sales figures for twelve months for two of the departments in the organization,
you would declare the array as follows
Dim Saleval(11,2)As Integer.
Here the subscripts 11 indicate the months and the subscript 2 indicates
the departments.
This is a two-dimensional array. You can also have three-dimensional
arrays. If you want to record the sales of five products in three departments for
twelve months then you need a three dimensional array.
Dim Saleval (11, 2, 4)As Integer.
Where the subscript 11 indicates months, the subscript 2 indicates the
three departments and 4 indicates the 5 products. Please remember that a
multidimensional array takes up a lot of space.
4.9.2Dynamic Arrays
Dynamic Arrays are used when you do not know the number of
elements for an array. For example, when you are reading a string into an array,
you may want to have the capability of changing the size of the array at run
time.
152
A dynamic array can be resized at any time and this helps you to mange
memory efficiently. For example, you can use a large array for a short time and
then free memory to the system when you are no longer using the array.
Alternatively you can increase the size of the array after having declared a
smaller array.
The ReDim is used in conjunction with the Dim statement while
declaring these arrays. The alternative is to declare an array with the largest
possible size and then ignore array elements you don’t need. However, this
approach, if overused, might cause the operating environment to run low on
memory.
Declaring a Dynamic Array
1. You declare the array as dynamic by giving it an empty dimension list.
Dim DynSalevel ()
2. Use the ReDim statement to allocate the actual number of elements.
ReDim DynSalvel (11,4)
ReDim is an executable statement and can appear only in a procedure. Unlike
the Dim and Static statements it, makes the application carry out an action at
run time. You can use ReDim each time you want to change the upper or lower
bounds of a dimension. You cannot however change the number of dimension.
The rules of syntax for dynamic arrays are the same as they are for fixed
sized arrays. The scoping rules are also the same as they are for other variables.
Example:
Dim Salval( ) As Integer
This statement will create an open-ended array.
ReDim Salval (12,6)
This will create a two dimensional array. The values for the subscripts of the
array can be passed using variables.
The Preserve Keyword
Whenever, the ReDim statement is used the previous array and its
contents are destroyed. Visual Basic resets the values to the empty value (for
Variant arrays), to zero (for numeric arrays), to a zero-length string(for string
arrays), or to Nothing (for arrays of objects.). This is useful when you want to
prepare the array for new data, or when you want to shrink the size of the array
to take up minimal memory. However, if you need to expand or increase the
size of the array ReDim by itself is not good news. In order to allow the array
to ‘grow’ the preserve keyword is used. The statement
ReDim Preserve Saleval (12,9) will not destroy the data that has already
been entered. It will only add the value for the second dimension. In this case
more columns are added to the table.
153
In the case of a single dimension dynamic array, you can enlarge an
array by one element without losing the values of the existing elements, using
Ubound function to refer to the upper bound. The Ubound function can be used
to get the upper bound of the array.
ReDim Preserve DynSaleval (Ubound(DynSaleval) +1)
More on ReDim
Only the upper bound of the last dimension in a multidimensional array
can be changed when you use the Preserve keyword; if you change any of the
other dimensions, or the lower bound of the last dimension, a run-time error
will occur.
Dim DynSaleval (11,2,4) As Integer.
It can be resized using the Preserve keyword as follows
ReDim Preserve SaleVal (11,2,6) AsInteger.
The following statement will return an error
ReDim Preserve SaleVal (15,2,6) As Integer.
You cannot declare an array of one data type and later use ReDim to
change the array to another data type, unless the array is contained in a Variant.
If the array is contained in a Variant, the type of the elements can be changed
using an As type clause, unless you’re using the Preserve keyword, in which
case no changes of data type are permitted.
If you make an array smaller than it was, data in the eliminated
elements will be lost.
The ReDim statement acts as a declarative statement. If the variable it
declares doesn’t exist at the module or procedure level, a new variable will be
created. If another variable with the same name is created later, even in a wider
scope, ReDim will refer to the later variable and will not necessarily cause a
compilation error, even if Option Explicit is in effect. ReDim should not be
used as a declarative statement, but simply for re-dimensioning arrays.
4.10 CONTROL STRUCTURES
1. If condition then [statement] [Else statements]
Which conditionally execute a group of statements, depending on the
value of an expression?
2. for counter = start To end [Step step] [statements] . . . . Next
This repeats a group of statements a specified number of times.
3. do [ {while | Until } condition ] . . . . Loop
which repeats a block of statements while a condition is True or until a
condition becomes True.
4. while condition [statements] Wend
154
which executes a series of statements as long as a given condition is
True.
5. Select Case test expression [case expression list –n [ statements –n] . . . .
End select
which executes one of several groups of statements, depending on the
value of an expression.
Variations of some of the above statements exist, but we will
concentrate on the statements listed.
The For . . . . Next Statement
This structure is used when you want to execute a statement or a block
of statements a certain number of time.
START
SET UPPERLIMIT
PROCESS
INCREMENT
IS
UPPER yes
LIMIT
?
no
CONTINUE
END
Example
For int I = 1 to 10
IntTotal = intTotal +intI
Next int I
This loop will compute the sum of the numbers from 1 to 10.
The statement intTotal = intTotal+1 is performed 10 times.
155
This loop will work as long as the value of intI is more than 1 and less
than 10.
1. The for statement initializes the value of intI as 1. Since 1 is less than
10, the next statement is executed.
2. The statement intTotal = intTotal +1 is executed.
3. The statement Next intI increments the value of intI by 1.
4. The control shifts to the beginning of the loop, where the value of intI is
checked.
5. If the value of intI is more than 10, the loop terminates, else steps 2 to 4
are executed.
Variations
1. The quantum of increments is decided by the [Step step] keyword.
Example:
For intI = 0 to 100 Step 5
the variable intI will assume the value 0, 5, 10, 15,etc.
The code
For intI = 5 to 100 step 5
Debug.print intI
Next intI
will print all the number from 5 to 100 that are divisible by 5.
The Decision Maker ……If
The If conditions…… statement is used when the program has to
perform an instruction or a block of instructions depending upon the value of an
expression. If the expression returns True then a set of statements(s) is
executed. The program may or may not execute any statement(s) if the
expression returns False.
Syntax
If condition Then [the condition must return a True or False]
[statement]
…..
[ElseIf condition-n Then [the condition must return a True or False]
[elseif statements]……
[Else
[else statements]
End If
156
START
STATEMENTS
YES
IS
EXPRESSION
STATEMENTS
?
NO
END
157
START
STATEMENTS
YES
Is
YES STATEMENTS
Expres
sion ?
no
IS YES
EXPRES STATEMENTS
SION ?
no
END
158
The Loop
Do [{While | Until } condition] …..Loop
This structure is used when we want the program to repeat a block of
statements while a condition is True.
Syntax
Do [{While | Until } condition]
[statements]
[Exit Do]
Loop
Example
intI =1
Do While intI < 10
Intsum = intsum + intI
Int I = intI+1
Loop
1. The value of intI is initialized to 1.
2. The exit condition is first checked to see if intI is less than 10. If intI is
less than 10, then the statements in the loop are executed
3. intsum = intsum +1 and intI = intI +1 are excuted.
4. The keyword Loop returns the control to the DoWhile ……..statement,
where the exit condition is checked.
The While Loop
While condition [statements] Wend
This structure executes a series of statement as long as a given condition
is true.
Syntax
While condition
[Statements]
Wend
Example:
Dim intI as Integer
intI =1
While intI < 10
intsum = intsum +1
intI = intI +1
159
Wend
Select case ……..End Select
This method is used when the program has to execute on of several
groups of statements, depending on the value of an expression. This is also
known as multi branch statement.
Syntax
Select Case testexpression
[Case expressionlist-n
[statements-n]] …….
[Case Else
[elsestatements]]
End Select
Example :
Select Case CandidateAge
Case <= 18
MsgBox you are in the Juniors
Case <= 50
MsgBox you are in the Seniors
Case Else
MsgBox you are in the Oldies
End Select
4.11 FUNCTIONS AND PROCEDURES
In this section we can see the steps to create our own function. For
example, suppose you need a random integer between 1 and 10.
choice = Int ((10* Rnd) + 1)
Next, suppose that the same programs need integer between 1 and 40,
between 1 and 100, and so on. Write code as
Choice = Int ((40*Rnd) + 1)
Choice = Int ((100*Rnd) + 1)
Writing a Simple Function:
To add your function open the code window, choose Tools|Add
procedure from the Tools menu, and the Add procedure dialog box will pop up.
Click the function radio button and assign the name then click OK, and a
function template for the form is shown in the code window.
Example:
Public Function RandomRange1To(x) As Integer
160
Randomize
RandomRange1To = Int (x * Rnd) + 1
End function
161
End function
Public Function Postage (Weight As Single) As Currency
//Calculate the cost, in cents, of mailing a first class letter of a
given weight in ounces the rule is .32 for the first ounce and .23 for each
additional ounce or fractional part
If Int(Weight) = Weight Then
Postage = 0.32 + (0.23 * (Weight – 1))
Else
Postage = 0.32 + (0.3 * (Int(Weight)))
End If
End function
4.11.1 USER – DEFINED FUNCTION
Public Function FunctionName (paramter1, paramter2,…..)
Statements
FunctionName = expression
Statements
FunctionName = expression
Statements
Etc.
End Function
where paramter1, paramter2, and so on are variables. As you have seen,
these variables are referred to as the parameters or arguments of the function.
4.12 BUILT-IN FUNCTION
A built-in function is a prepackaged piece of code that accomplishes a
single task. In this section we can see some of the built-in functions.
4.12.1 String Function
Space Function:
We often need the variable with full of spaces or with string of repeated
characters. The function
Space(Numberof spaces) gives the string consisting only of spaces.
The function
String(Number, StringofExpression) gives the string of repeated
characters.
Exanple:
X = String(10,”z”) yields the string of ten z’s.
162
Trim Function:
One of the thing we have to consider is removing the extra spaces in the
string entered. Trim function is used to trim the spaces. Syntax of the function
is
TRIM(String)
LTRIM(string)
RTRIM(string)
Trim function removes the spaces at both the end. Rtrim removes the
spaces at the right end of the string and Ltrim removes the spaces at the left end
of the string.
Example;
str = “ Welcome “
Trim(str) gives you “Welcome”
Rtrim(str) gives you “ Welcome”
And
Ltrim(str) gives the string “Welcome “
Case Conversion Functions:
The case conversion functions are used to convert the cases of the string
from lower to upper and vice versa.
LCase function converts all the characters in a string into lowercase.
UCase function converts all the characters in a string into uppercase.
Example:
givenstr = “testing sentence”
Res1 = UCase(givenstr)
Res2 = LCase(Res1)
Output of above code is Res1 = “TESTING SENTENCE” and res2 is
same as the givenstr.
Finding Length of the String:
Len(str) gives the length of the string str.
Example:
Len(“madam”) will give the result as 5.
InStr function:
InStr ([where to start,] stringsearch, stringtofind)
This function allows the user to find the position of the string
stringtofind in the string stringsearch from the starting position specified by
the parameter.
163
Example:
Phrase = “QuickBasic was Visual Basic’s distant ancestor”
X = InStr (1, phrase, “Basic”)
The value of X is 6 because the string “Basic” occurs in the phrase at
the sixth position. In this case, the optional first position specifies from which
position to start the search. If you leave this entry out, the search automatically
starts from the first position.
The full form of the function is even more powerful and lets you always
make a case-sensitive comparison regardless of the current setting of Option
compare. The syntax is
InStr ([start,] string1, string2, compare]).
Where the compare parameter specifies the type of string comparison. If
you set it to 0 then the comparison is case sensitive regardless of the current
setting of option compare. If you use the built-in constant vbTextCompare, you
get a case-insensitive comparison again, regardless of the setting of Option
compare. Thus,
X = InStr (1, phrase, “basic”, vbTextcompare)
will always give you the value 6.
The InStrRev Function
The InStrRev function, that starts searching from the back end of the
string.
InStrRev (OriginalString, Substring [, start [, compare]])
The Compare parameter is exactly as before.
The Replace Function
For example, suppose you want to change the string “JavaScript is the
Best scripting language” to “VBScript is the best scripting language” use
replace function.
TestString = “JavaScript is the best scripting language”
TestString = Replace (TestString, “JavaScript”, “VBScript”)
Syntax of the full function is
Replace(Expression, Find, Replace With [,start [,count[, compare]])
For example, after VB processes the following code,
TestString = “AAAAAA”
TestString = Replace (TextString, “A”, “Z”, 1, 1)
You would end up with the string “ZAAAAA” since the count
parameter is set to 1.
164
4.12.2 Numeric Functions
The Round Function
Round (expression [, NumberOfDecimalPlace])
Where the optional second parameter allows you to round past the
decimal point. If you leave it off, you get an integer. For example:
Round (3.7) = 4
Round (3.76, 1) = 3.76
Round (3.786, 2) = 3.79
Other Useful Numeric Functions:
Sgn: The sgn function gives you a +1 if what is inside the parentheses
is postive, -1 if negative, and a 0 if it’s zero.
Abs: The Abs function gives the absolute value of whatever is inside
the parentheses. All this function does is to remove minus signs
Abs (-1) =1= Abs(1).
One common use of the absolute value function is Abs(B-A). This gives
the distance between the numbers A and B. For example, suppose
A=3 and B = 4.
Then, Abs (A-B) = Abs (B-A) =1
Sqr: The Sqr function returns the square root of the numeric expression inside
the parentless, which must be non-negative or a run –time error follows.
Exp: The Exp function gives e (e is roughly 2.7182) to the power x,
where e is the base for natural logarithms, and x is the value in the parentheses.
The answer is single precision if x is an integer or is itself a single-precision
number; otherwise, the answer is a double precision number.
Log: The log function gives the natural logarithm of a number. To find
the common log (log to base 10) use
Log10 (x) =Log (x) / Log (10)
Which gives the common logarithm of the value (which must be
positive) inside the parentheses.
Trig Function:
Visual Basic has the built-in trigonometric functions sin(sine), Cos
(cosine), and Tan (tangent). The only problem is that Visual Basic expects the
angle inside the parentheses following the functions to be in radian measure. To
convert from degrees to radians, you need the value of .
The formula is
Radians = degrees* / 180
165
4.12.3 Date Function
The Date function returns a data of the form month –day- year (mm-dd-
yyyy) for the current data. The month and day always use two digits; the year
uses four (for example,
01-01-1999 for 1 january 1999). You can also use this function as a
statement to reset the current date in the system. The least ambiguous way to do
this is by assigning a string to date in one of the following forms,
Date = “mm-dd-yyyy”
Date = “mm/dd/yyyy”
Where mm are numerals between 01 and 12, dd are days between 01
and 31, and yyyy are years between 100 and 9999.
Example of Time
Command Effect
Time = “hh” Set the hour; minutes and seconds are set to 0
Time = “hh:mm” Set the hour and minutes; seconds are set to 0
Time = “hh:mm:ss” Set the hour, minutes, and seconds
You will usually need to know what today’s date is. For this, Visual
Basic has three functions, as summarized in the following table.
Function Description
Now Returns the date and time as stored in the system
clock
Date Returns the current date
166
You can apply the format function to any date expression to display the
information contained in the number. For example, if it is now 10:01 P.M. on
January 1, 1998, the results are as follows:
Form Display
167
The syntax is
Pv (rate, nper, Pmt, fv, due)
The rate is, as usual, the interest rate per period, nper is the total number
of payments made, pmt is the number of the payments made each period. The
fv entry is the future value or case balance you want after you’ve received
(made) the final payment.
Npv this is a net present value function. This function is used, for
example, if you start out by paying money as startup cost but then get money in
succeeding years. The syntax is
NPV (RatePerPeriod, ArrayOf ( ))
You have to fill the array with the appropriate values in the correct
order. For example, the first entry could be a negative number representing
startup cost and the remaining entries a positive number representing value
received. At least one entry must be positive and one entry must be negative.
This function is more general than the PV function because using an array
allows the amounts received or disbursed to change over time.
Rate: This function gives the interest rate per period for an annuity. The
syntax is
Rate (nper, pmt, Pv,fv, due, guess)
Common Functions:
Function Purpose
Abs Finds the absolute value of a number
168
Nper Time to accumulate (disburse) an annuity
169
LTrim Remove spaces from the beginning of a string
170
Hour Tells you the hour a string or number
represents
4.13 FORMS
Visual basic organizes the application in to projects. Each project
comprises of multiple windows and the code that activates the control on the
form is stored with the form as a separate files.
The main characteristic of a Form is the title bar on which the Form's
caption is displayed. On the left end of the title bar is the Control Menu icon.
Clicking this icon opens the Control Menu. Maximize, Minimize and Close
buttons can be found on the right side of the Form. Clicking on these buttons
performs the associated function.
171
A typical application has more than a single Form. When an application
runs the main Form is loaded. By setting the Project properties you can control
which Form is to be displayed in the Start-Up of the application. Following
figure illustrates the Project property window.
Loading and Unloading Forms
In order to load and unload the forms, Load and Unload statements are
used. The Load statement has the following syntax:
Load FormName
and the Unload statement has the following syntax:
Unload FormName
The FormName variable is the name of the Form to be loaded or
unloaded. Unlike the Show method which cares of both loading and displaying
the Form, the load statement doesn't show the Form
Showing and Hiding Forms
Show method is used to Show a Form. If the Form is loaded but
invisible, the Show method is used to bring the Form on Top every other
window. If the Form is not loaded, the Show method loads it and then displays
it.
FormName.Show mode
The FormName variable is the Form's name, and the optional argument
mode determines whether the Form will be Modal or not. It can have one of the
following syntax:
* 0-Modeless (default)
* 1-Modal
Modeless Forms are the normal Forms. Modeless Forms interact with
the user and the user allowed switching to any other Form of the application. If
you do not specify the optional mode argument, by default the mode is set to
modeless.
The Modal Forms takes the total control of the application where user
cannot switch to any other Forms in the application unless the Form is closed.
A modal Form, thus, must have a Close button or some means to close the
Form in order to return to the Form where the Modal Form was loaded.
Hiding Forms
The Hide method is used to hide a Form. The following is the syntax of
the Hide Method.
FormName.Hide
To hide a Form from within its own code, the following code can be used.
Me.Hide
172
You must understand that the Forms that are hidden are not unloaded; they
remains in the memory and can be displayed instantly with the Show Method.
When a Form is hidden, you can still access its properties and code. For
instance, you can change the settings of its Control Properties or call any Public
functions in the Form.
Form Events:
Event procedures are nothing more than lines of programming code that
tells Visual Basic how to respond to a given event.
Click – To respond to a click
Double click – to respond to a double click
Form resize – to respond when the user resizes a form
4.14 PROPERTIES
173
3- Fixed Double
4- Fixed Tool window
5- Sizable Tool Window
Control Box: Active only in the run time. Clicking the box displays the
common window tasks such as minimizing, maximizing, and closing.
Enabled: If it is set to false form can not be activated.
Font: Allows you to choose the fontname, size etc.
Height and Width: Represents the height and width of the form.
4.15 MDI FORMS
An MDI Form acts like a container for the other forms in the
application. Therefore the user can start an application, minimize it and close it
with a single point control. One need not close all the constituent forms. As in
the case of Word, click on the minimize button to minimize all the open
documents.
Most of the control buttons and code for the various forms can be
shared. All function like adding, displaying, sorting records, etc. is commonly
used by most of the forms.
Reduce the number of controls. Common controls can be available with
the MDI form and shared by the other forms.
All activities like data-end operations and updating of records can be
handled from the MDI form.
In short the MDI forms will allow easier organization of the forms in
the application and reduce the amount of code and the number of controls in
your application.
An MDI Application consists of One MDI Parent form, one or more
MDI child form(s) and optionally independent forms and modules.
Creating a simple MDI application
1. Start a new Standard.Exe project.
2. Click on Projects.
3. from the drop-down menu, click on ‘Add MDI Form’
4. A form with a darker color will be displayed. This is the MDI Form.
1. An application can have only one MDI form. If a project already has an
MDI form, the Add MDI form command on the project menu will be
unavailable. If you need to have more than one MDI form for your
application, you will need to rework your design.
2. It can contain only those controls that have an ‘Align property or those
controls that are not visible during runtime. This is because the internal
area of an MDI form is defined by the area not covered by these
174
controls. These are Toolbar, Picture Box, and Data control. The align
property here is related to the alignment of the control on the form.
3. To place other controls on an MDI form, you can draw a picture box on
the form, and then draw other controls inside the picture box. You can
use the print method to display text in picture box on an MDI form, but
not to display text on the MDI form itself.
4. An MDI form object can’t be model.
5. The menu for the child from will be displayed as the menu on the MDI
form when the child form has the focus.
6. You can access the collection of controls on an MDI form using the
controls collection. For example, in order to hide all the controls on an
MDI form you can use code similar to the following:
For Each Control in MDIForm1.controls
Control.visible = False
Next Control
7. The default autoshowchildren property displays the child forms
automatically when they are loaded.
8. The default ScrollBars property will display the scroll bars when the
child forms extend beyond the boundaries of the parent form.
9. The count property of the MDI form tells you the number of controls in
the controls collection.
To create an MDI child Form, select Form1(or add a new form) and set
its MDI child Property to true. It is a standard form with the following
attributes.
1. A child form cannot be moved outside the Parent form’s boundaries.
2. Activation a child form will result in the activation of the parent form.
3. When a child form is minimized, its icon will appear at the bottom of
the workspace of the parent form.
4. When a child form is maximized, it fills the entire area of the parent
form, and its menu will become the menu of the parent form.
5. There can be more than one child form in an application.
6. The icons for MDI parent, child and a standard form are different.
Loading MDI Forms and Child Forms
When you double-click on a word documents on your desktop, the word
program is automatically invoked. The document is the child form, and the
word program is the MDI Parent Form. However, you can start word without
opening a document. Similarly, when you load the form, its parent form (the
MDI form) is automatically loaded and displayed. When you load the MDI
form, however its children are not automatically loaded.
175
You can set the AutoShowChildren property as False, in order to load
MDI child windows as hidden, and leave them hidden until you display them
using the show method. This allows you to complete any background work
before the child form gets the focus.
After having clicked away to create multiple instances of Form1, you
probably feel like a crow sitting on a batch of eggs in order to hatch them. It
does not know which of the eggs belongs to a nightingale and which are its
own. In your case, the problem is in determining which control and which form
has the focus.
User of your MDI application may open, save, and close several child
forms in one session. To control the program better, you should be able to refer
to the active form and maintain state information on child forms. Let us see the
functions and the methods we can use to specify the active child form or
control, load and unload MDI and child forms, and maintain state information
for a child form.
The ActiveForm Property
This property returns the form that is the active window in the
application. If a control in the child form has the focus, it returns the name of
that form.
Syntax
Object.ActiveForm
Example:
ActiveForm.Text1.Text = “This is to test if we have got it right”
Create any number of instances of the child form and then click on the
MDI form. The text string that you have entered will be displayed in the active
form. Select one of the child forms at random and then click on the MDI form
to check out if the ActiveForm property really works.
176
NOTES
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
177
UNIT - V
5.1 EVENTS
5.1.1 Event Driven Programming
Visual Basic programs are built around events. Events are various
things that can happen in a program. This will become clearer when studied in
contrast to procedural programming. In procedural languages, an application
written is executed by checking for the program logically through the program
statements, one after another. For a temporary phase, the control may be
transferred to some other point in a program. While in an event driven
application, the program statements are executed only when a particular event
calls a specific part of the code that is assigned to the event.
Let us consider a TextBox control and a few of its associated events to
understand the concept of event driven programming. The TextBox control
supports various events such as Change, Click, MouseMove and many more
that will be listed in the Properties dropdown list in the code window for the
TextBox control. We will look into a few of them as given below.
The code entered in the Change event fires when there is a change in the
contents of the TextBox
The Click event fires when the TextBox control is clicked.
The MouseMove event fires when the mouse is moved over the
TextBox
Mouse Events:
Visual Basic responds to various mouse events, which are recognized
by most of the controls. The main events are MouseDown, MouseUp and
MouseMove. mouseDown occurs when the user presses any mouse button and
MouseUp occurs when the user releases any mouse button. These events use
the arguments button, Shift, X, Y and they contain information about the
mouse's condition when the button is clicked.
The first argument is an integer called Button. The value of the
argument indicates whether the left, right or middle mouse button was clicked.
The second argument in an integer called shift. The value of this argument
indicates whether the mouse button was clicked simultaneously with the Shift
key, Ctrl key or Alt key. The third and fourth arguments X and Y are the
coordinates of the mouse location at the time the mouse button was clicked. As
the Form_MouseDown( ) is executed automatically whenever the mouse button
is clicked inside the Form's area the X, Y co-ordinates are referenced to the
form.
MouseMove
Visual Basic does not generate a MouseMove event for every pixel the
mouse moves over and a limited number of mouse messages are generated per
second by the operating environment. The following application illustrates how
often the Form_MouseMove ( ) event is executed.
178
Open a new standard EXE project and save the form as
MouseMove.frm and save the Project as MouseMOve.vbp. Place a
CommandButton control and name the caption as Clear and set the name as
cmdClear.
The following code is entered in the cmdClear_Click ( ) and
Form_MouseMove ( ) events respectively.
Private Sub cmdClear_Click()
frmMouseMove.Cls
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X
As Single, Y As Single)
Circle (X, Y), 70
End Sub
The above procedure simply draws small circles at the mouse's current
location using the Circle method. The parameter x, y represent the centre of the
circle, and the second parameter represent the radius of the circle.
Save the application and run. You can notice that when the mouse is
moved inside the Form, circles are drawn along the path of the mouse
movement.
5.1.2 Key Events
The Key press event reports on which ASCII coded key a user is
pressed. This lets you identify what key is pressed like ctrl, alt etc.
Key Up:
This event is called when the key is released.
Key down:
This event is called when the key is pressed.
5.2 MENUS
Menus offer a variety of functionalities to define the application: we can
include sub-menus, checked items, enabled/disabled functions, toolbar icons.
The VB IDE that you are using certainly displays all of these tools, as in the
diagram below.
179
Fig – 5.1 Menu example
The ampersand (&) in the captions (the Caption is the part that will
display in the menu bar, not the name), creates a Hot-key, meaning a function
that can be called from the keyboard using the <Alt> key. Putting an & before a
letter in a caption makes that letter the hot-key for the function; <Alt><F> will
call-up File, <Alt><E> will call-up Edit, and so on. Just make sure that the
same hot-key is not used for 2 functions on the same level.
The other consideration when creating the menu is to give each menu
item a specific name. In this case we use the prefix mnu_ to identify menu
items. These are important because they will be referred to in code and it
should be clear that mnu_exit is the Exit function in the menu whereas cb_exit
is the Exit command button.
180
Caption text box: The name you enter in this box is the one displayed in the
menu.
Name Text Box: Each menu item has a control name. The text entered
in this box is assigned as a name of menu item.
OK and Cancel Buttons: Click OK button to confirm the menu creation,
and click cancel button to cancel the operation.
Index Box: Use the index box if you want to make the menu item as a
part of the control array.
Short cut box:
The box let you add the accelerator keys to your menu items.
The other properties Checked enable you to place the check mark in
front of the menu item. Enable property is checked means the menu can be
activated and if the Visible property is set then the menu is visible else it is
invisible.
5.3 COMMON DIALOG CONTROL
In order to provide standardization in the interface for all windows
compliant applications, Visual Basic has the CommonDialog Control. The
Windows Common Dialog Control allows you to deploy the dialog boxes that
it provides with all its applications. The Common Dialog Control lets you
display the following dialog boxes.
Open A File
Save a File
Set a Color
Set a Font
Print a Document.
Moreover, it does not need any great programming. Simply add the control to
your form and call the method or function that you want. Your application
deals with the user in the same manner as Windows does.
The commondialog control can display the following dialogs, using the
specified methods.
Method Dialog Displayed
ShowOpen Show Open Dialog Box
ShowSave Show SaveAs Dialog Box
ShowColor Show Color Dialog Box
ShowFont Show Font Dialog Box
ShowPrinter Show Print or Print Option Dialog Box
ShowHelp Invokes the Windows Help Engine
181
5.4 RECHTEXTBOX CONTROL
CommonDialog control made our life easier by giving us a simple and
easy way to provide the necessary interface to the user. We were able to create
a small application that would allow the user to create a new file or open an
existing file, add text to it, save it, save the changes and print the contents of the
file as well. We could also make changes to the font size, the color of the text,
etc.
We could not selectively change the font size, color or indentation.
These styles are very necessary if we are going to create our own word
processor. Besides, we may want to add pictures to output text file, or to a
spreadsheet, just to add some styles to the text! In order to allow the user to do
all this, the conventional text box would not fit the bill. The conventional
textbox can hold only plain text. Microsoft provides one such control called the
RichTextBox control. The Rich Text Box control allows the user to enter and
edit text with more advanced formatting features than the conventional
TextBox control.
The RichTextBox control provides a number of properties you can use
to apply formatting to a selected portion of text within the control. Select the
portion of the text to be formatted and apply the necessary changes. You can
make text bold or italic, change the color, and create superscripts and
subscripts. You can also adjust paragraph formatting by setting both left and
right indents, as well as hanging indents.
Start a new project or add a new form to your current project. The
RichTextBox control is not part of the standard toolbox. To add the control
1. Select the Project/Components menu item.
2. Select the Controls tab in the Component box.
3. Double click on the Microsoft Rich Textbox Control item from the list
of components.
4. Close the Components box.
A new component will appear on the toolbox.
Draw the following controls on the form.
One Rich textbox control
Six CommandButton controls(FontStyle, FontColor, Index, FileOpen,
Print and Exit)
Changing the font of the selected text
In the case of the Rich textbox, formatting changes have to be applied to
the text after selecting it. In order to change the font of a portion or all the text
in the rich textbox, select the text and call the font dialog box. Select the font
type and click OK. The selected text will be displayed in the new format. The
code for this is very simple.
commonDialog1.ShowFont
182
//This line will change the font of the selected text.
RichTextBox1.SelFontName = CommonDialog1.FontName
Changing the Color of the Selected Text
To change the color of the selected text or all the text in the rich
textbox, the procedure is similar to that we used for changing the font. The
necessary code is as follows.
CommonDialog1.ShowColor
RichTextBox1.SelColor = CommanDialog1.Color
The Rich Textbox also allows you to indent the text. You can have a left
indent, A right indent or hanging indent.
Sellndent(default is the left indent) specifies the distance between the
left edge of the RichTextBox control and the left edge of the text that is selected
or added. SelRightIndent specifies the distance between the right edge of the
RichTextBox control and the right edge of the text that is selected or added.
Hanging indent is the extra indent given to a line or lines in a paragraph
over above the indent given for the first line of the same paragraph. The
selhangingindent specifies the distance between the left edge of the first line of
text in the selected paragraph, and the left edge of subsequent lines of text in
the same paragraph.
Changing the indent
In order to change the left indent of the selected text you need to
provide the amount of indent required either at runtime or at design time. The
amount of indent has to be given as an integer. The Rich Text box allows you
to add .bmps, .gif and other pictures as part of the document. You can even
introduce hyperlinks to create help files and so on. The Rich Text box allows
you to directly read data from a file and to save the data entered as on .rtf file.
An .rtf file can be read by MS Word.
5.5 INPUT BOXES
Input Boxes are an alternative way of getting information from the user.
Input Box function displays the modal dialog box on the screen. Modality is the
principal advantage of input boxes since the user can not continue their work
unless the user supplies the necessary data. The disadvantages are that the
dimensions of the input box are fixed and lose the flexibility of the text box.
Input boxes have a title bar that you can set. There is also a prompt;
“This shows a sample input box”. There are always two command buttons
labeled OK and Cancel. Finally, there is a text area at the bottom. Visual Basic
always places the focus in this text area when it processes a statement
containing an InputBox function. The simplest syntax for the InputBox
function is
StringVariable = InputBox (promptString)
183
this form uses the name of the project in the title bar of the input box. The full
syntax for the InputBox function is
variableName = InputBox (prompt,[title],[default],[xpos],
[ypos][helpfile], [context])
The prompt parameter is a string or string variable whose value Visual
Basic display in the dialog box. It is limited to roughly 1,024 characters.
The title parameter is optional. If it is omitted then the application name
is used in the title bar.
Default is also optional. This lets you display the default text in the edit
box. If it is omitted the edit box will be empty.
Both Xpos and Ypos is also optional. This is used to specify the
position of the input box on the screen.
Helpfile and context are used together when we have a message
attached to the box.
Example:
x = InputBox("Enter your name", "test input box")
Output of the above statement is
184
Fig 5.4 Message Box –example
The value of symbolic constants for the type of message box is given in
the table.
If the Message Box function is used it should appear on the right hand
side of the expression since it returns the value of the button clicked. In the
example mentioned above if the Yes Button is pressed then Vbyes is returned
else VbNo is returned.
If the statement like MsgBox “testing Message Box” is used then the
output is displayed as
185
5.7 THE FLEX GRID CONTROL
The flex grid control has more than 80 properties, 20 events, and 10
methods. The flex grid control lets you build spreadsheet like features into your
projects or display tabular information neatly and efficiently. This control
displays a rectangular grid of rows and columns at design time. How many
rows and columns you see at design time depends both on the number or rows
and columns you have set and the grid.
The flex grid control is not part of your toolbox, choose
project/components and check off Microsoft Flex Grid Control 6.0 in the dialog
box. Each grid member is usually called a cell. Cells can hold text, bitmaps, or
icons, and you can even have some cells holding text and other holding
graphics. Numbers must be translated back and forth using the right conversion
(Cint, CDbl and so on) and str($) functions or the Variant data type must be
used-as you would do with text boxes. The grid control even includes a built-in
word-wrap feature that you can activate via code or the properties window so
users can enter text more easily.
User can move from cell to cell by using the arrow keys or the mouse;
Visual Basic handles such movement automatically. As the user of your control
moves around the grid, Visual Basic keeps track of what the current cell is as
the values of the Row and Col properties.
Users can work with contiguous groups of cells in the grid, usually
called regions, by clicking a cell and dragging the mouse or by pressing SHIFT
plus an arrow key to select the region. Once a region is selected, code can be
used to analyze or change the contents.
General Properties of the Flex Grid Control
Many properties of the flex grid control are the same as those of other
controls. For example, the Height and Width properties tell you how large the
grid will appear; the Enabled property determines whether the grid will notice
keystrokes or mouse activity. Similarly, if you set the ScrollBar property to a
nonzero value(1 for Horizontal, 2 for Vertical, 3 for both), Visual Basic
automatically adds the appropriate scroll bars when there is information of the
grid that cannot be seen.
Some of the special properties are CellFontBold, CellFontItalic,
CellBackColor, and CellForeColor. As you might expect from the names, these
properties affect the text or color of the current cell.
Cols, Rows: These properties determine the number of rows and columns in
the grid. The default value for each of these properties is 2, but you can reset
them in code or via the properties window, as needed. They must be integers,
and the syntax is
GirdName.Cols=NumOfCols%
GirdName.Rows=NumOf Rows%
You can also add an optional form name. For Example
186
frmDisplay.cols=10
Col, Row These properties (which shouldn’t be confused with cols
and rows!) set or return the row and column for the currently selected cell
inside the grid. These properties are only available at run time. As the user
moves around the grid, the values of these properties change. You then use
their values to determine where inside the grid the user is. By adjusting their
values via code, you can specify the current cell directly. Since both col and
row start out at zero, the top left corner cell has col value 0 and row value 0.
ColPosition, RowPosition
These properties let you move whole rows and columns around in your
grid. The syntax is
GridName.ColPosition(number) [=value]
GridName.RowPosition(number) [=value]
ColWidth, RowHeight
These two properties specify the width of a specific column or height of
a specific row. They can only be set via code. Both are measured in twips. The
syntax is
GirdName.ColWidth(Cols=NumOf%)=Width%
GirdName.RowHeight(Rows=NumOf %)=Height%
Text, TextMatrix: The Text property sets or returns the text inside the current
cell. For example, the following fragment sets up a grid (the control name is the
default-MSFlexGrid1) with four rows and four columns. We add some text to
that cell and then display it on the form.
MSF1exGrid1.Cols = 4 //have four rows
MSF1exGrid1.Rows = 4 //have four columns
MSF1exGrid1.Col = 3
MSF1exGrid1.Row = 3
MSF1exGrid1.Text = “This would go in the button right corner”
MsgBox MSF1exGrid1. Text & “is in cell 3, 3”
MSF1exGrid1.Col = 0
MSF1exGrid1.Row = 0
MsgBox MSF1exGrid1. Text & “is in cell 0, 0”
5.8 DATA GRID
Data Grid is the control attached to data control displays the information
from the attached table.
187
Fig – 5.6 data grid, adodc data control and the property form
From the components click the data grid control and place it in the form
and set the respective properties. Click the ADODC1 and set the properties. To
connect to the database use either connection string or ODBC data source.
Select the table to be connected. Set the property data source of data grid to
adodc control. Once the properties are set, it gets populated automatically with
the data from the recordset object.
188
Fig 5.7 Sample data grid – data populated from Authors table.
5.9 INTRODUCTION TO GRAPHICS
The graphic methods in Visual Basic allow you to control each dot that
appears on the screen. Certain combinations of hardware, software and
monitors can divide the screen into more than 1,000,000 dots and theoretically
choose from a palette of more than 16,777,216 (256 * 256 * 256) colours for
each pixel.
5.9.1 Fundamentals of Graphics
To draw on the screen, from Visual basic the commands are passed to
windows, windows in turn tells the display adapter to how to display the
images. To save a copy of the object in memory set the AutoRedraw property
to true. The effects of setting the AutoRedraw property to true are slightly
different for forms and picture boxes.
For a resizable form, Visual basic saves a copy of the entire form. Thus,
when the form is enlarged no graphics information is lost.
For a picture box, Visual Basic saves an image only as large as the
current size of the box. Nothing new will appear even if the box is
enlarged later.
Thus, drawing to picture boxes requires less memory than drawing to
forms, even if the picture box fills up the form.
189
5.9.2 Screen Scales
The default scale for forma and picture boxes is twips, that is 1.20 of a
printers point and 1/440 of an inch. The default size for a VGA monitor of 14
inch size is 640 x 480 and in twips the size is 7485 x 4425.
Coordinates Location
(0,0) Top left corner
(7485, 0) Top right corner
(0, 4425) Bottom left corner
(7485, 4425) Bottom right corner
(3742, 2212) Roughly the center
Other Screen Scales:
There are other six screen scales. These scales can be set by using the
ScaleMode option. Once you set the scalemode property, the size of the
window can be found using the ScaleHeight and ScaleWidth.
ScaleMode Units
1 Twips
2 Points (72 per inch)
3 Pixels
4 Characters
5 Inches
6 Millimeters
7 Centimeters
Custom Scales:
The screen is normally numbered with (0,0) as the top left corner. This
is obviously inconvenient for drawing tables, charts, graphs and other
mathematical shapes. In mathematics, we use the Cartesian (X-Y) system, with
X measuring from left to right and Y from bottom to top.
You can use the command Scale (-320, 240) – (320, -240) to set up the
new coordinate system with (0,0) at the center of the form. Then the
coordinates specify the four corners are,
(-320, 240)
( 320, 240)
(320, -240)
(-320, -240)
The general syntax of the Scale method is
Scale (LeftX, TopY) – (RightX, BottomY)
190
5.9.3 The Line and Shape Controls
The shape control can be used to display rectangles, squares, ovals and
circles. Using this you can draw the rounded rectangles and rounded squares.
The Line control can be used to draw the lines with various thickness.
Shape:
This determines the type of the shape. There are six possible settings
Setting of the Shape Property Effect
0 rectangle
1 Square
2 Oval
3 Circle
4 Rounded Rectangle
5 Rounded square
The Line Control:
The Line control has 15 properties. The most important property for the
line control at design time is BorderStyle and BorderWidth. BorderWidth
property sets the thickness of the line. The BorderStyle property sets the style
of the line like solid, dashed and so son.
Value of BorderStyle Meaning
0 Transparent
1 Solid
2 Dashed
3 Dotted
4 Dash dot
5 Dash dot dot
6 Inside Solid
191
FIG – 5.8 – EXAMPLE FOR GRAPHIC PRIMITIVES
5.9.4 Graphics Via Code
Instead of drawing shapes at the design time using the methods the
drawings can be carried out using codes.
Colour:
If the colour is not specified, then the Visual Basic uses the foreground
colour for all the graphics methods. There are four ways to specify colours.
The first way is at design time using the palettes that show up in the property
window. The second way is by using the hexadecimal code in the code or at
design time.
The third way us to use the RGB function. The syntax for the function
is RGB(AmountofRed, AmountofGreen, AmountofBlue) where the amount of
color is an integer between 0 to 255. The last method is by using the QBColor
function.
QBColor(colorcode) where colorcode is an integer value between 0 and
15.
192
code Color Code Color
0 Black 8 Gray
1 Blue 9 Light blue
2 Green 10 Light green
3 Cyan 11 Light cyan
4 Red 12 Light red
5 Magenta 13 Light magenta
6 Brown 14 Yellow
7 White 15 High intensity white
Pixel Control:
This control is used to turn on the pixel. The syntax for this method is
PSet(Col, Row) [, ColorCode]
5.9.5 Lines and Boxes
In addition to shape and line controls, Visual Basic provides the
graphic primitives to draw the geometric figures such as lines, boxes, circles,
ellipses and wedges with single statements.
The Line method takes the form
Line (StartCol, StartRow) – (EndCol, EndRow), ColorCode
This method draws the line between the specified coordinates using the color
specified in the colorcode.
Visual Basic keeps track of where it stopped plotting. This location is
usually called the last point referenced(LPR) and the values of the CurrentX
and CurrentY variables store this information. For example
Line - (160, 90)
Draws a line from the last point referenced to the point with the coordinates
(160, 90).
Boxes:
Line method with little modification draws a rectangle.
Line (FirstCol, FirstRow) – (SecCol, SecRow),CCode, B
draws a rectangle in the given colour code, whose opposite corners are given by
FirstCol, FirstRow and SecCol, SecRow.
193
5.9.6 Filled Boxes
In the above method instead of B use BF to get the filled box.
Filled Style, Fill Color:
Boxes are usually solid or empty but visual basic allows you to use
seven different patterns to fill boxes.
Settings of FillStyle Property Effect
0 Solid
1 (Default) Empty
2 Horizontal line
3 Vertical Line
4 Upward Diagonal
5 Downward Diagonal
6 Cross
7 Diagonal Cross
5.9.7 Circles, Ellipses and Pie charts
The Circle method is used to draw the circle. The syntax is
Circle (0,0) , 0.5
The last point referenced (CurrentX, CurrentY) after a Circle method is always
the center of the circle. The color code can also be added to the circle method.
Circle (0,0), 0.5 , CCode would draw a circle of radius of 0.5 in the
colour specified in the colorcode CCode.
The method Circle (Xrad, Yrad), Radius, CCode, StartAngle,
EndAngle draws an arc of the circle starting at the angle given in radians by
StartAngle and ending with EndAngle.
Ellipses and Aspect ratio:
By adding one more option the same circle draws an ellipse. The syntax
for the method is
Circle [step] (XCenter, YCenter), radius, , , , aspect.
If the aspect parameter is less than 1, the radius is taken in the column
direction and the ellipse is stretched in the horizontal direction. If the aspect
parameter is greater than 1, the radius is taken in the row direction and the
ellipse is stretched in the vertical direction.
5.10 DATABASE
A database is a collection of records that can be manipulated with ease.
Further, all databases can be manipulated using SQL. A table is a basic
repository in which data is stored, and has a specific structure for storing data.
It is made up of one or more than one column. The data is stored in the form of
Rows and Columns. A table may often hold information about one topic.
194
Example:
Students Mark Details
Sl.no Name Language English Allied major
001 Aaaa 70 85 65 70
02 Xxxxx 45 52 85 84
This table consists of two records (rows) and six fields (columns).
The table can be created using Visual Data Manager that comes with
Visual Basic or with other DBMS packages like Oracle and so on. Visual Data
manager is a default connector. Whereas tables created using other packages
are connected through ODBC connectivity or OLEDB provider.
The Visual Data Manager options are available under the AddIns Menu.
When Visual Data Manager is selected the VisData Window is displayed. From
the File menu New option is selected. From the pop–up menu select Access and
the recent version.
Creating a table:
Select New Tables from the database window to create a new table.
This will result in another window being displayed with a number of text boxes
and check boxes. Add the fields and set properties like ordinal position, type
etc.
195
Fig-5. 10 – Sample window – adding fields in the table
To populate the data in the tables, create application with the methods to
1. Establish a connection with the database.
2. Extract the fields from the relevant database.
3. Display them on the form.
4. Accept changes made to the data on the form and update the database.
Using Data Control:
Data control can be used to populate the items from the tables. The
following two properties should be set at runtime or design time to connect
with databases.
Database Name:
This specifies the name of the database that must be opened.
Record Source:
This specifies the name of the table(s) of the database from which
the data has to be extracted.
When we run the program after setting these properties, Visual Basic
connects to the database specified, and returns a set of records from the table(s)
in the form of a Record set.
A Recordset is an object that points to the data in the database. It is the
set of records returned, based on the RecordSource property of the Data
196
control. The RecordSource property can be the name of a table in the databases
or an SQL statement that selects fields from one or more tables.
Setting the properties for the Data Control:
BOFAction : Action to be taken when the user reaches the beginning of file.
EOFAction: Action to be taken when we reach the end of file.
Caption: This tells the Data control the type of database that will be accessed.
It could be FoxPro, dBase, Paradox, Access, etc. the default is Access.
Database Name: Specifies the name of the database that the Data control will
access. Give the name of the file that contains the database.
Recordset Type: This property specifies the type of record set object the
control will use to access the database. There are three options: 1. Table 2.
Dynaset
3. Snapshot.
RecordSource: The RecordSource property specifies the source of the records
accessible thorough bound controls on the form. If the RecordSource property
is set to the name of an existing table in the database, all of the fields in that
table are visible to the bound controls attached to the Data control.
Some of the data Bound Controls are
Label
TextBox
Check Box
Image
OLE
List Box
Picture
Combo Box
Binding the Bound Controls:
Select Text1 in the form. In the properties window do the following.
1. Click on DataSource property. Set it to the name of the data control.
2. Click on Data Field. A List of fields available will drop down. Select the
field name which you want to bind in the text1.
Adding a New Record:
The AddNew method adds a new record at the end of the file, and clears
the contents of the textbox.
Deleting a Record:
The delete method deletes the current record.
197
Updating the Database:
The Data control itself handles the task of updating the database with
the changes made to the current record, when you move the record pointer to
another record.
UpdateRecord and UpdateControls Method:
These methods are special to the Data control. The UpdateRecord
method allows the user to save the changes to the current record and continue
editing. The UpdateControls method does the reverse of the above. This
method will be of use when the user wants to roll back editing changes made to
the current record before updating.
Finding a Record:
The find method works only when the records type is a Dynaset or
snapshot. If the Recordset type is set to Table type, then you have to use seek
method.
Methods to connect to the database:
I Using DAO:
1. In the General section declare the variables as given below.
Dim db as database
Dim rs as recordset
2. To open the database and to populate the records in the recordset
Set db = OpenDatabase(path of the file
Set rs = db.OpenRecordset(select stmt)
Ex:
Set db = OpenDatabase("d:\vbexer\student.mdb")
Set rs = db.OpenRecordset("select * from students")
Where student.mdb is a database and students is a table.
3. Using the recordset rs we can insert, edit and delete the records
II Using ADODB
1. In the General section declare the variables for database connection and the
recordset.
Dim db as adodb.connection
Dim rs as adodb.recordset
2. To connect with the database, create an instance of ADODB connection and
recordset.
set db = new adodb.connection
set rs = new adodb.recordset
198
db.provider = “Microsoft.jet.oledb.4.0” [ provider to connect to Ms-
Access]
db.Open "d:\vbexer\student.mdb" [ enter the path of the mdb file]
rs.Open "select * from perdet", db, adOpenDynamic, adLockOptimistic
Where “perdet” is the table in the database student.mdb
Preparing reports Using Data Report:
1. Select the Data Environment option in the project menu.
2. Right click the connection tab, and select the properties you will get the
window as in the figure.
3. Select the relevant provider and click the next tab. In the popup window
select the database and click the test connection. If the connection is
established correctly then the test connection succeeded message is
displayed.
4. Right click the connection; from the pop up window select add
command. Select the SQL statement.
5. Using the SQL builder, build the command.
6. Add data report.
7. Drag the command from the Data Environment.
8. Align the title and set the values for report title, page title etc.
199
Fig-5.12 Data Link property page
200
Fig- 5.14 Adding Command
201
Fig- 5.16 Dragging command to data report
202
Fig-5.18 Inserting command to data report
203
5.11. BUILDING YOUR OWN ACTIVEX CONTROLS
Prior to the development of Visual Basic 5, VB developers relied on
C++ to create a new reusable controls. Visual Basic 5 has the provision to
create new controls.
Choose ActiveX control from the New Project dialog box. The form in
the middle of the user control designer is user control form. You can add
control or controls correspondingly you can add the code to interact.
Usually text box is a control, which accepts the user value as a string.
To do arithmetic computations the input entered through the text box has to be
converted to numeric value. So, you can create a numeric text box control using
ActiveX control.
Design a numeric text box with the properties:
The current value
A minimum acceptable value
A maximum acceptable value
A range value that allows you to easily set a symmetric range.
Add two custom events to the user control
BadKey for when the user tries to type something like a letter in the
box
BadValue for when the user exceeds the range or copies a non
number into the box.
1. Choose ActiveX control from the New Project dialog box.
2. Add a textbox to the user control.
3. Change the name of the usercontrol1 to NumericTextBox
Testing the control:
Choose File/Add project.
Choose Standard EXE and click open.
Now the project explorer will contain both the projects.
Double click the form in the project2.
Double click on the Numeric Text box line in the project explorer to
make the user control active.
Close the control designer.
To use the new control, double click the icon of the new control in
the tool box.
These steps allows you to create a control of your own and adding the
control to your project. Still you have to add events to make the control as a
numeric text box.
204
After selecting usercontrol, add the events you want. To add custom events, for
example add the given code to lostfocus event.
Private sub txtValue_LostFocus( )
If Not (IsNumeric(txtValue.Text)) Then
RaiseEvent BadValue(NotNumeric)
End IF
End Sub
Add the following information in the declarations of the general section
of the user control form.
Public Event BadValue(WhatsWrong As Integer)
Public Event BadKey( )
Test the control by placing it in some project.
205
NOTES
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
206
NOTES
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
207
NOTES
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
…………………………………………………………………………………...
208