Skip to content Skip to navigation

Connexions

You are here: Home » Content » VC++ Tutorial for Beginners

Navigation

Content Actions

  • Download module PDF
  • Add to ...
    Add the module to:
    • My Favorites
    • A lens
    • An external social bookmarking service
    • My Favorites (What is 'My Favorites'?)
      'My Favorites' is a special kind of lens which you can use to bookmark modules and collections directly in Connexions. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need a Connexions account to use 'My Favorites'.
    • A lens (What is a lens?)

      Definition of a lens

      Lenses

      A lens is a custom view of Connexions content. You can think of it as a fancy kind of list that will let you see Connexions through the eyes of organizations and people you trust.

      What is in a lens?

      Lens makers point to Connexions 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 Connexions member, a community, or a respected organization.

    • External bookmarks
  • E-mail the author

Recently Viewed

VC++ Tutorial for Beginners

Module by: Avanija j

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:

graphics1.pngAdvantages 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.

graphics2.png
The Windows 1.0 product box showed the new tiled windows and graphical user interface in the operating system
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.

graphics3.jpg
Even before the Windows 1.0 graphical user interface, there was this pre-Windows 1.0 Interface Manager

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.

graphics4.jpg
Windows 3.0 featured a new File Manager

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.

graphics5.png
Windows NT 3.1 contained overlapping windows and other features similar to Windows 3.1

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
Figure 1 (graphics6.png)
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. graphics7.pngFigure 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,

int nCmdShow)

{int i;

MessageBox(0,"Application executing","Application",MB_OK);

return(0);

}

graphics8.png

Figure 2.10(a) Sample Output

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 Function
h Handle
i int(integer)
l Long
n Short(int) or near pointer
p Pointer
s Character string
sz Character string terminated by zero
w Word(two bytes)

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

lstrcpy

Copies a string to a buffer.

Syntax

LPSTR lstrcpy(LPSTR lpszString1,LPSTR lpszString2);

The first parameter lpszString1 is the Pointer to a buffer to receive the contents of the string pointed to by the lpszString2 parameter. The buffer must be large enough to contain the string, including the terminating wide null character. The second parameter lpszString2 is the pointer to the null-terminated wide string to be copied. This function returns a pointer to the buffer. Similarly two wide strings can be copied using the function lstrcpyW.

lstrcpyn

Copies a string to a buffer, up to a specified number of characters.

Syntax

LPSTR lstrcpyn(LPSTR lpszString1,LPSTR lpszString2,int iMaxLength);

The first parameter lpszString1 is the pointer to a buffer to receive the contents of the string that the lpszString2 parameter points to. The buffer must be large enough to contain the string, including the terminating wide null character. The second parameter lpszString2 is the pointer to the null-terminated string to be copied. The third parameter iMaxLength gives the maximum number of characters to copy, including a terminating null character. This function returns a pointer to the buffer. If iMaxLength is nonzero, lstrcpyn always inserts a terminating null character in the destination string, which could result in the source string being truncated. Similarly lstrcpynW copies a wide string to a buffer, up to a specified number of wide characters.

lstrlen

Retrieves the length of the specified string.

Syntax

int lstrlen(LPSTR lpszString);

The first parameter lpszString is the pointer to a null-terminated wide string. If the function succeeds, the return value specifies the length of the string. Similarly lstrlenW retrieves the length of the specified wide string.

1.16 The Sample SDK Program

Creating a window first requires registering a window class and that requires a window procedure to process messages to the window. This involves a bit of overhead that appears in almost every windows program. The program shown below is a simple program that handles only three windows messages(two mouse click messages and a quit message). Figure 1.16(a) shows the applications only window.

graphics9.png

Figure 1.16 (a) A Minimal Windows Program written using SDK

// Sample SDK program to display window

#include <windows.h>

WNDCLASS wc;

MSG msg;

HWND hwnd;

LRESULT CALLBACK wndproc(HWND,UINT,WPARAM,LPARAM);

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,

int nCmdShow)

{

wc.style=CS_HREDRAW|CS_VREDRAW;

wc.lpfnWndProc=wndproc;

wc.hInstance=hInstance;

wc.hCursor=LoadCursor(hInstance,IDC_ARROW);

wc.hIcon=LoadIcon(hInstance,NULL);

wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);

wc.lpszClassName ="Sample";

wc.lpszMenuName =NULL;

if (!RegisterClass(&wc))

