Skip to content Skip to navigation Log In Contact Us Report a Bug Search: Connexions Home Selected:Content Lenses About Us Help MyCNX You are here: Home » Content » VC++ Tutorial for Beginners Navigation RECENTLY VIEWED Print this page Download Reuse / Edit Add to a lens S earch
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Skip to content Skip to navigation
Log In
Contact Us
Report a Bug
Search:
Connexions Home Selected:Content Lenses About Us Help MyCNX
You are here: Home » Content » VC++ Tutorial for Beginners
Navigation
RECENTLY VIEWED
Print this page
Download
Reuse / Edit
Add to a lens
Search
Add to Favorites
VC++ Tutorial for BeginnersModule by: Avanija j. E-mail the author
Summary: This course entails the programming concepts in VC++ with clear syntax specification and programming examples.
Chapter 1
Basics of Windows Programming
1. 1 Paradigms of Programming Languages
Although many different computer architectures are being developed, the most prevalent is still the
traditional von Neumann architecture - consisting of a single sequential CPU separate from memory,
with data piped between cpu and memory. This is reflected in the design of the dominant computer
languages, with dynamic variables (representing memory cells with changing values); sequential
iteration (reflecting the single sequential cpu); assignment statements (reflecting piping). This
combination of choices gives rise to the imperative language paradigm - C, Ada, Pascal, FORTRAN,
COBOL, Basic etc.
But other choices are possible - variables do not have to directly reflect memory cells (logic
programming); repetition need not be iterative (logic, functional, concurrent); assignment need not be
important (logic, functional); data and control need not be separated (object oriented, functional).
A paradigm is essentially a high level model of what computation is about - the unifying factor that
makes Ada and C seem very similar, ignoring details such as what data or control structures are
available, exactly how variables are passed to procedures, and so on.
Some Paradigms
Procedural (COBOL, FORTRAN, Pascal, C)
functional (LISP)
logic (PROLOG)
structured
object-oriented (Smalltalk)
4GL (Dbase)
Visual (Visual Basic)
1.1.1 Procedural
This is focusing on grouping organizations and/or code by similar operations or by the operations that
can be done on them.
1.1.2 Functional
Functional programming is so called because a program consists entirely of functions. The program
itself is written as a function which receives the program's input as its argument and delivers the
program's output as its result. Typically the main function is defined in terms of other functions, which
in turn are defined in terms of still more functions, until at the bottom level the functions are language
primitives. These functions are much like ordinary mathematical functions.
Functional programs contain no assignment statements, so variables, once given a value, never
change. Functions can be described intentionally by a rule describing the association, or extensionally
as a set of associated pairs (argument, result) which are called the graph of the function. Functional
programming also provides greater abstraction for solution. One such a feature is polymorphism which
allows general definition of functions which could be applied to objects of any type. To achieve such a
behavior we use type variables which stand for any type. Further higher order functions provide facility
to treat functions as a data objects and use them like other data objects. It means that function (higher
order function) can manipulate and create other functions. Another important feature of the functional
programming is that evaluation of arguments could be delayed but done at most once. This technique
is called lazy evaluation. Postponing sometimes can lead to such a situation that postponed value
could be found as not necessary to evaluate, even when argument is undefined. If such a function can
return a defined result we call it non-strict, else if returns undefined is called strict.
1.1.3 Logic
The basic constructs of logic programming, terms and statements are inherited from logic. There are
three basic statements: facts, rules and queries. There is a single data structure: the logical term.
In a logic programming language the logical relationship between various entities are declared. The
programmer writes a database of facts and rules. The user supplies a queries (goals) which the system
tries to prove. This involves matching the current goal against each fact or the left hand side of each
rule using unification. If the goal matches a fact, the goal succeeds; if it matches a rule then the
process recurses, taking each sub-goal on the right hand side of the rule as the current goal. If all sub-
goals succeed then the rule succeeds.
Logic programming languages tend to be declarative programming languages, as opposed to the more
traditional imperative programming languages. In a declarative language, you concentrate on the
relationships between the parts of the problem, rather than on the exact sequence of steps required to
solve the problem. An example of a well-known declarative languages are SQL, Prolog.
1.1.4 Structural
Two mathematicians, Corrado Bohm and Guiseppe Jacopini proved that any computer
program can be written with the three structures : sequences, decisions and loops.
This discovery led to the method of modern programming known as structured
programming. Structured programming can be seen as a subset or sub discipline of
Procedural programming one of the major paradigms (and probably the most popular
one) for Programming computers. It is possible to do structured programming in
almost any procedural programming languages.
Edsger Dijkstra a professor of computer science at the Technological University at Eindhoven proposes
that GOTO statements be abolished from all high-level languages such as BASIC. Modern programming
languages such as Visual Basic do away with the need for GOTO statements.
A computer program is said to be structured if it has a modular design and uses only the three types of
logical structures, sequences, decisions and loops.
Sequences: Statements are executed one after another.
Decisions: One of two blocks of program code is executed based on a test for some condition.
Loops (Iteration): One or more statements are executed repeatedly as long as a specified condition is
true.
One major shortcoming of earlier programming languages was their reliance on the GoTo statement.
This statement was used to branch (that is jump) from one line of the program to another. It was
common for a program to be composed on a convoluted tangle of branching that produced confusing
code sometimes referred to as spaghetti code.
The logic of a structured program can be pictured using a flowchart that flows smoothly fro the top to
the bottom without unstructured branching (GoTos). Here is an example of a flowchart showing the
structure with and without the GoTo statement:
Advantages of
Structured Programming
The goal of structured programming is to create correct programs that are easy to write, understand
and change.
Easy to writeModular design increases the
programmer's productivity by allowing them to
look at the big picture first and focus on details
later. Several Programmers can work on a single,
large program, each working on a different
module. Studies show structured programs take
less time to write than standard programs.
Procedures written for one program can be reused
in other programs requiring the same task. A
procedure that can be used in many programs is
said to be reusable
Easy to debugSince each procedure is specialized
to perform just one task, a procedure can be
checked individually. Older unstructured programs
consist of a sequence of instructions that are not
grouped for specific tasks. The logic of such
programs is cluttered with details and therefore
difficult to follow.
Easy to UnderstandThe relationship between the
procedures shows the modular design of the
program.Meaningful procedure names and clear
documentation identify the task performed by
each module. Meaningful variable names help the
programmer identify the purpose of each variable.
Easy to ChangeSince a correctly written
structured program is self-documenting, it can be
easily understood by another programmer.
Earlier Analysis and Design
As programs got more complex, programmers realized that there might be a better way to write
programs than getting a problem statement and sitting down and writing code. In other words, a little
abstract planning might help. Along these lines, some abstract modeling techniques were developed.
Earlier methods included flowcharts and functional specifications, functional decomposition. Later
techniques involved:
data flow diagrams (functionality)
data dictionaries (functionality)
Decision trees
process specifications (structured English)
entity relationship diagrams (data -- Information
modeling)
The later techniques arose from the structured programming languages, and became used in
structured analysis and design. The intention of the models was to create extra levels of abstraction
between the real-world problem/system and the computer implementation of the system. They served
as a bridge between the real world situation, and the computer code. The problem was mapped into a
verbal problem statement, and then into a requirements analysis model, which was far removed from
the machine implementation. The analysis model was then mapped into a design model, which was
one step closer to the machine implementation (the code). Finally, code was written from the design
model. However, these earlier abstract models all ran on one premise -- there is data, and there are
functions that process the data. The first models attempted only to model the functionality of the real-
world systems. Later, entity relationship diagrams were added -- these modeled the data, or the static
nature of the system. However, the functionality models and the data models were distinct and
separate entities.
1.1.4 Object-oriented
In object-oriented programming programmers define not only the data type of a data structure, but
also the types of operations (functions) that can be applied to the data structure. In this way, the data
structure becomes an object that includes both data and functions. In addition, programmers can
create relationships between one object and another. For example, objects can inherit characteristics
from other objects. Objects and object interactions are the basic elements of design.
One of the principal advantages of object-oriented programming techniques over imperative
programming techniques is that they enable programmers to create modules that do not need to be
changed when a new type of object is added. A programmer can simply create a new object that
inherits many of its features from existing objects. This makes object-oriented programs easier to
modify.
The advantages of object-oriented programming do not evidence themselves when you are writing a
single function for a particular purpose. Instead, the advantages arise when you are designing a large
system that will do similar , but not identical, things to a variety of data objects. By specifying classes
of data objects for which identical effects will occur, you can define a single generic function that
embraces the similarities across object types, but permits individual implementations or methods for
each defined class. As an example of languages that implements object paradigm are Smalltalk, Delphi
and Java.
OO The Object Oriented Paradigm
Is it possible to make a computer think the way people naturally think, rather than in terms of data and
instructions that process data? The base machine will probably always think in terms of data and
instructions that process data. However, are there high-level languages that can add another layer of
abstraction on top of the machine, so that the high level languages can be written in code that mirrors
the way people think? Yes, of course -- these are the OO languages! Some OO languages are better at
hiding the basic premise of the machine. Smalltalk is probably the best, while C++ is probably the
worst .
History of OO languages
First OO language was Simula -- 1967. Used widely in Europe, it never caught on in the U.S. Then came
Smalltalk -- 1972. In 1986, Bjarne Stroustrup invented C++, and Brad Cox created Objective-C. OO
languages began taking off at this time. But as of 1994, OO languages have been around for 24 years.
Earlier versions, such as Smalltalk, may have been unpopular because machines weren't powerful
enough to handle them.
What Makes a Language Object-Oriented?
According to Bertrand Meyer, an OO programming language should contain the following 7 qualities
[7]:
The support of modules.
The modules must support data
abstraction, which entails: a.) Information
hiding and b.) Encapsulation.
Automatic memory management (not
necessarily garbage collection).
All data are defined by abstract data type
(ADT) based modules. (e.g. classes).
Ability to extend existing classes (i.e.
inheritance).
Support of polymorphism and dynamic
binding.
Multiple inheritance (the need for this
feature in an OO language is disputed by
many in the OO field.)
Objects
Basic building block of OO languages is the object. Like objects of human thought, OO objects combine
both data (nouns and adjectives) and actions (verbs) into one package. Data is implemented as data,
while actions are implemented as functions. The machine still sees a data-functionality split. But the
outside world sees data and functionality merged into one whole.
Classes
OO Languages promote classification at two levels. First, there is the class construct. Classes are like
"cookie cutters" from which objects are moulded. We have a "cat" class from which we create cat
objects, each with different attributes. The class specifies the attributes (and the functionality) while
the objects fill in the attribute values. For example, we have a cat class that has weight, color, and
name attributes specified. From the cat class, we create cat objects, through which the program is
actually run.
Inheritance
A looser classification scheme is obtained through inheritance. We can tie in our cat class into a whole
inheritance hierarchy which includes the entire cat family, the mammals, all animals, and then all
living things.
Polymorphism
Polymorphism is the method by which OO languages mirror the human thought processes' tendency to
group certain actions together. We can call similar functionality by the same name -- e.g. cats eat and
cows eat, but the way they eat is different. However, we still call their actions "eating". OO languages
allow for similar functions (actions) to be given similar names. This allows for conceptual clarity in
writing code. Note that C and other traditional languages use polymorphism to some extent. For
example, the arithmetic operators act on both floating point numbers and integers with the same
operators (+, - , /, *, etc) even though the underlying implementation is radically different.
Abstraction
Software objects mirror the human mind's tendency to abstract out details. Software objects hide the
internal details of an object behind the walls of an interface. The "user" or "client" of an object does
not have to worry about the inner details of the object, only the abstract principles of the object, as
defined by the interface.
1.2. The Windows Environment
Windows is a Graphical User Interface (GUI). It uses graphics to organize the user’s workspace. User’s
choose items and execute programs by pointing and clicking with a mouse. The program that run from
within Windows also have a Graphical User Interface (GUI); for example, MS-Excel and MS-Word.
Moreover these programs can run only within Windows. This is because Windows provides these
programs with a number of built in functions and data which are not available in other environments.
The functions that are provided by windows include functions with the functionality to draw text in
different sizes and styles using font data. Windows provides a broad range of graphical functions for
drawing lines and geometric shapes and changing color. Windows program make use of these built in
functions and do not have to be coded to perform these tasks.
These system defined functions that an application can call are provided by an interface known as the
Application Program Interface (API) Every Windows environment has its unique API. For example, the
API that Windows 95 supports (also called the Win32 interface) is a 32-bit API. All the functions
supported by the API can work with 32 bits of information at any given time. Writing programs for the
Windows environment using the API functions is referred to as SDK programming where SDK stands for
Software Development Kit.
1.3
A History of Windows
Windows promised an easy-to-use graphical interface, device-independent graphics and multitasking
support. The development was delayed several times, however, and the Windows 1.0 hit the store
shelves in November 1985. The selection of applications was sparse, however, and Windows sales
were modest.
Windows 1.0 package, included
MS-DOS Executive, Calendar, Cardfile, Notepad, Terminal, Calculator, Clock, Reversi, Control Panel, PIF
(Program Information File) Editor, Print Spooler, Clipboard, RAMDrive, Windows Write, Windows Paint.
On November 10, 1983, Microsoft announced Microsoft Windows, an extension of the MS-DOS
operating system that would provide a graphical operating environment for PC users. Microsoft called
Windows 1.0 a new software environment for developing and running applications that use bitmap
displays and mouse pointing devices. With Windows, the graphical user interface (GUI) era at Microsoft
had begun.
The release of Windows XP in 2001 marked a major milestone in the Windows desktop operating
system family, by bringing together the two previously separate lines of Windows desktop operating
systems.
With the upcoming release of Windows .NET Server, Microsoft will complete a cycle of server operating
system upgrades it began nearly a decade ago in 1993, with the release of the first version of
Microsoft Windows NT Server. To understand the progression of Windows server operating systems
you have to look back earlier than 1993, however, to the even longer line of Windows desktop
operating systems stretching back to the early 1980s.
To explain the many advances since Windows 1.0, the following pages summarize milestones in the
development of Windows desktop operating systems at Microsoft.
Many longtime PC users trace Windows to the 1990 release of Windows 3.0, the first widely popular
version of Windows and the first version of Windows many PC users ever tried. But Microsoft actually
released the first version of Windows six years earlier, in 1985. To understand the roots of today's
Windows operating systems, we must journey back nearly 20 years.
The Windows 1.0 product box showed the new tiled windows and graphical user interface in the operating systemTABLE 1
1985: Windows 1.0
The first version of Windows was a milestone product because it allowed PC users to switch from the
MS-DOS® method of typing commands at the C prompt (C:\) to using a mouse to point and click their
way through functions, such as starting applications, in the operating system.
Windows 1.0 also allowed users to switch between several programs—without requiring them to quit
and restart individual applications. The product included a set of desktop applications, including the
MS-DOS file management program, a calendar, card file, notepad, calculator, clock, and
telecommunications programs, which helped users manage day-to-day activities.
Even before the Windows 1.0 graphical user interface, there was this pre-Windows 1.0 Interface ManagerTABLE 2
1987: Windows 2.0
With the second version of Windows, Microsoft took advantage of the improved processing speed of
the Intel 286 processor, expanded memory, and inter-application communication capabilities using
Dynamic Data Exchange (DDE). Windows 2.0 featured support for the VGA graphics standard, and also
allowed users to overlap windows, control screen layout, and use keyboard combinations to move
rapidly through Windows operations.
Many developers started writing their first Window-based applications for Windows 2.x. Following the
release of Windows 2.0 was Windows/386 2.03, which took advantage of the protected mode and
extended memory capabilities of the Intel 386 processor.
Subsequent Windows releases continued to improve the speed, reliability, and usability of the PC, and
improved the interface design and capabilities.
1990: Windows 3.0
Microsoft's first mainstream computing platform offered 32-bit performance, advanced graphics, and
full support of the more powerful Intel 386 processor. A new wave of 386 PCs helped drive the
popularity of Windows 3.0, which offered a wide range of new features and capabilities, including:
Program Manager, File Manager, and Print
Manager
A completely rewritten application
development environment with modular
virtual device drivers (VxDs), native
support for applications running in
extended memory, and fully pre-emptive
MS-DOS multitasking
An improved set of Windows icons
The popularity of Windows 3.0 blossomed with the release of a completely new Windows software
development kit (SDK), which helped software developers focus more on writing applications and less
on writing device drivers. Widespread acceptance among third-party hardware and software
developers helped fuel the success of Windows 3.0.
Windows 3.0 featured a new File ManagerTABLE 3
1993: Windows for Workgroups 3.11
A superset of Windows 3.1, Windows for Workgroups 3.11 added peer-to-peer workgroup and domain
networking support. For the first time, Windows PCs were natively network-aware and became an
integral part of the emerging client/server computing evolution.
Windows for Workgroups was used in local area networks (LANs) and on stand-alone PCs and laptop
computers. It added features of special interest to corporate users, such as centralized configuration
and security, significantly improved support for Novell NetWare networks, and remote access service
(RAS). Windows for Workgroups also offered the performance benefits of Microsoft's new 32-bit file
system.
1993: Windows NT 3.1
The release to manufacturing of Microsoft Windows NT® on July 27, 1993, marked an important
milestone for Microsoft. It completed a project Microsoft began in the late 1980s to build an advanced
new operating system from scratch. "Windows NT represents nothing less than a fundamental change
in the way that companies can address their business computing requirements.
Windows NT was the first Windows operating system to combine support for high-end client/server
business applications with the industry's leading personal productivity applications. The operating
system broke new ground in security, operating system power, performance, desktop scalability, and
reliability with a range of key new features. These included a pre-emptive multitasking scheduler for
Windows-based applications, integrated networking, domain server security, OS/2 and POSIX
subsystems, support for multiple processor architectures, and the NTFS file system.
Windows NT 3.1 contained overlapping windows and other features similar to Windows 3.1TABLE 4
The new operating system began with version 3.1 in order to maintain consistency with Windows 3.1,
which at the time was a well-established operating system for both home and business users.
Windows NT was geared toward business users and was initially available in both a desktop
(workstation) version and a server version called Windows NT Advanced Server. The desktop version
was well received by developers because of its security, stability, and rich Microsoft Win32®
application programming interface (API)—a combination that made it easier to support powerful
programs.
Windows NT was a strategic platform that could integrate client/server applications with existing
Windows-based desktop applications, or function as a technical workstation to run high-end
engineering or scientific applications.
1993: Windows NT Workstation 3.5
Windows NT Workstation 3.5 supported the OpenGL graphics standard, which helped power high-end
applications for software development, engineering, financial analysis, scientific, and business-critical
tasks.
The Windows NT Workstation 3.5 release provided the highest degree of protection yet for critical
business applications and data. The product also offered 32-bit performance improvements, better
application support, including support for NetWare file and print servers, and improved productivity
features, such as the capability to give files 255-character names.
1995: Windows 95
Windows 95 was the successor to Microsoft's three existing general-purpose desktop operating
systems—Windows 3.1, Windows for Workgroups, and MS-DOS. Windows 95 included an integrated 32-
bit TCP/IP stack for built-in Internet support, dial-up networking, and new Plug and Play capabilities
that made it easy for users to install hardware and software.
The 32-bit operating system also offered enhanced multimedia capabilities, more powerful features for
mobile computing, and integrated networking. In order to keep memory requirements to a minimum, it
did not include support for such features as system-level security or Unicode, which came later.
1996: Windows NT Workstation 4.0
This upgrade to Microsoft's business desktop operating system brought increased ease of use and
simplified management, higher network throughput, and a complete set of tools for developing and
managing intranets.
Windows NT Workstation 4.0 included the popular Windows 95 user interface and improved networking
support, providing secure, easy access to the Internet and corporate intranets.
In October 1998, Microsoft announced that Windows NT would no longer carry the initials NT," and
that the next major version of the operating system would be called Windows 2000.
1998: Windows 98
Windows 98 was the upgrade to Windows 95. Described as an operating system that "Works Better,
Plays Better," Windows 98 was the first version of Windows designed specifically for consumers.
Windows 98 enabled users to find PC- or Internet-based information easily, it opened and closed
applications more quickly, and it included support for reading DVD discs and connecting to universal
serial bus (USB) devices.
1999: Windows 98 Second Edition
Microsoft Windows 98 SE, as it was often abbreviated, was an incremental update to Windows 98. It
offered consumers a variety of new and enhanced hardware compatibility and Internet-related
features.
Windows 98 SE delivered an improved online experience with Internet Explorer 5 browser software and
Microsoft Windows NetMeeting® version 3.0 conferencing software. It also included Microsoft
DirectX® API 6.1, which delivered a variety of Windows multimedia improvements, and offered home
networking capabilities through Internet connection sharing (ICS). Windows 98 SE was also Microsoft's
first consumer operating system capable of using device drivers that also worked with the Windows NT
business operating system.
2000: Windows Millennium Edition (Windows Me)
Windows Me offered consumers numerous music, video, and home networking enhancements and
reliability improvements.
System Restore let users roll back their PC software configuration to a date or time before a problem
occurred. Windows Movie Maker provided users with the tools to digitally edit, save, and share home
videos. Microsoft Windows Media™ Player 7 technologies allowed users to easily find, organize, and
play digital media.
Windows Me was the last Microsoft operating system to be based on the Windows 95 kernel. Microsoft
announced that all future operating system products would be based on the Windows NT and Windows
2000 kernel.
2000: Windows 2000 Professional
Figure 1
Windows 2000 Professional was the upgrade to Windows NT Workstation 4.0, but it was more than just
that. Windows 2000 Professional was designed to replace Windows 95, Windows 98, and Windows NT
Workstation 4.0 on all business desktops and laptops. Built on top of the proven Windows NT
Workstation 4.0 code base, Windows 2000 added major improvements in reliability, ease of use,
Internet compatibility, and support for mobile computing.
Windows 2000 Professional also made hardware installation much easier than it was with Windows NT
Workstation 4.0 by adding support for a wide variety of new Plug and Play hardware, including
advanced networking and wireless products, USB devices, IEEE 1394 devices, and infrared devices.
2001: Windows XP
Windows XP is a unifying leap forward for desktop operating systems. With the release of Windows XP
Home Edition and Windows XP Professional in October 2001, Microsoft succeeded in merging its two
Windows operating system lines for consumers and businesses, uniting them around the Windows NT
and Windows 2000 code base.
With Windows XP, consumers and home users now have performance, stability, and security that
business users benefited from in Windows 2000.
Windows XP also includes the broad base of application and hardware compatibility of Windows 98 and
Windows Me, while adding new tech-support technology, a fresh user interface, and many other
improvements that make it easier to use for a broad range of tasks.
Windows XP is available in two main versions, Windows XP Professional and Windows XP Home Edition,
as well as a 64-bit edition, Windows XP 64-Bit Edition, for power users with workstations that use the
Intel Itanium 64-bit processor.
2001: Windows XP Professional
Windows XP Professional benefits from the long track record of Microsoft Windows NT technology:
superior operating system performance, including preemptive multitasking, fault tolerance, and
system memory protection.
Windows XP Professional also offers a redesigned interface and includes features for business and
advanced home computing, including Remote Desktop, encrypting file system, system restore and
advanced networking features. It also offers numerous key enhancements such as wireless 802.1x
networking support, Windows Messenger, Remote Assistance, and the System Restore feature.
2001:WindowsXPHomeEdition
Windows XP Home Edition offers a clean, simplified visual design that makes frequently accessed
features more accessible. The product offers many enhancements aimed at home users such as the
Network Setup Wizard, Microsoft Windows Media™ Player, Windows Movie Maker, and enhanced digital
photo capabilities.
1.4 Windows Programming Model
Programs written for traditional operating environments use a procedural programming model in which
programs execute from top to bottom in an orderly fashion. The path taken from start to finish may
vary with each invocation of the program depending on the input it receives or the conditions under
which it is run, but the path remains fairly predictable. In a C program, execution begins with the first
line in the function named main and ends when main returns. In between, main might call other
functions and these functions might call even more functions, but ultimately it is the program—not the
operating system—that determines what gets called and when.
Windows programs operate differently. They use the event-driven programming model illustrated in
Figure 1.4, in which applications respond to events by processing messages sent by the operating
system. An event could be a keystroke, a mouse click, or a command for a window to repaint itself,
among other things. The entry point for a Windows program is a function named WinMain, but most of
the action takes place in a function known as the window
procedure.
Figure 1.4 Windows Programming Model
The window procedure processes messages sent to the window. WinMain creates that window and
then enters a message loop, alternately retrieving messages and dispatching them to the window
procedure. Messages wait in a message queue until they are retrieved. A typical Windows application
performs the bulk of its processing in response to the messages it receives, and in between messages,
it does little except wait for the next message to arrive.
The message loop ends when a WM_QUIT message is retrieved from the message queue, signaling
that it's time for the application to end. This message usually appears because the user selected Exit
from the File menu, clicked the close button (the small button with an X in the window's upper right
corner), or selected Close from the window's system menu. When the message loop ends, WinMain
returns and the application terminates.
1.5 Dynamic Link Library (DLL)
Dynamic Link Library (DLL) is a collection of software routines programmed in a language such as C or
Pascal, which has been packaged especially for use from another program. For example, a C
programmer might write a routine that accesses a laser disc player. By compiling this as a DLL, it
might be usable by an author of a Windows Help hyper book, without them having to know anything
about the programming. In windows programming DLL plays an important part. Windows provides
function calls to implement its user interface and display text and graphics on the video display. These
functions are implemented in DLL. These are files with extension .DLL or .EXE.
The original idea for the DLL system was that there would be a central repository of code. Here are the
advantages:
Applications would link to this code
library, thus saving greatly on duplication
of effort and storage space.
Applications that used the DLL system
would behave exactly the same as all
other applications that used it.
If a problem arose, or a new feature was
desired, it could be written once and all
would benefit. In this sense, the DLL
system is a weak version of the object-
programming paradigm.
Naturally enough, along with these advantages came some responsibilities. An application should only
place a DLL in the central repository if:
The DLL was newer and/or better than the
ones already there.
The DLL was uniquely named, i.e. did not
conflict with a DLL for another purpose
with the same name.
If the DLL replaced another with the same
name, then the code in the DLL would be
exhaustively tested, so that on
replacement, other applications could use
it in the same way as its predecessor.
In time, all these rules have been broken, even by Microsoft itself, the originator of the idea.
On several occasions Microsoft has
created and distributed DLL files that
instantaneously broke every Windows
application in the world.
Regularly, end users will install an
application that has a DLL with the same
name as a "system" DLL, thus
mysteriously bringing down the system
until an expert can sort it out.
Over time, the "synchronization" problem
becomes more severe. In this scenario, a
DLL is replaced that brings it into conflict
with other DLLs it must work with.
The service pack problem is becoming
severe. In this scenario, Microsoft releases
a service pack that updates all key system
DLLs. All the elements of the service pack
must simultaneously be present in their
most recent form or the system will crash.
Then the user installs an application that
blithely replaces one or more of the DLLs
from the service pack. Result – system
failure, even on Windows NT 4.0, which,
notwithstanding its reputation for stability
and resilience, will fail utterly and
completely.
This is an example of a collision between an idea and reality, a key element in the human drama. The
idea was sound, but it failed to take into account the imperfections in the human character, in
particular those imperfections that influence the creation and operation of computer programs. The
reality is that Microsoft and any number of software vendors regularly risk the stability and security of
the end user's machine by writing DLL code as though it were normal programming. It isn't. To write a
DLL, you must imagine the effect of your changes and additions on every computer program that uses
it. This is obviously impossible. The solution to these problems is to go back to the system that
preceded the DLL system. Every application should place as many DLL files as possible in its own
directory (some DLL files are part of Windows itself, these must be accessed in common). No
application should assume that it can copy DLLs into the system directory or that its newer version of a
system DLL is safe to copy solely because it is newer. Many applications (including Microsoft's own)
have rendered systems unstable or unusable through this reasoning.
Win32s DLL Libraries
The Win32s DLL Libraries are an add-on set of programs that expand the MS Windows 3.1 and MS
Windows for Workgroups 3.11 systems so that they can run programs that follow the Win32s standard
from MicroSoft. By allowing them to run Win32s compliant programs, programers can write programs
to follow that standard and have it run, hopefully, on MS Windows 3.1, MS Windows for Workgroups
3.11, MS Windows 95 and MS Windows NT.
MS DOS and MS Windows 3.1/MS Windows for Workgroups 3.11 run 16-bit coded programs. The limit
to 16-bit allows them to run on older computers with no significant changes. MS Windows 95 and MS
Windows NT run 32-bit coded programs and do not need DOS at all. The 32-bit code needs at least a
386 IBM Compatible computer to run because the code is 32-bits instead of 16-bits it can:
Use the full BUS width of the CPU to tranfer more
information per computer clock cycle
Have a more robust command structure with a
possible 2^32 ( 4294967296 ) commands. Of
course, at this stage of computer development
there is no need for THAT MANY commands. But it
is useful for splitting up common functions into
seperate commands that were previously
combined or grouping some common groups of
commands into single commands.
In the course of writing and distributing Windows applications, the majority of customer problems were
related to DLLs. If you create a program that assumed that standard Windows system DLLs would be
present, those DLLs would not be present or would not be current, and the application would fail. If I
took it upon myself to follow the DLL guidelines and copy DLLs into the system directory after
ascertaining that my DLL was newer than the current one, other applications would fail. To avoid this
problem it is better to include in the application all required DLLs in the program directory.
1.6 API (Application Programming Interface)
A set of routines, protocols, and tools for building software applications. A good API makes it easier to
develop a program by providing all the building blocks. A programmer puts the blocks together.
API (Application Programming Interface) is a set of commands, which interfaces the programs with the
processors. The most commonly used set of external procedures are those that make up Microsoft
Windows itself. The Windows API contains thousands of functions, structures, and constants that you
can declare and use in your projects. Those functions are written in the C language, however, so they
must be declared before you can use them. The declarations for DLL procedures can become fairly
complex. Specifically to C# it is more complex than VB. You can use API viewer tool to get API function
declaration but you have to keep in mind the type of parameter which is different in C#.
Most of the advanced languages support API programming. The Microsoft Foundation Class Library
(MFC) framework encapsulates a large portion of the Win32 (API). ODBC API Functions are useful for
performing fast operations on database. With API your application can request lower-level services to
perform on computer's operating system. As API supports thousands of functionality from simple
Message Box to Encryption or Remote computing, developers should know how to implement API in
their program.
API\’s has many types depending on OS, processor and functionality.
OS specific API:
Each operating system has common set of API's and some special
e.g.
Windows NT supports MS-DOS, Win16, Win32, POSIX (Portable Operating System Interface), OS/2
console API and Windows 95 supports MS-DOS, Win16 and Win32 APIs.
Win16 & Win32 API:
Win16 is an API created for 16-bit processor and relies on 16 bit values. It has platform independent
nature.
e.g. you can tie Win16 programs to MS-DOS feature like TSR programs.
Win32 is an API created for 32-bit processor and relies on 32 bit values. It is portable to any operating
system, wide range of processors and platform independent nature. Win32 API’s has ‘32’ prefix after
the library name e.g. KERNEL32, USER32 etc…
All APIs are implemented using 3 Libraries.
Kernel
User
GDI
KERNEL
It is the library named KERNEL32.DLL, which supports capabilities that are associated with OS such as
Process loading.
Context switching.
File I/O.
Memory management.
e.g. The GlobalMemoryStatus function obtains information about the system's current usage of both
physical and virtual memory
USER
This is the library named "USER32.DLL" in Win32. This allows managing the entire user interfaces such
as :
Windows
Menus
Dialog Boxes
Icons etc.
e.g. The DrawIcon function draws an icon or cursor into the specified device context.
GDI (Graphical Device Interface)
This is the library named "GDI32.dll" in Win32. It is Graphic output library. Using GDI Windows draws
windows, menus and dialog boxes.
It can create Graphical Output.
It can also use for storing graphical images.
e.g. The CreateBitmap function creates a bitmap with the specified width, height, and color format
(color planes and bits-per-pixel).
1.7 The Programming Environment
The Microsoft Visual C++ package includes more than the C compiler and other files and tools
necessary to compile and link windows programs. It also includes the Visual C++ Developer Studio an
environment in which you can edit your source code, create resources such as icons and dialog boxes
and edit, compile, run and debug your programs. The msdn portion of the Microsoft URL stands for
Microsoft Developer Network which is a program that provides developers with the frequently updated
CD-ROMs containing much of what they need to be on the cutting edge of windows development.
1.7.1 Graphical User Interface Concepts
Since the invention of Graphical User Interface (GUI) is in 1972 from that we have seen a good number
of attempts to define and build the perfect GUI. GUI consists of number of elements such as:
The Explorer – Program that manages the GUI.
The Taskbar – Gray bar across the bottom of the
screen. It contains icons representing all active
programs, the clock and various utilities.
The Start Menu – A one button approach to
accessing programs, help, and system settings.
GUIs offer a standard look and feel to application thus reducing development and learning time. A GUI
is an environment that can work with graphic objects and it allows event-based interaction with
program for e.g., clicking on mouse buttons, entering data through a text field (like for the calculator
tool). Each event triggers the execution of event handler function to take appropriate action. Microsoft
Windows a typical example has the following components.
Menus (Including placement and names of options
and styles such as pull down or popup).
Icons (for identifying application and resources).
Tiled Windows (for views of multiple programs or
data or for multiple views of a single program or a
data block).
Dialog Boxes (for selecting files, options and
settings when an option is selected, the one
previously selected is turned off).
Check Lists (from which the user can make
multiple selections as in specifying print or file
attributes).
Support for a pointing device, typically a mouse
(especially to select and drag screen elements).
Scroll bars (along the edges to show the relative
position of the contents such as the end or
beginning of the text or to move to a different
position such as another part of a spread sheet).
A GUI enforces consistency by restricting developers they must support features for the program to
run under the GUI. In addition one benefit of GUI is that the user can learn a second application faster
because he or she is familiar with the environment. Note that the benefit comes with succeeding
applications. Consistency and familiarity help produce shorter learning curves. Users generally prefer
the interface style they know, whether it be Macintosh or Microsoft Windows. The consistency offered
by a GUI trades on the users familiarity with the environment.
Drawing and CAD programs are the best suited to GUI. Since, by their nature they manipulate objects
lines and curves, fill closed areas with color. For database programs, such manipulation is not as
useful. However they can use GUIs effectively to:
Specify data fields when setting up reports.
Select sort keys.
Transfer data to or from other applications (such
as a spread sheet).
The last point is particularly important. Database applications often must transfer data to and from
spreadsheets, word processors, desktop publishing programs, business or presentation graphics
programs, statistics programs or project management software. GUIs generally have data exchange
features, such as Microsoft windows dynamic data exchange (DDE) to handle such transfers.
A final benefit of GUI is that it lets you see the final product before you print it. What You See Is What
You Get (WYSIWYG) is a feature essential to desktop publishing and drawing applications and useful in
database applications (so you can inspect reports to see that all data fits on the page).
However there are drawbacks associated with using GUI. The cost includes the expense of graphics
cards, pointing device (such as mouse) and extra memory. Because GUIs run in graphics mode, screen
refresh is usually slower as well. If speed is important, a GUIs consistency may not be sufficient
compensation.
1.8 Event Driven Programming
While your program was looking for a particular kind of input, be it a mouse click or a key press, it
wasn’t doing any other work. If at a particular place in your program you were looking for a mouse
click and a key was pressed, generally the key press was ignored (at least at that instant). While this
approach to programming is functional in many situations, it does not work very well when there are
multiple possible sources of input whose arrival time you cannot predict and where it is unacceptable
to ignore any of the inputs. As an example consider the case of a VCR.
On a typical VCR there are a number of buttons, sensor inputs for tape in and the end of the tape as
well as commands that can be received from the remote control. The program for the embedded
computer controlling the VCR must be able to respond to any of those inputs at any time and in any
sequence. For example, while running fast forward, you can stop, play, change channels, and program
the VCR to record or any number of other actions. The program cannot move to only looking for the
channel select buttons while you are programming, or it would miss the end of tape sensor for the
rewinding tape.
Clearly, what we need is a program structure that will allow us to respond to a multitude of possible
inputs, any of which may arrive at unpredictable times and in an unpredictable sequence. While this
problem is very common in embedded systems, like the VCR, it is also very common in modern
desktop computers. Think about using a word processor. While you are typing, the program is
accepting your keys and entering the characters into your document. You can also click with the
mouse at any place on the screen. If the mouse pointer is at another place in your document, the point
of insertion moves. If it is in the menu bar, a menu will drop down. If it is over a formatting button, it
may change the format of the next character entered. Your word processor, or most other programs
running under Windows, MacOS, X-Windows or any other modern Graphical User Interface(GUI), must
also be capable of dealing with the same kind of variable input that the VCR must handle. All of these
operating systems, and many embedded applications, have adopted a common program structure to
deal with the need to respond to many asynchronous (not time sequence) inputs. This program
structure is generally called event driven programming.
Under the event driven programming model, the program structure is divided into two rough groups,
Events and Services. An event represents the occurrence of something interesting. A service is what
you do in response to the event. While events most often originate from the outside your program,
such a mouse click, events can also generated by other parts of the program. The program executes
by constantly checking for possible events and, when an event is detected, executing the associated
service.
In order for this approach to work, the events must checked continuously and often. This implies that
the services must execute quickly, so that the program can get back to checking for events. In order to
meet this requirement, the service can not to go into a state where it is waiting for some long or
indeterminate time. The most common example of this would be a while loop where the condition for
termination was not under program control, for example; a switch closure. This kind of program
structure, an indefinite loop is referred to as ‘Blocking ‘ code. In order for the even t driven
programming model to work, you must only write ‘Non-Blocking’ code. So how to deal with the need to
wait for the switch close? You make the switch closure an event. Then, rather than waiting in a loop for
the switch to close, you program a service that does the right thing when the switch closes and let all
of the event checkers run while you are waiting for the switch to close. In this way, you could also
react to another event while you were waiting for the switch to close.
Event Checkers
An event, by its nature, represents a discrete point in time. At one instant, the event has not occurred ,
at the next it has. In the case of a switch, the opening or closing of the switch represents an event. The
switch being open or closed does not represent an event. The event is marked by the transition from
open to closed.
1.9 Header Files
Windows programs begin with a processor directive at the top such as :
#include <windows.h>
WINDOWS.H is a master file that includes other Windows header files, some of which also include other
header files. The most important and most basic of these header files are:
WINDEF.H Basic type definitions.
WINNT.H Type definitions for Unicode support.
WINBASE.H Kernel functions.
WINUSER.H User interface functions.
WINGDI.H Graphics device interface functions.
These header files define all the Windows data types, function calls, data structures and constant
identifiers. They are important part of Windows documentation.
1.10 Program Entry Point
In windows program the entry point is WinMain similar to the main function in C program. The WinMain
function appears like this:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine,
int nCmdShow)
It is declared in WINBASE.H like so (line breaks and all) :
int
WINAPI
WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd
);
This declaration uses a system called “Hungarian notation” through which the variable name is
indicated with a short prefix that indicates the variables data type. This notation will be discussed
later. The first parameter to WinMain is an “instance handle”. In windows programming a handle is
simply a number that an application uses to identify something. In this case the handle uniquely
identifies the program. It is required as an argument to some other windows function calls. In early
versions of windows when you run the same program concurrently more than once, multiple instances
of that program will be created. A program can determine if other instances of itself are running by
checking the hPrevInstance parameter. In 32 bit versions this concept has been abandoned.
The second parameter to WinMain is always NULL (defined 0). The third parameter to WinMain is
command line used to run the program. The fourth parameter to WinMain indicates how the program
should be initially displayed either normally or maximized to fill the window or minimized to be
displayed in the task list bar.
1.11 Compile, Link and Run Windows program
When you are ready to compile your program named samplewinprg, you can select Build
samplewinprg.exe from the Build menu or press F7, or select the Build icon from the Build toolbar. The
appearance of this icon is shown in the Build menu. If the Build toolbar is not currently displayed you
can choose Customize from the tools menu and select the Toolbars tab. Pick Build or Build MiniBar.
Alternatively you can execute samplewinprg.exe from the Build menu by pressing Ctrl+F5 or click the
Execute program icon. From the Build toolbar. A message will be displayed asking if you want to build
the program.
During compilation the compiler generates an .OBJ(object) file from the C source code file. During the
ling stage the linker combines the .OBJ file with .LIB(library) files to create the .EXE(executable) file.
You can see a list of these library files by selecting settings from the Project tab and clicking the Link
tab. In particular you’ll notice KERNEL32.LIB, USER32.LIB, and GDI32.LIB. These are “import libraries”
for the three major Windows subsystems. They contain the dynamic-ling library names and reference
information that is bound in to the .EXE file. Windows uses this information to resolve calls from the
program to function in the KERNEL32.DLL, USER32.DLL and GDI32.DLL dynamic link libraries. In Visual
C++ Developer Studio, you can compile and link the program in different configurations. By default
these are called Debug and Release.
1.12 MessageBox Function
The MessageBox function is designed to display short messages. The window that a MessageBox
displays is considered to be a dialog box. The first argument to MessageBox is normally a window
handle. The second argument is the text string that appears in the body of the message box and the
third argument is the text string that appears in the caption bar of the message box. The fourth
parameter can be any of the combination of constants beginning with the prefix MB_ that are defined
in the WINUSER.H. The list of buttons that can appear in dialog box are:
MB_OK
MB_OKCANCEL
MB_ABORTRETRYIGNORE
MB_YESNO
MB_YESNOCANCEL
MB_RETRYCANCEL
The appearance of the icon in the message box can be any one of the following:
MB_ICANHAND
MB_ICONEXCLAMATION
MB_ICONASTERISK
1.13 Data Types
Windows programming has a reputation for its variety of data types, it uses all C data types and also
introduces a few data types of its own. The sample windows application illustrated in this chapter uses
a few of the Windows data types.
The following code displays a message as displayed in figure 2.10(a)
# include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,PSTR szCmdLine,
In this program, the MessageBox function returns the value 1, but it is more proper to say that it
returns IDOK, which is defined in WINUSER.h as equaling 1.Each running copy of a program is called an
instance. To refer to a particular instance of a program, a handle is required. A handle is an unsigned
integer that Windows uses internally to keep track of objects in memory. For example, every window
on the screen has a unique window handle. Handles are also used to keep a track of running
applications, allocated memory blocks and a host of other objects.
A handle is simply a number assigned by the system to a particular entity. It serves to identify the
entity, whether it is an instance, a window, a control or a block of memory. All objects in windows are
referred to by handles. Handles are a replacement of pointers. There are a number of related data
types for describing different kinds of handles. All these data types begin with the letter H. Thus,
HWND is the data type for a window handle, and HPEN is the handle to PEN. In the program shown
above, hInstance is the handle that identifies the current instance of the application and hPrevInstance
contains the hInstance value for the last copy of application.
Internally the Kernel of windows maintains tables that allow windows to convert handles to physical
memory addresses. A handle is a pointer to a memory location. The reason for this complexity is that
windows moves objects (memory blocks, programs and so on) in memory to make room for others. If
windows moves and object in memory, the handle table is updated. The handle used by the program
does not need to change since it always gets correctly translated to the right physical memory
addresses by the windows kernel, no matter where the object is moved in memory. Figure 2.10(b)
displays a representation of handles in the memory.
Program Windows Kernel Memory
HandleHandle TablePhysical Address
Figure 2.10(b) Handles in the Memory
If a pointer was used to refer to an object in memory, the pointer will be invalid when the object is
moved by windows as a part of its memory management. Thus pointers can be dereferenced whereas
handles will continue to be valid since the handle to pointer table will be updated automatically by
windows whenever it moves an object in memory.
In the above program, LPSTR is another new windows data type that is used; it is used to store a Long
Pointer to a String same as the char data type of C. The MessageBox function of the Win32 API displays
a message on the screen, with the specified title and message text, the message displayed will show
an OK button also, which will dismiss the MessageBox as specified by the MB_OK parameter.
1.14 Hungarian Naming Convention
The names of the variables used in a window program follow a naming convention called Hungarian
notation, in honor of its inventor Charles Simonyi. The idea is to precede variable names with key
letters that describe the type of data the variable represents and follow a verb-noun combination. The
Table 1.14 represents the Hungarian notations.
Table 1.14 Variable Name Codes in Hungarian Notation
Variable Name PrefixCode
Data Type
b BOOL(Boolean). The variable here can take either True or False
values.by BYTE(unsigned character)c Char(character)dw DWORD(double word)fn Functionh Handlei int(integer)l Longn Short(int) or near pointerp Pointers Character stringsz Character string terminated by zerow Word(two bytes)TABLE 5
1.15 Windows String Functions
The collection of string functions included in windows to calculate string length, copy string, concatenate strings and compare strings are listed below:
lstrcmpi - Compares two strings, ignoring case.
lstrcmp – Compares two strings.
lstrcpyn - Copies one string to another, with a maximum length.
lstrcpy - Copies one string to another.
lstrlen - Gets the length of a string in characters.
lstrcmpi
Compares two character strings. The comparison is not case sensitive.
Syntax
int lstrcmpi(LPSTR lpszString1,LPSTR lpszString2);
The first parameter lpszString1 is the pointer to the first null-terminated string to be compared. The
second parameter lpszString2 is the pointer to the second null-terminated string to be compared. This
function returns a negative value if the function succeeds and the string that lpszString1 points to is
less than the string that lpszString2 points to. Returns a positive value if the string that lpszString1
points to is greater than the string that lpszString2 points to. Returns zero if the strings are equal. The
lstrcmpi function compares two wide strings by checking the first characters against each other, the
second characters against each other, and so on until it finds an inequality or reaches the ends of the
strings. Similarly two wide strings can be compared using the function lstrcmpiW and also the wide
character string can be represented using LPCWSTR (long pointer to wide character string).
lstrcmp
Compares two strings. The comparison is case sensitive.
Syntax
int lstrcmp(LPSTR lpszString1,LPSTR lpszString2);
The first parameter lpszString1 is the Pointer to the first null-terminated wide string to be compared.
The second parameter lpszString2 is the Pointer to the second null-terminated wide string to be
compared. Returns a negative value if the function succeeds and the string that lpszString1 points to is
less than the string that lpszString2 points to. Returns a positive value if the string that lpszString1
points to is greater than the string that lpszString2 points to. This function returns zero if the strings
are equal. The lstrcmp function compares two strings by checking the first characters against each
other, the second characters against each other, and so on until it finds an inequality or reaches the
ends of the strings. Similarly two wide strings can be compared ignoring case using the function
The second method to get a handle to DC of the client area of the windows js by calling GetDC to
obtain the handle and ReleaseDC to release the handle. This can be done with the statement like this:
hdc = GetDC (hwnd) ;
[ GDI functions]
ReleaseDC (hwnd,hdc);
The functions GetDC and ReleaseDC should be called in pairs like BeginPaint and EndPaint. GetDC is
used while processing message and ReleaseDC is used to exit the window procedure. Do not call
GetDC in one message and ReleaseDC in another message. A function similar to GetDC is
GetWindowDC. While GetDC returns a device context handle for writing on the client area of the
window, GetWindowDC returns a device context handle for writing on the entire window.To use the
function GetWindowDC your program has to process WM_NCPAINT (non client paint) message.
2.6 TextOut
The TextOut function writes a character string at the specified location, using the currently selected
font, background color, and text color.
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
);
The first argument is the handle to the device context either the hdc value returned from GetDC or
from BeginPaint during the processing of a WM_PAINT message. The second and third arguments x and
y defines the starting point of the character string within the client area. The fourth argument lpsring is
a pointer to character string and the last argument cbString indicates the number of characters in the
string.
Eg: TextOut (hdc,x,y,”LeftButtonPressed”,17);
2.7 System Font and Text Metrics
The device context defines the font that windows uses to display the text when TextOut function is
called. The default font is a system font which is used by windows for text strings in title bars, menus
and dialog boxes. In earlier versions of windows the system font was a fixed pitch font in which all the
characters had the same width. But now the system font is a “raster font” which means that the
characters are defined as blocks of pixels. The size of a character is based on the size of the video
display.
To display multiple lines of text by using the TextOut function the dimensions of characters in the font
should be known The successive lines of the text can be spaced based on the height of the characters
and the columns of the text can be spaced on the average width of the characters. Just as a program
can determine information about the sizes or metrics of user interface items by calling the
GetSystemMetrics function, a program can determine font sizes by calling GetTextMetrics.
GetTextMetrics requires a handle to a device context because it returns information about the font
currently selected in the device context. The TEXTMETRIC structure has 20 fields but only the first
seven fields are essential.
typedef struct tagTEXTMETRIC
{
LONG tmHeight;
LONG tmAscent;
LONG tmDescent;
LONG tmInternalLeading;
LONG tmExternalLeading;
LONG tmAveCharWidth;
LONG tmMaxCharWidth;
[ other structure fields]
}
To use the GetTextMetrics function a structure variable tm should be defined.
TEXTMETRIC tm;
To determine the text metrics you get a handle to a device context and call GetTextMetrics
hdc = GetDC (hwnd) ;
GetTextMetrics (hdc , &tm);
ReleaseDC (hwnd, hdc);
The most important value in TEXTMETRIC is the tmHeight which is the sum of tmAscent and
tmDescent. These two values represent the maximum vertical extents of characters in the font above
and below base line. The term leading refers to the space that the printer inserts between the lines of
text. In the TEXTMETRIC structure internal leading is the space in which accent marks appear and the
external leading is not included in the tmHeight value. It is an amount of space that the designer of the
font suggests be added between successive rows of displayed text. The TEXTMETRIC structure
contains two fields that describes the character width one is tmAveCharWidth field which is a weighted
average of lowercase characters and another is tmMaxCharWidth which is the width of the widest
character in the font.
2.8 System Metrics
Display elements are the parts of a window and the display that appear on the system display screen.
System metrics are the dimensions of various display elements. Typical system metrics include the
window border width, icon height, and so on. System metrics also describe other aspects of the
system, such as whether a mouse is installed, double-byte characters are supported, or a debugging
version of the operating system is installed. The header file SYSMETS.H responds to GetSystemMetrics
function call. The GetSystemMetrics function retrieves the specified system metric. If the function
succeeds, the return value is the requested system metric or configuration setting. If the function fails,
the return value is zero. System metrics may vary from display to display. Applications can also
retrieve and set the color of window elements such as menus, scroll bars, and buttons by using the
GetSysColor and SetSysColor functions, respectively.
GetSystemMetrics
The GetSystemMetrics function retrieves various system metrics (widths and heights of display
elements) and system configuration settings. All dimensions retrieved by GetSystemMetrics are in
pixels.
int GetSystemMetrics ( int nIndex)
The nIndex parameter can be one of the following values. Note that all SM_CX* values are widths and
all SM_CY* values are heights.
Table 2.8 (a) nIndex parameter values
Value Meaning
SM_ARRANGEFlags specifying how the system arranged minimized windows. For more information about minimized windows, see the following Remarks section.
SM_CLEANBOOT Value that specifies how the system was started: 0 Normal boot1 Fail-safe boot2 Fail-safe with network bootFail-safe boot (also called SafeBoot, Safe Mode, or Clean Boot)
bypasses the user's startup files.
SM_CMONITORSWindows 98/Me, Windows 2000/XP: Number of display monitors on the desktop.
SM_CMOUSEBUTTONSNumber of buttons on mouse, or zero if no mouse is installed.
SM_CXBORDER, SM_CYBORDER
Width and height of a window border, in pixels. This is equivalent to the SM_CXEDGE value for windows with the 3-D look.
SM_CXCURSOR, SM_CYCURSOR
Width and height of a cursor, in pixels. The system cannot create cursors of other sizes.
SM_CXDLGFRAME, SM_CYDLGFRAME
Same as SM_CXFIXEDFRAME and SM_CYFIXEDFRAME.
SM_CXDOUBLECLK, SM_CYDOUBLECLK
Width and height of the rectangle around the location of a first click in a double-click sequence, in pixels. The second click must occur within this rectangle for the system to consider the two clicks a double-click. (The two clicks must also occur within a specified time.) To set the width and height of the double-click rectangle, call SystemParametersInfo with the SPI_SETDOUBLECLKHEIGHT and SPI_SETDOUBLECLKWIDTH flags.
SM_CXDRAG, SM_CYDRAG
Width and height of a rectangle centered on a drag point to allow for limited movement of the mouse pointer before a drag operation begins. These values are in pixels. It allows the user to click and release the mouse button easily without unintentionally starting a drag operation.
SM_CXEDGE, SM_CYEDGEDimensions of a 3-D border, in pixels. These are the 3-D counterparts of SM_CXBORDER and SM_CYBORDER.
SM_CXFIXEDFRAME, SM_CYFIXEDFRAME
Thickness of the frame around the perimeter of a window that has a caption but is not sizable, in pixels. SM_CXFIXEDFRAME is the height of the horizontal border and SM_CYFIXEDFRAME is the width of the vertical border. Same as SM_CXDLGFRAME and SM_CYDLGFRAME.
SM_CXFOCUSBORDER, SM_CYFOCUSBORDER
Windows XP: Width of the left and right edges and the height of the top and bottom edges of the focus rectangle drawn by DrawFocusRec. These values are in pixels.
SM_CXFRAME, SM_CYFRAME Same as SM_CXSIZEFRAME and SM_CYSIZEFRAME.
SM_CXFULLSCREEN, SM_CYFULLSCREEN
Width and height of the client area for a full-screen window on the primary display monitor, in pixels. To get the coordinates of the portion of the screen not obscured by the system taskbar or by application desktop toolbars, call the SystemParametersInfo function with the SPI_GETWORKAREA value.
SM_CXHSCROLL, SM_CYHSCROLL
Width of the arrow bitmap on a horizontal scroll bar, in pixels; and height of a horizontal scroll bar, in pixels.
SM_CXHTHUMB Width of the thumb box in a horizontal scroll bar, in pixels.
SM_CXICON, SM_CYICONDefault width and height of an icon, in pixels. The LoadIcon function can load only icons of these dimensions.
SM_CXICONSPACING, SM_CYICONSPACING
Dimensions of a grid cell for items in large icon view, in pixels. Each item fits into a rectangle of this size when arranged. These values are always greater than or equal to SM_CXICON and SM_CYICON.
SM_CXMAXIMIZED, SM_CYMAXIMIZED
Default dimensions, in pixels, of a maximized top-level window on the primary display monitor.
SM_CXMAXTRACK, SM_CYMAXTRACK
Default maximum dimensions of a window that has a caption and sizing borders, in pixels. This metric refers to the entire desktop. The user cannot drag the window frame to a size larger than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message.
SM_CXMENUCHECK, SM_CYMENUCHECK
Dimensions of the default menu check-mark bitmap, in pixels.
SM_CXMENUSIZE, SM_CYMENUSIZE
Dimensions of menu bar buttons, such as the child window close button used in the multiple document interface, in pixels.
SM_CXMIN, SM_CYMIN Minimum width and height of a window, in pixels.SM_CXMINIMIZED, SM_CYMINIMIZED
Dimensions of a minimized window, in pixels.
SM_CXMINSPACING SM_CYMINSPACING
Dimensions of a grid cell for a minimized window, in pixels. Each minimized window fits into a rectangle this size when arranged. These values are always greater than or equal to SM_CXMINIMIZED and SM_CYMINIMIZED.
SM_CXMINTRACK, SM_CYMINTRACK
Minimum tracking width and height of a window, in pixels. The user cannot drag the window frame to a size smaller than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message.
SM_CXSCREEN, SM_CYSCREEN
Width and height of the screen of the primary display monitor, in pixels. These are the same values obtained by calling GetDeviceCaps (hdcPrimaryMonitor, HORZRES/VERTRES).
SM_CXSIZE, SM_CYSIZEWidth and height of a button in a window's caption or title bar, in pixels.
SM_CXSIZEFRAME, SM_CYSIZEFRAME
Thickness of the sizing border around the perimeter of a window that can be resized, in pixels. SM_CXSIZEFRAME is the width of the horizontal border, and SM_CYSIZEFRAME is the height of the vertical border. Same as SM_CXFRAME and SM_CYFRAME.
SM_CXSMICON, SM_CYSMICON
Recommended dimensions of a small icon, in pixels. Small icons typically appear in window captions and in small icon view.
SM_CXSMSIZE SM_CYSMSIZE Dimensions of small caption buttons, in pixels.
SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN
Windows 98/Me, Windows 2000/XP: Width and height of the virtual screen, in pixels. The virtual screen is the bounding rectangle of all display monitors. The SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN metrics are the coordinates of the top-left corner of the virtual screen.
SM_CXVSCROLL, SM_CYVSCROLL
Width of a vertical scroll bar, in pixels; and height of the arrow bitmap on a vertical scroll bar, in pixels.
SM_CYCAPTION Height of a caption area, in pixels.SM_CYMENU Height of a single-line menu bar, in pixels.SM_CYSMCAPTION Height of a small caption, in pixels.SM_CYVTHUMB Height of the thumb box in a vertical scroll bar, in pixels.
SM_DBCSENABLEDTRUE or nonzero if the double-byte character-set (DBCS) version of User.exe is installed; FALSE or zero otherwise.
SM_DEBUGTRUE or nonzero if the debug version of User.exe is installed; FALSE or zero otherwise.
SM_IMMENABLED
Windows 2000/XP: TRUE or nonzero if Input Method Manager/Input Method Editor features are enabled; FALSE or zero otherwise. SM_IMMENABLED indicates whether the system is ready to use a Unicode-based IME on a Unicode application. To ensure that a language-dependent IME works, check SM_DBCSENABLED and the system ANSI code page. Otherwise the ANSI-to-Unicode conversion may not be performed correctly, or some components like fonts or registry setting may not be present.
SM_MENUDROPALIGNMENTTRUE or nonzero if drop-down menus are right-aligned with the corresponding menu-bar item; FALSE or zero if the menus are left-aligned.
SM_MIDEASTENABLEDTRUE if the system is enabled for Hebrew and Arabic languages.
SM_MOUSEPRESENTTRUE or nonzero if a mouse is installed; FALSE or zero otherwise.
SM_MOUSEWHEELPRESENTWindows NT 4.0 and later, Windows 98/Me: TRUE or nonzero if a mouse with a wheel is installed; FALSE or zero otherwise.
SM_NETWORKLeast significant bit is set if a network is present; otherwise, it is cleared. The other bits are reserved for future use.
SM_PENWINDOWSTRUE or nonzero if the Microsoft Windows for Pen computing extensions are installed; FALSE or zero otherwise.
SM_REMOTECONTROLWindows XP: This system metric is used in a Terminal Services environment. Its value is TRUE if the current session is remotely controlled; FALSE otherwise.
SM_REMOTESESSION Windows NT 4.0: This system metric is used in a Terminal Services environment. If the calling process is associated
with a Terminal Services client session, the return value is TRUE or nonzero. If the calling process is associated with the Terminal Server console session, the return value is zero.
SM_SECURE TRUE if security is present; FALSE otherwise.
SM_SAMEDISPLAYFORMAT
Windows 98/Me, Windows 2000/XP: TRUE if all the display monitors have the same color format, FALSE otherwise. Note that two displays can have the same bit depth, but different color formats. For example, the red, green, and blue pixels can be encoded with different numbers of bits, or those bits can be located in different places in a pixel's color value.
SM_SHOWSOUNDS
TRUE or nonzero if the user requires an application to present information visually in situations where it would otherwise present the information only in audible form; FALSE, or zero, otherwise.
SM_SHUTTINGDOWNWindows XP: TRUE if the current session is shutting down; FALSE otherwise.
SM_SLOWMACHINETRUE if the computer has a low-end (slow) processor; FALSE otherwise.
SM_SWAPBUTTONTRUE or nonzero if the meanings of the left and right mouse buttons are swapped; FALSE or zero otherwise.
SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN
Windows 98/Me, Windows 2000/XP: Coordinates for the left side and the top of the virtual screen. The virtual screen is the bounding rectangle of all display monitors. The SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN metrics are the width and height of the virtual screen.
TABLE 6
GetSystemMetrics(SM_CMONITORS) counts only display monitors. The SM_ARRANGE setting specifies
how the system arranges minimized windows, and consists of a starting position and a direction. The
starting position can be one of the following values.
Table 2.8 (b) Starting position values and direction of screen
Value MeaningARW_BOTTOMLEFT Start at the lower-left corner of the screen (default position).
ARW_BOTTOMRIGHTStart at the lower-right corner of the screen. Equivalent to ARW_STARTRIGHT.
ARW_HIDEHide minimized windows by moving them off the visible area of the screen.
ARW_TOPLEFTStart at the upper-left corner of the screen. Equivalent to ARV_STARTTOP.
ARW_TOPRIGHTStart at the upper-right corner of the screen. Equivalent to ARW_STARTTOP | SRW_STARTRIGHT.
TABLE 7
Table 2.8 (c) Lists the values of the direction in which to arrange the window.
Value MeaningARW_DOWNArrange vertically, top to bottom.ARW_LEFT Arrange horizontally, left to right.ARW_RIGHTArrange horizontally, right to left.ARW_UP Arrange vertically, bottom to top.TABLE 8
GetSysColor
The GetSysColor function retrieves the current color of the specified display element. Display elements
are the parts of a window and the display that appear on the system display screen. The function
returns the red, green, blue (RGB) color value of the given element. The parameter nIndex is used to
retrieve the color and can have one of the values listed in the Table 2.8(d). If the nIndex parameter is
out of range, the return value is zero. Because zero is also a valid RGB value, you cannot use
GetSysColor to determine whether a system color is supported by the current platform. Instead, use
the GetSysColorBrush function, which returns NULL if the color is not supported.
DWORD GetSysColor ( int nIndex);
Table 2.8 (d) Color values for GetSysColor function call
Value Meaning
COLOR_3DDKSHADOWDark shadow for three-dimensional display elements.
COLOR_3DFACE, COLOR_BTNFACEFace color for three-dimensional display elements and for dialog box backgrounds.
Highlight color for three-dimensional display elements (for edges facing the light source.)
COLOR_3DLIGHTLight color for three-dimensional display elements (for edges facing the light source.)
COLOR_3DSHADOW, COLOR_BTNSHADOW
Shadow color for three-dimensional display elements (for edges facing away from the light source).
COLOR_ACTIVEBORDER Active window border.
COLOR_ACTIVECAPTION
Active window title bar. Windows 98/Me, Windows 2000/XP: Specifies the left side color in the color gradient of an active window's title bar if the gradient effect is enabled.
COLOR_APPWORKSPACEBackground color of multiple document interface (MDI) applications.
COLOR_BACKGROUND, COLOR_DESKTOP
Desktop.
COLOR_BTNTEXT Text on push buttons.
COLOR_CAPTIONTEXTText in caption, size box, and scroll bar arrow box.
COLOR_GRADIENTACTIVECAPTION
Windows 98/Me, Windows 2000/XP: Right side color in the color gradient of an active window's title bar. COLOR_ACTIVECAPTION specifies the left side color. Use SPI_GETGRADIENTCAPTIONS with the SystemParametersInfo function to determine whether the gradient effect is enabled.
COLOR_GRADIENTINACTIVECAPTION
Windows 98/Me, Windows 2000/XP: Right side color in the color gradient of an inactive window's title bar. COLOR_INACTIVECAPTION specifies the left side color.
COLOR_GRAYTEXTGrayed (disabled) text. This color is set to 0 if the current display driver does not support a solid gray color.
COLOR_HIGHLIGHT Item(s) selected in a control.COLOR_HIGHLIGHTTEXT Text of item(s) selected in a control.
COLOR_HOTLIGHTWindows 98/Me, Windows 2000/XP: Color for a hot-tracked item. Single clicking a hot-tracked item executes the item.
COLOR_INACTIVEBORDER Inactive window border.
COLOR_INACTIVECAPTION
Inactive window caption. Windows 98/Me, Windows 2000/XP: Specifies the left side color in the color gradient of an inactive window's title bar if the gradient effect is enabled.
COLOR_INACTIVECAPTIONTEXT Color of text in an inactive caption.COLOR_INFOBK Background color for tooltip controls.COLOR_INFOTEXT Text color for tooltip controls.COLOR_MENU Menu background.
COLOR_MENUHILIGHT
Windows XP: The color used to highlight menu items when the menu appears as a flat menu. The highlighted menu item is outlined with COLOR_HIGHLIGHT.
COLOR_MENUBAR
Windows XP: The background color for the menu bar when menus appear as flat menus. However, COLOR_MENU continues to specify the background color of the menu popup.
COLOR_MENUTEXT Text in menus.
COLOR_SCROLLBAR Scroll bar gray area.COLOR_WINDOW Window background.COLOR_WINDOWFRAME Window frame.COLOR_WINDOWTEXT Text in windows.TABLE 9
SetSysColors
The SetSysColors function sets the colors for one or more display elements. Display elements are the
various parts of a window and the display that appear on the system display screen.
Compile, Build and Execute the program. The output of the program is shown in figure 2.16.
Figure 2.16 Running Instance of MouseKeyMsg Program
Exercises 2
1. What is GDI?
2. Define DC.
3. What is WM_PAINT Message?
4. List the Paint Structure (PAINTSTRUCT) and explain it.
5. Write the syntax of TextOut function.
6. Define System Metrics.
7. What is Client area and Non Client area.
8. What are the GDI Primitives?
9. List out the Pen and Brush Styles.
10. Write a Windows Program to draw a Bezier Spline.
11. List out the Mouse and Keyboard Messages.
12. Write a Windows Program to draw a Sine Wave.
Chapter 3
Windows Controls and Resources
3.1 Child Window Controls
Windows provides several predefined window classes which we can readily use in our own programs.
Most of the time we use them as components of a dialog box so they're usually called child window
controls. The child window controls process their own mouse and keyboard messages and notify the
parent window when their states have changed. They relieve the burden from programmers
enormously so you should use them as much as possible. Controls can be placed on a normal window
by using the Create command with various styles to design them. But in reality you should put them in
a dialog box.
Examples of predefined window classes are buttons, listbox, checkboxes, radio buttons, edit controls,
etc.
In order to use a child window control, you must create it with win.CreateWindow or
win.CreateWindowEx. Note that you don't have to register the window class since it's registered for
you by Windows. The class name parameter MUST be the predefined class name. Say, if you want to
create a button, you must specify "button" as the class name in win.CreateWindowEx. The other
parameters you must fill in are the parent window handle and the control ID. The control ID must be
unique among the controls. The control ID is the ID of that control. You use it to differentiate between
the controls.
After the control was created, it will send messages notifying the parent window when its state has
changed. Normally, you create the child windows during win.WM_CREATE message of the parent
window. The child window sends win.WM_COMMAND messages to the parent window with its control ID
in the low word of wParam, the notification code in the high word of wParam, and its window handle in
lParam. Each child window control has different notification codes, refer to your Win32 API reference
for more information.
The parent window can send commands to the child windows too, by calling win.SendMessage
function. win.SendMessage function sends the specified message with accompanying values in
wParam and lParam to the window specified by the window handle. It's an extremely useful function
since it can send messages to any window provided you know its window handle.
So, after creating the child windows, the parent window must process win. WM_COMMAND messages
to be able to receive notification codes from the child windows. The examples in this chapter uses
dialog box to place various controls.
3.2 Button Class
Buttons are Windows Controls that respond to user clicks. They are created with the CreateWindow or
CreateWindowEx Window function. They can have a variety of styles as shown below:
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_AUTO3STATE Same as a three-state check box,
except that the box changes its state when the user
selects it.
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_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_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_PUSHBUTTON Creates a pushbutton that posts a
WM_COMMAND message to the owner window when the
user selects the button.
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_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.
3.2.1 Communication between Child and Parent Windows
When you click a button with the mouse the child window control sends a WM_COMMAND message to
its parent window. The program traps the WM_COMMAND message and displays the values of wparam
(child window ID and notification code) and lparam (child window handle). The notification code
indicates in more detail what the message means. The possible button notification messages are:
BN_CLICK
BN_DBCLICK
BN_PAINT
BN_KILLFOCUS
BN_HILITE
BN_UNHILITE
BN_PUSHED
BN_UNPUSHED
BN_DISABLE
BN_SETFOCUS
BN_KILLFOCUS
In addition to the notification messages mentioned above there are also button messages each begins
with letter BM. These messages are used by the window procedure to send messages to the child
window control. The button messages are:
BM_GETCHECK
BM_GETIMAGE
BM_GETSTATE
BM_SETCHECK
BM_SETIMAGE
BM_SETSTYLE
BM_CLICKED
3.2.2 Push Buttons
A small rectangular control that a user can turn on or off. A push button, also known as a command
button, has a raised appearance in its default off state and a depressed appearance when it is turned
on. Push button controls are used to trigger an immediate action without retaining any type of on/off
indication. The rectangle takes up the full height and width of the dimension given in the
CreateWindow. There are two types of push buttons BS_PUSHBUTTON and BS_DEFPUSHBUTTON where
“DEF” stands for default.
An application sends a BM_SETSTATE message to change the highlight state of a button. The highlight
state indicates whether the button is highlighted as if the user had pushed it.
BM_SETSTATE message syntax:
wParam = (WPARAM) fstate; // highlight state
lParam = 0; // not used; must be zero
where fState is the value of wParam and specifies whether the button is to be highlighted. A value of
TRUE or nonzero highlights the button. A value of FALSE or zero removes any highlighting.
This message always returns zero. Highlighting only affects the appearance of a button. It has no
effect on the check state or a radio button or check box. A button is automatically highlighted when
the user positions the cursor over it and presses and holds the left mouse button. The highlighting is
removed when the user releases the mouse button.
This call causes the button to be depressed:
SendMessage(hwndButton,BM_SETSTATE,1,0);
To return to the normal state the call to be used is:
SendMessage(hwndButton,BM_SETSTATE,0,0);
The hwndButton window handle is the value returned from the CreateWindow call. You can also send a
BM_GETSTATE message to push button. An application sends a BM_GETSTATE message to determine
the state of a button or check box. The value TRUE is returned if the button is depressed and FALSE if
it is not depressed. Most applications do not require this information.
BM_GETSTATE message syntax:
wParam = 0; // not used; must be zero
lParam = 0; // not used; must be zero
The BM_SETCHECK and BM_GETCHECK messages are not used by push button because they do not
retain on/off information.
3.2.3 Check Boxes
An interactive control found in graphical user interfaces. Check boxes are used to enable or disable
one or more features or options from a set. When an option is selected, an X or a check mark appears
in the box. The two most common styles of check box are BS_CHECKBOX and BS_AUTOCHECKBOX. You
can set the check state of the check box with the message BM_SETCHECK.
BM_SETCHECKMESSAGE has two parameters:
wParam = (WPARAM)fcheck; // check state
lParam = 0; // not used; must be zero
where fCheck is the value of wParam.and specifies the check state. This parameter can be one of the
values mentioned in Table 3.2.3.
Table 3.2.3 Values for fCheck Parameter
Value MeaningBST_CHECKED Sets the button state to checked.
BST_INDETERMINATESets the button state to grayed, indicating an indeterminate state. Use this value only if the button has the BS_3STATE or BS_AUTO3STATE style.
BST_UNCHECKED Sets the button state to cleared.TABLE 11
You can initialize a check box with a check mark by sending BM_SETCHECK message:
SendMessage(hwndButton,BM_SETCHECK,1,0);
For BS_AUTOCHECKBOX style the button control itself toggles the check mark on and off. When the
current state of the button is needed send the control a BM_GETCHECK message:
Highlight color for three-dimensional display elements (for edges facing the light source.)
COLOR_3DLIGHTLight color for three-dimensional display elements (for edges facing the light source.)
COLOR_3DSHADOW, COLOR_BTNSHADOWShadow color for three-dimensional display elements (for edges facing away from the light source).
COLOR_ACTIVEBORDER Active window border.COLOR_ACTIVECAPTION Active window title bar.
COLOR_APPWORKSPACEBackground color of multiple document interface (MDI) applications.
COLOR_BACKGROUND, COLOR_DESKTOP Desktop.COLOR_BTNTEXT Text on push buttons.
COLOR_CAPTIONTEXTText in caption, size box, and scroll bar arrow box.
COLOR_GRAYTEXTGrayed (disabled) text. This color is set to 0 if the current display driver does not support a solid gray color.
COLOR_HIGHLIGHT Item(s) selected in a control.COLOR_HIGHLIGHTTEXT Text of item(s) selected in a control.COLOR_INACTIVEBORDER Inactive window border.COLOR_INACTIVECAPTION Inactive window caption.COLOR_INACTIVECAPTIONTEXT Color of text in an inactive caption.COLOR_INFOBK Background color for tooltip controls.COLOR_INFOTEXT Text color for tooltip controls.COLOR_MENU Menu background.COLOR_MENUTEXT Text in menus.COLOR_SCROLLBAR Scroll bar gray area.COLOR_WINDOW Window background.COLOR_WINDOWFRAME Window frame.COLOR_WINDOWTEXT Text in windows.TABLE 12
The SetSysColors function sets the colors for one or more display elements. Display elements are the
various parts of a window and the display that appear on the system display screen.
WINAPI SetSysColors(
int cElements, // number of elements to change
CONST int *lpaElements, // address of array of elements
CONST COLORREF *lpargbValues // address of array of RGB values
);
3.2.8 List Box Class
The list box is a window that displays a list of character strings. The user selects a string from the list
by tapping it with the stylus. When a string is selected, it appears highlighted. You can use a vertical or
horizontal scroll bar with a list box to scroll lists that are too long for the control window. The list box
automatically hides or shows the scroll bar, as needed.
Messages
As you may remember from our earlier discussion of the message loop, windows communicate using
messages, you send them to get a control to do something, and when an event occurs on the control it
will send you a notification message back. For the standard controls this notification will be a
WM_COMMAND message as we've already seen with buttons and menus. For the Common Controls
which I may get to later, it will be WM_NOTIFY.
The messages you send are widely varied between each control, and each control has it's own set of
messages. Once in a while the same message will be used for more than one kind of control, but in
general they will only work on the control they are intended for. This is especially annoying with the
listbox and combobox messages (LB_* and CB_*) which although they perform nearly identical tasks,
are NOT interchangeable.On the other hand, generic messages like WM_SETTEXT are supported by
almost all controls. A control is just a window after all.
You can send messages using the SendMessage() API, and use GetDlgItem() to retreive the handle to
the control, or you can use SendDlgItemMessage() which does both steps for you, the results of both
methods are identical.
Adding Items to list box
The first thing you'll want to do with a listbox is add items to it.
int index = SendDlgItemMessage(hwnd, IDC_LIST, LB_ADDSTRING, 0, (LPARAM)"Hi there!");
As you can see, this is a pretty simple task. If the listbox has the LBS_SORT style, the new item will be
added in alphabetical order; otherwise it will just be added to the end of the list.
This message returns the index of the new item either way, and we can use this to perform other tasks
on the item, such as associating some data with it. Usually this will be things like a pointer to a struct
containing more information, or maybe an ID that you will use to identify the item, it's up to you.
LoadIcon returns a value of type HICON, a handle to an icon. The parameters
hInstance is a handle to an instance of the module whose executable file contains the
icon to be loaded. This parameter must be NULL when a standard icon is being loaded
and MAKEINTRESOURCE contains the name of the icon resource to be loaded. To use
one of the predefined icons, set the hInstance parameter to NULL and the second
parameter to one of the values in Table 3.3.1.
Table 3.3.1 Second Parameter values for LoadIcon
Value DescriptionIDI_APPLICATION Default application icon.IDI_ASTERISK Same as IDI_INFORMATION.IDI_ERROR Hand-shaped icon.IDI_EXCLAMATIONSame as IDI_WARNING.IDI_HAND Same as IDI_ERROR.
IDI_INFORMATION Asterisk icon.IDI_QUESTION Question mark icon.IDI_WARNING Exclamation point icon.IDI_WINLOGO Windows logo icon.TABLE 13
The icon created can be displayed in its client area, repeated horizontally and vertically using the
statement LoadIcon and obtains a handle to the icon using the statements:
cxIcon = GetSystemMetrics (SM_CXICON);
cyIcon = GetSystemMetrics (SM_CYICON);
It obtains the size of the icon. The program can then display the icon with multiple calls to
DrawIcon (hdc , x , y ,hIcon);
Where x and y coordinates of where the upper left corner of the displayed icon is positioned. The
smaller icon size can also be obtained from the system metrics SM_CXSMSIZE and SM_CYSMSIZE
indices. The first SM means system metrics and the second SM means small.
Example program for icon demo
Create an application named IconDemo by selecting the project type Win 32 Application in the
appwizard and click OK. Now an empty project without using MFC classes is created.
Click Insert->Resource from the menu and then select the Icon option. Design the Icon as shown in
figure 3.3.1(a).
Figure 3.3.1(a) Icon design for the program
Save the icon design in your project and then include the .rc and resource.h header file to your project
workspace. Change the ID for Icon as ID_ICON Click File->New and then select the option C++ Source
File and give a name to the .cpp implementation file (here the name is Icon.cpp). Enter the code given
Compile, Build and Execute the Program. The output is as shown in figures 3.3.3(a) and 3.3.3(b). Click
the menu item Stuff. The message is displayed as shown in figure 3.3.3(b)
Figure 3.3.3(a) Running Instance of Menu program
Figure 3.3.3(b) Running Instance of Menu program
3.3.4 Dialog Box
A dialog box is a temporary window that contains controls. You can use it to display status information and to get user input. Just go File -> Open in any text editor or any other kind of editor; you are presented with a dialog box, one that probably allows you to select a file to be opened. Dialogs aren't limited to the standard open file ones; they can look like and do whatever you choose. The attractive point of dialogs is that they provide a quick way to arrange and create a GUI (Graphic User Interface) and even some default processing, cutting down on the amount of code you must write.
One thing to remember is that dialogs are just windows. The difference between a dialog and a
"normal" window is that the system does some additional default processing for dialogs, such as
creating and initializing controls, and handling tab order. Nearly all APIs that are applicable to "normal"
windows will work just as well on dialogs, and vice versa! There are two types of dialog box such as
“modal” and “modeless” dialog box. The modal dialog box is the most common. When your program
displays a modal dialog box the user must explicitly end the dialog box by clicking a push button
marked either OK or Cancel. The user can switch to another program while the dialog box is still
displayed.
The first step is to create the dialog resource. As with any resource how you do this will depend on
your compiler/IDE. Here I will show you the plain text of the dialog in the .rc file and let you incorporate
Compile, Build and Execute the program. The output is as shown in figure 3.3.6(b).
Figure 3.3.6(b) Running Instance of Bitmap Program
Exercises 3
1. What are the various button styles that
can be used in Windows Programming?
2. Explain the functions SetDlgItemText
and GetDlgItemText.
3. Explain the List Box and Scroll Bar Class.
4. Explain the LoadIcon and LoadBitmap
functions.
5. Explain SetMenu and LoadMenu
functions.
6. What are the advantages of using Dialog
Box?
7. Differentiate Modal Dialog and Modeless
Dialog.
8. Explain the BitBlt function.
9. Write a Windows program to add and
removo items in a List box.
10. Write a Windows program to display a
Bitmap in the centre of the screen.
Content actions
SHARE CONTENT
SHARE MODULE:
GIVE FEEDBACK:
E-mail the module author
DOWNLOAD MODULE AS:
PDF | EPUB (?)
WHAT IS AN EPUB FILE?
EPUB is an electronic book format that can be read on a variety of mobile devices.
DOWNLOADING TO A READING DEVICE
For detailed instructions on how to download this content's EPUB to your specific device, click the"(?)"link.
| More downloads ...
ADD MODULE TO:
My Favorites Login Required(?) 'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.
| A lens I own Login Required(?)
Definition of a lens
LensesA lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.
What is in a lens?Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.
Who can create a lens?Any individual member, a community, or a respected organization.
What are tags?
Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.
| External bookmarks
REUSE / EDIT:
Reuse or edit module Login Required(?)Check out and editIf you have permission to edit this content, using the "Reuse / Edit" action will allow you to check the content out into your Personal Workspace or a shared Workgroup and then make your edits.
Derive a copyIf you don't have permission to edit the content, you can still use "Reuse / Edit" to adapt the content by creating a derived copy of it and then editing and publishing the copy.
Footer
More about this module: Metadata | Downloads | Version History
How to reuse and attribute this content
How to cite and attribute this content
This work is licensed by Avanija j under a Creative Commons Attribution License (CC-BY 2.0), and is an Open Educational Resource.
Last edited by Avanija j on Apr 4, 2007 12:57 pm GMT-5.