return false;

hwnd=CreateWindow(“Sample”,”AsampleSDK Window”,

WS_OVERLAPPEDWINDOW,//window style

CW_USEDEFAULT, //initial x position

CW_USEDEFAULT, //initial y position

CW_USEDEFAULT, //initial x size

CW_USEDEFAULT, //initial y size

NULL,//parent window handle

NULL,//window menu handle

HINSTANCE,//program instance handle

NULL);//creation parameters

ShowWindow(hwnd,nCmdShow);

UpdateWindow(hwnd);

while(GetMessage(&msg,NULL,0,0))

{

TranslateMessage(&msg);

DispatchMessage(&msg);

}

return true;

}

LRESULT CALLBACK wndproc(HWND hwnd,UINT wm,WPARAM wp,LPARAM lp)

{

char left[]="You have pressed left mouse button";

char right[]="You have pressed right mouse button";

switch(wm)

{

case WM_LBUTTONDOWN:

{

MessageBox(GetFocus(),left,"About",MB_OK|MB_ICONINFORMATION);

break;

}

case WM_RBUTTONDOWN:

{

MessageBox(GetFocus(),right,"About",MB_OK|MB_ICONINFORMATION);

break;

}

case WM_DESTROY:

{

PostQuitMessage(0);

return 0;

}

default:

break;

}

return(DefWindowProc(hwnd,wm,wp,lp));

}

graphics10.png

Figure 1.16 (b) The sample SDK program responding to a left mouse click message

1.16.1Dissecting the Program

The code for this program deserves a closer examination. The program starts with #include<windows.h>. This statement includes the main windows header file(WINDOWS.H) that in turn includes all the windows header file that contain structures, macros, API prototypes and everything else that the SDK program needs. Then the two SDK functions declared are: the program entry point WinMain() and the application’s window procedure in this case wndproc. However there is a reference to wndproc in WinMain, which is why the function is declared near the top of the program.

Windows function calls

The sample SDK windows program makes calls to fewer windows functions. These functions with a brief description are:

  • Load IconLoads an icon for use by a program.
  • Load CursorLoads a mouse cursor for use by a program.
  • GetStockObjectObtains a graphic object in this case a brush used for painting the windows background.
  • RegisterClassRegisters a window class for the program’s window
  • MessageBoxDisplays a message box.
  • CreateWindowCreates a window based on a window class.
  • ShowWindowShows the window on the screen.
  • UpdateWindowDirects the window to paint itself.
  • GetMessageObtains a message from message queue.
  • TranslateMessage Translates some keyboard messages.
  • DispatchMessage Sends a message to a window procedure.
  • PostQuitMessage To insert a “quit” message in to the message queue.
  • DefWindowProc Performe default processing of messages.

Window Class Structure(WNDCLASS)

The WNDCLASS structure is used to define all windows that you can view on your monitor. The structure of a window class looks like this:

typedef struct_WNDCLASS

{UINT style; //window class style

WNDPROC lpfnWndProc; //window procedure

int cbLlsExtra; //extra class bytes

int cbWndExtra; //extra window bytes

HANDLE hInstance; // instance handle

HICON hIcon; // icon handle

HCURSOR hCursor; // cursor handle

HBRUSH hbrBackground; // background brush color

LPCTSTR lpszMenuName; // menu resource

LPCTSTR lpszClassName; // window class name

}WNDCLASS ;

Message Structure

Because almost everything in windows happens in response to messages, the windows message structure MSG is extremely important. This structure is defined as follows:

typedef Struct tagMsg

{HWND hwnd; // handle of the windows to retrieve messages

UINT message; // message value for each windows identified by macros in WINDOWS.H

WPARAM wp; // additional information about the message

DWORD time; //time at which the message was posted to the queue

POINT pt; // screen coordinates of the cursor when the message was posted

}MSG;

Uppercase Identifiers

These identifiers are defined in the windows header files. The identifiers contain a two-letter or three-letter prefix followed by an underscore:

CS_HREDRAWDT_VCENTERSND_FILENAME

CS_VREDRAWIDC_ARROWWM_CREATE

CW_USEDEFAULTIDI_APPLICATIONWM_DESRTOY

DT_CENTERMB_ICONERRORWM_PAINT

DT_SINGLENAMESND_ASYNCWS_OVERLAPPEDWINDOW

These are simply numeric constants. The prefix indicates a general category to which the constant belongs.

  • CS Class style option
  • CW Create window option
  • DT Draw text option
  • IDI ID number for an icon
  • IDC ID number for a cursor
  • MB Message box options
  • SND Sound option
  • WM Window message
  • WS Window style

Initializing and Registering the Window Class

Windows allows multiple instances of a single application to run concurrently each application window has a window class. A window class must be initialized and registered when the first instance begins execution. If there are no previous instances of the application running the WNDCLASS structure variable wc is initialized with values and registered with windows by calling the RegisterClass() API function with a pointer to wc as the only parameter. Here is the way to handle the RegisterClass function call:

if(!RegisterClass(&wc)

return false;

In some sample windows programs you may see the following code in WinMain:

If(!hPrevInstance)

{wc.style=CS_HREDRAW | CS_VREDRAW;

[ other wndclass initialization]

RegisterClass(&wc);

}

This declaration is necessary only for 16 bit version of windows, if you started up a new instance of a program that was already running then the hPrevInstance parameter should be the instance handle of the previous instance. The window class can be registered only if hPrevInstance was NULL, indicating no other instances of the program were running. But in 32 bit versions of windows hPrevInstance is always NULL, it is not necessary to check hPrevInstance.

Creating the Window

The application window is created by calling the API function CreateWindow(). The CreateWindow() function takes 11 parameters. Here’s the CreateWindow call with comments identifying the parameters.

hwnd=CreateWindow( SZAPPNAME, // window class name

SZAPPTITLE, // window caption

WS_OVERLAPPEDWINDOW, // window style

CW_USEDEFAULT, // initial x position

CW_USEDEFAULT, // initial y position

CW_USEDEFAULT, // initial x size

CW_USEDEFAULT, // initial y size

NULL, // parent window handle

NULL, // window menu handle

HINSTANCE, // program instance handle

NULL); //creation parameters

The window created by this program is a normal overlapped window. It will have a title bar, system menu button to the left of the title bar, a thick window sizing border and minimize, maximize and close buttons to the right of the title bar. This is the standard style for windows. By using the identifier CW_USEDEFAULT to indicate (initial x , y position and initial x , y size) we are indicating that we want windows to use the default position for an overlapped window.

The argument marked “parent window handle” is to set to NULL when creating a “top level” window such as an application window. Normally, when a parent-child relationship exists between two windows the child window always appears on the surface of its parent. The “window menu handle” is also set to NULL because the window has no menu. The “program instance handle” is set to the instance handle passed to the program as a parameter of WinMain. Finally a “creation parameter” is set to NULL. The CreateWindow function call returns a handle to created window which is stored in the variable hwnd. It is defined to be of type HWND (handle to a window).

Displaying the Window

After the CreateWindow call returns the window has been created internally in windows. However the windows do not yet appear on the video display, two more calls are needed. They are:

ShowWindow(hwnd,nCmdShow);

UpdateWindow(hwnd);

The ShowWindow call determines how to display the window on the screen., whether it is normal, minimized or maximized. The first argument is the handle to the window just created by CreateWindow. The second argument nCmdShow is the value passed as a parameter to WinMain which determines how the window is to be internally displayed on the screen whether it is normal, minimized or maximized. This can be done by defining the second parameter to have one of the fields given below:

  • SW_SHOWMAXIMIZED - To display maximized window.
  • SW_SHOWMINIMIZED – To display minimized window.
  • SW_SHOWNORMAL – To display normal window.
  • SW_SHOWMINOACTIVE – To display the window in task bar.

If the second argument to ShowWindow is SW_SHOWNORMAL the client area of the window is erased with background brush specified in the window class. The function call UpdateWindow causes the client area to be painted.

Window Procedure

The window procedure determines what the window displays in its client area and how the window responds to user input. A windows program can contain more than one window procedure. The window procedure can be defined like this:

LRESULT CALLBACK wndproc(HWND hwnd, UINT message, WPARAM wp, LPARAM lp)

These parameters are identical to the first four fields of the MSG structure. The first parameter hwnd is the handle to window receiving the message. If a program creates multiple windows based on the same window class and hence the same window procedure, hwnd identifies the particular window receiving the message. The second parameter is a number that identifies the message. The last two parameters are 32 bit message parameters that provide more information about the message.

Handling Messages in Window Procedure

After the UpdateWindow call the window is fully visible in the screen. The program must now make itself ready to read input from the user through mouse and keyboard. Message queue is maintained for each windows program currently running under windows. When an input event occurs windows translates the event in to a message that it places in the message queue. The messages can be retrieved from the message queue by executing the message loop:

While(GetMessage(&msg,NULL,0,0))

{ TranslateMessage(&msg);

DispatchMessage(&msg);

}

The GetMessage call retrieves a message from a message queue and passes to window a pointer to a MSG structure named msg.

The TranslateMessage call passes the msg structure back to windows for some keyboard translation.

The DispatchMessage call passes the msg structure back to windows and the windows then sends the message to the appropriate window procedure for processing.

Every message that window procedure receives is identified by a number. This is defined with the identifiers beginning with the prefix WM(Window Message) for each type of message. This can be done through switch and case statement. To process a message, the window procedure should return 0. All the messages not to be processed must be passed to a windows function named DefWindowProc. The value returned from DefWindowProc must be returned from the window procedure. In the sample windows program, wndproc chooses to process four messages: WM_CREATE, WM_LBUTTONDOWN, WM_RBUTTONDOWN and WM_DESTROY. The messages can be defined like this:

switch(msg)

{ case WM_CREATE:

[process WM_CREATE message]

return 0;

case WM_LBUTTONDOWN :

[process WM_LBUTTONDOWN message]

return 0;

case WM_RBUTTONDOWN :

[process WM_RBUTTONDOWN message]

return 0;

case WM_DESTROY :

[process WM_DESTROY message]

return 0;

}

return DefWindowProc(hwnd,msg,wp,lp);

Windows Messages

Windows messages are sent by Windows to your application. These messages begin with the WM_ prefix. The WM_* messages are sent by windows and are usually handled by windows and views, some of the commonly processed windows messages are: WM_COMMAND, WM_CHAR, WM_DESTROY and WM_QUIT message.

WM_COMMAND Message

This message notifies the program that the user has selected a menu item, a child window control or has used an accelerator key. An accelerator key is a key combination which is used to invoke the options of a menu and other controls.

WM_CHAR Message

This message is used to retrieve ASCII keyboard inputs such as letters, numbers and printable symbols. This message is generated when the user presses a character with an ASCII value on keyboard.

WM_DESTROY Message

This message notifies the program that a window is being destroyed after it is removed from the screen. The message is sent after the window image is removed from the screen. For example WM_DESTROY is sent to the parent window before a child window is destroyed.

WM_QUIT Message

This message indicates a request to terminate an application and is done when the application calls the PostQuitMessage function. It causes the GetMessage function to return a zero and drop out from message loop. The return statement exits from WinMain and terminates the program.

Exercises 1

  1. Differentiate Structured Programming and Object Oriented Programming.
  2. Define Object and Class.
  3. Explain the Windows Programming Model.
  4. What is DLL?
  5. What is API?
  6. Explain the GUI concepts.
  7. Write short notes on Event Driven Programming.
  8. What is Hungarian Notation?
  9. Write short notes on Windows String Functions.
  10. Explain the Message function calls used in Windows Programming.
  11. Write the Window Class structure, Message structure and explain them.
  12. Explain how to register the Window class.
  13. List out the options available to display the Window.
  14. Write short notes on Window Procedure.
  15. Write about the Windows Messages.

Chapter – 2

Basics of GDI and DC

2.1Graphics Device Interface (GDI)

The graphics device interface (GDI) provides functions and related structures that an application can use to generate graphical output for displays, printers, and other devices. Using GDI functions, you can draw lines, curves, closed figures, paths, text, and bitmap images. The color and style of the items you draw depends on the drawing objects — that is, pens, brushes, and fonts — that you create. You can use pens to draw lines and curves, brushes to fill the interiors of closed figures, and fonts to write text.

Applications direct output to a specified device by creating a device context (DC) for the device. The device context is a GDI-managed structure containing information about the device, such as its operating modes and current selections. An application creates a DC by using device context functions. GDI returns a device context handle, which is used in subsequent calls to identify the device. For example, using the handle, an application can retrieve information about the capabilities of the device, such as its technology type (display, printer, or other device) and the dimensions and resolution of the display surface.

Applications can direct output to a physical device, such as a display or printer, or to a "logical" device, such as a memory device or metafile. Logical devices give applications the means to store output in a form that is easy to send subsequently to a physical device. After an application records output in a metafile, it can play that metafile any number of times, sending the output to any number of physical devices.

Applications use attribute functions to set the operating modes and current selections for the device. The operating modes include the text and background colors, the mixing mode (also called the binary raster operation) that specifies how colors in a pen or brush combine with colors already on the display surface, and the mapping mode that specifies how GDI maps the coordinates used by the application to the coordinate system of the device. The current selections identify which drawing objects are used when drawing output. Figure 2.1 shows the diagrammatic representation of GDI.

graphics11.png graphics12.png graphics13.png

Application obtains aGDI uses DC to locate

DC “handle” from the correct window or

Windows GDI anddevice driver and perform

Passes it to all GDIrequested function.

Functions

Figure 2.1 Graphics Device Interface

2.2 Device Context

Returns an integer that identifies the device-context of window if it has one, or nil otherwise. A device-context is a construct used in the Windows API to specify a set of parameters that are used when drawing on a window. A common graphics application does not normally need to deal with a window's device-context directly, but if you need to pass the window to a WINAPI function that calls for the window's device-context (or hDC), then you should pass the integer returned by this function for that argument. Every non-control window in common graphics (and every lisp-widget window) is automatically assigned a device-context, which it keeps until it is closed. Controls supplied by the OS (all controls except lisp-widgets), on the other hand, are not automatically given device-contexts in lisp since it is normally only the OS rather than lisp that draws on the control. If you do want to draw directly on a non-lisp control, then you must give the window of the control a device-context while drawing on it.

2.3 The WM_PAINT message

The WM_PAINT message is a request to repaint the window. Every application is responsible for redrawing its window(s). This means that the application will have to keep track of the current state, so that it knows that to draw. In most cases, the WM_PAINT message will be triggerd from the outside. However, it is also possible to trigger WM_PAINT from inside the application. With the Invalidate() function, you can tell that the contents of a window are no longer valid so that it will need to be redrawn. With the InvalidateRect() function, you can specify that only part of the window content is invalid, so that only that part will be redrawn. In this way, you can prevent the flickering of the screen when redrawing. Because paint message have very low priority, you might want to send an immediate redraw request. You can do this with the UpdateWindow() function.

2.4 Getting a Device Context Handle

There are two methods in getting a Device Context handle. The first method is by processing WM_PAINT messages. Two functions involved in this process are BeginPaint and EndPaint. These functions require the handle to window, which is passed to the window procedure as an argument and the address of a structure variable of type PAINTSTRUCT which has to be defined within the window procedure like so:

PAINTSTRUCT ps; // where ps is the paint structure variable

While processing a WM_PAINT message the window procedure first calls the function BeginPaint which causes the background of the invalid region to be erased and prepare the window for painting. This function fills the fields of the paint structure. The value returned by BeginPaint is a device context handle. This value can be stored in a variable commonly named as hdc, which has to be defined in window procedure like so:

HDC hdc; // handle to DC

HDC is a data type defined as a 32 bit integer. After the definition of HDC the program can use functions like TextOut. The call to EndPaint releases the device context handle. The processing of WM_PAINT message looks like this:

case WM_PAINT:

hdc = BeginPaint(hwnd,&ps);

[ GDI functions]

EndPaint (hwnd,&ps);

return 0;

2.5 The Paint Structure(PAINTSTRUCT)

The PAINTSTRUCT structure contains information for an application. This information can be used to paint the client area of a window owned by that application.

typedef struct tagPAINTSTRUCT { // ps

HDC hdc;

BOOL fErase;

RECT rcPaint;

BOOL fRestore;

BOOL fIncUpdate;

BYTE rgbReserved[32];

} PAINTSTRUCT;

  • hdc Handle to the display DC to be used for painting.
  • fErase Specifies whether the background must be erased. This value is nonzero if the application should erase the background. The application is responsible for erasing the background if a window class is created without a background brush. For more information, see the description of the hbrBackground member of the WNDCLASS structure.
  • rcPaint Specifies a RECT structure that specifies the upper left and lower right corners of the rectangle in which the painting is requested.
  • fRestore Reserved; used internally by the system.
  • fIncUpdate Reserved used internally by the system.
  • rgbReserved Reserved used internally by the system.

Windows erases the background using the brush specified in the hbrBackground field of the WNDCLASS structure that is used when registering the window class during WinMain initialization. Many windows programs specify a white brush for the windows background. This is indicated in the program with the statement like this:

wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;

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;

LON