Connexions module: m14425


VC++ Tutorial for Beginners
Avanija j
This work is produced by The Connexions Project and licensed under the Creative Commons Attribution License †

Abstract This course entails the programming concepts in VC++ with clear syntax specication and programming examples.

1 Chapter 1 2 Basics of Windows Programming 3 1. 1 Paradigms of Programming Languages
Although many dierent 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 reected in the design of the dominant computer languages, with dynamic variables (representing memory cells with changing values); sequential iteration (reecting the single sequential cpu); assignment statements (reecting 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 reect 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.

3.1 Some Paradigms
• • • • • • •
Procedural (COBOL, FORTRAN, Pascal, C) functional (LISP) logic (PROLOG) structured object-oriented (Smalltalk) 4GL (Dbase) Visual (Visual Basic)

1.1.1 Procedural
∗ Version
1.1: Apr 4, 2007 12:57 pm GMT-5


Connexions module: m14425


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 dened in terms of other functions, which in turn are dened 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. also provides greater abstraction for solution. Functional programming One such a feature is polymorphism which allows general

denition 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 undened. If such a function can return a dened result we call it non-strict, else if returns undened is called strict. 1.1.3 Logic The basic constructs of logic programming, terms and statements are inherited from logic. There are The 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. 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 unication. 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.

3.2 1.1.4 Structural 3.3 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 specied condition is true.

Connexions module: m14425


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 owchart that ows smoothly fro the top to the bottom without unstructured branching (GoTos). Here is an example of a owchart 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 rst and focus on details later. Several Programmers can work on a single, large program, each working on a dierent 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 specic tasks. The logic of such programs is cluttered with details and therefore dicult 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.

As an example of languages that implements object paradigm are Smalltalk. The advantages of object-oriented programming do not evidence themselves when you are writing a single function for a particular purpose.1/ . and the computer code. In addition. 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. Objects and object interactions are the basic elements of design.Connexions module: m14425 4 • Easy to ChangeSince a correctly written structured program is self-documenting. or the static nature of the system. Later. things to a variety of data objects. these earlier abstract models all ran on one premise  there is data. objects can inherit characteristics from other objects. but permits individual implementations or methods for each dened class. Smalltalk is probably the best.4 Earlier Analysis and Design As programs got more complex. are there high-level languages that can add another layer of abstraction on top of the machine. Instead. programmers can create relationships between one object and another. you can dene a single generic function that embraces the similarities across object types. This makes object-oriented programs easier to modify. but also the types of operations (functions) that can be applied to the data In other words. Finally. A programmer can simply create a new object that inherits many of its features from existing objects. Later techniques involved: • • • • • data ow diagrams (functionality) data dictionaries (functionality) Decision trees process specications (structured English) entity relationship diagrams (data  Information modeling) The later techniques arose from the structured programming languages. so that the high level languages can be written in code that mirrors the way people think? Yes. For example. 3. 3. programmers realized that there might be a better way to write programs than getting a problem statement and sitting down and writing code. and became used in structured analysis and design. The analysis model was then mapped into a design model. the functionality models and the data models were distinct and separate entities. The problem was mapped into a verbal problem statement. However. They served as a bridge between the real world situation. the advantages arise when you are designing a large system that will do similar . Earlier methods included owcharts and functional specications. the data structure becomes an object that includes both data and functions. 1.4 Object-oriented In object-oriented programming programmers dene not only the data type of a data structure. entity relationship diagrams were added  these modeled the data. of course  these are the OO languages! Some OO languages are better at hiding the basic premise of the machine. However.1. it can be easily understood by another programmer. a little abstract planning might help. some abstract modeling techniques were developed. The rst models attempted only to model the functionality of the real-world systems. http://cnx. which was far removed from the machine implementation.5 OO The Object Oriented Paradigm Is it possible to make a computer think the way people naturally think. 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. functional decomposition. However. and then into a requirements analysis model. 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. In this way. Delphi and Java. code was written from the design model. while C++ is probably the worst . Along these lines. but not identical. and there are functions that process the data. which was one step closer to the machine implementation (the code). By specifying classes of data objects for which identical eects will occur.

and Brad Cox created Objective-C.) 3. Ability to extend existing classes (i.5 Inheritance A looser classication scheme is obtained through inheritance. Data is implemented as data. OO languages allow for similar functions (actions) to be given similar names. which entails: a.g.5. while actions are implemented as functions. things. However.Connexions module: m14425 5 3.1/ . Bjarne Stroustrup invented All data are dened by abstract data type (ADT) based modules. OO languages have been around for 24 years. For example. We have a "cat" class from which we create cat objects. *. the arithmetic operators act on both oating point numbers and integers with the same operators (+. cats eat and cows eat.5. Classes are like "cookie cutters" from which objects are moulded. This allows for conceptual clarity in writing code. Then came Smalltalk  1972. OO objects combine both data (nouns and adjectives) and actions (verbs) into one package. we have a cat class that has weight. The class species the attributes (and the functionality) while the objects ll in the attribute values. In 1986. . We can call similar functionality by the same name  e. We can tie in our cat class into a whole inheritance hierarchy which includes the entire cat family. it never caught on in the U. color. But the outside world sees data and functionality merged into one whole. Support of polymorphism and dynamic binding. we create cat objects. each with dierent attributes. Earlier versions. First.) Encapsulation. /. Like objects of human thought.5.. 3. languages began taking o at this time.S. Automatic memory management (not necessarily garbage collection). http://cnx. there is the class construct. handle them.5.1 History of OO languages First OO language was Simula  1967.e. (e.3 Objects Basic building block of OO languages is the object.4 Classes OO Languages promote classication at two levels.6 Polymorphism Polymorphism is the method by which OO languages mirror the human thought processes' tendency to group certain actions together. The machine still sees a data-functionality split. we still call their actions "eating".) Information hiding and b. 3. Used widely in Europe. through which the program is actually run.g.2 What Makes a Language Object-Oriented? According to Bertrand Meyer. For example. all animals. and then all living 3. may have been unpopular because machines weren't powerful enough to 3.5. Note that C and other traditional languages use polymorphism to some extent.5. classes). the mammals. The modules must support data abstraction. but the way they eat is dierent. such as Smalltalk. and name attributes specied. inheritance). OO But as of 1994. Multiple inheritance (the need for this feature in an OO language is disputed by many in the OO eld. an OO programming language should contain the following 7 qualities [7]: • • • • • • • The support of modules. etc) even though the underlying implementation is radically dierent. From the cat class.

Microsoft called Windows 1. Clipboard. only the abstract principles of the object.0. Calendar. however. however. operating systems. To understand the progression of Windows server operating systems you have to look back earlier than 1993. On November 10. the rst widely popular version of Windows and the rst version of Windows many PC users ever tried. Many longtime PC users trace Windows to the 1990 release of Windows 3. The selection of applications was sparse. User's choose items and execute programs by pointing and clicking with a mouse. Notepad. to the even longer line of Windows desktop operating systems stretching back to the early 1980s.0 a new software environment for developing and running applications that use bitmap displays and mouse pointing devices.7 Abstraction Software objects mirror the human mind's tendency to abstract out details. as dened by the interface. The Windows Environment Windows is a Graphical User Interface (GUI). With the upcoming release of Windows . This is because Windows provides these programs with a number of built in functions and data which are not available in other environments. Reversi. an extension of the MS-DOS operating system that would provide a graphical operating environment for PC users. by bringing together the two previously separate lines of Windows desktop operating systems. Print Spooler. 1. These system dened 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. All the functions supported by the API can work with 32 bits of information at any given time. The "user" or "client" of an object does not have to worry about the inner details of the object. Windows Paint. Windows program make use of these built in functions and do not have to be coded to perform these tasks. the following pages summarize milestones in the development of Windows desktop operating systems at Microsoft. Microsoft announced Microsoft Windows. Windows Write. Cardle. PIF (Program Information File) Editor. MS-Excel and MS-Word. To understand the roots of today's Windows Writing programs for the Windows environment using the API functions is referred to as SDK programming where SDK stands for Software http://cnx. Development Kit. Terminal. Clock. The functions that are provided by windows include functions with the functionality to draw text in dierent sizes and styles using font data. included MS-DOS Executive. Windows provides a broad range of graphical functions for drawing lines and geometric shapes and changing color. Microsoft will complete a cycle of server operating system upgrades it began nearly a decade ago in 1993. Software objects hide the internal details of an object behind the walls of an interface. It uses graphics to organize the user's workspace. we must journey back nearly 20 years. RAMDrive. with the release of the rst version of Microsoft Windows NT Server.0. however. Windows 1. Moreover these programs can run only within Windows. in 1985. Control Panel. 1983. The release of Windows XP in 2001 marked a major milestone in the Windows desktop operating system But Microsoft actually released the rst version of Windows six years earlier. For example. for example.5.0 package. and Windows sales were modest. 1. With Windows. Calculator. The development was delayed several times.0 hit the store shelves in November 1985.1/ .NET Server.3 A History of Windows Windows promised an easy-to-use graphical interface. the API that Windows 95 supports (also called the Win32 interface) is a 32-bit API. the graphical user interface (GUI) era at Microsoft had begun.Connexions module: m14425 6 3. To explain the many advances since Windows 1. The program that run from within Windows also have a Graphical User Interface (GUI). device-independent graphics and multitasking support. and the Windows 1.

such as starting applications. notepad. continued on next page http://cnx. in the operating system. Windows 1.Connexions module: m14425 7 The Windows 1.1/ . calculator. clock. The product included a set of desktop applications.0 also allowed users to switch between several programswithout requiring them to quit and restart individual applications. a calendar. including the MSDOS le management and telecommunications programs. card le.0 product box showed the new tiled windows and graphical user interface in the operating system Table 1 1985: Windows 1. which helped users manage day-to-day activities.0 The rst 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.

expanded memory. including: • • Program Manager. and also allowed users to overlap windows. Subsequent Windows releases continued to improve the speed.0 was Windows/386 2. and Print Manager A completely rewritten application development environment with modular virtual device drivers (VxDs). File Manager. A new wave of 386 PCs helped drive the popularity of Windows 3. Following the release of Windows 2. and usability of the PC.0 With the second version of Windows. http://cnx.x. Widespread acceptance among third-party hardware and software developers helped fuel the success of Windows 3. and improved the interface design and capabilities. and fully pre-emptive MS-DOS multitasking • An improved set of Windows icons The popularity of Windows 3.Connexions module: m14425 8 Even before the Windows 1. Microsoft took advantage of the improved processing speed of the Intel 286 processor.0 graphical user interface. Windows 2. advanced graphics. 1990: Windows 3.03. there was this pre-Windows 1.0 Microsoft's rst mainstream computing platform oered 32-bit performance. which oered a wide range of new features and capabilities. reliability. which helped software developers focus more on writing applications and less on writing device and use keyboard combinations to move rapidly through Windows operations.0 Interface Manager Table 2 1987: Windows 2. which took advantage of the protected mode and extended memory capabilities of the Intel 386 processor. and inter-application communication capabilities using Dynamic Data Exchange (DDE). control screen layout.0 blossomed with the release of a completely new Windows software development kit (SDK).0 featured support for the VGA graphics standard. native support for applications running in extended memory. Many developers started writing their rst Window-based applications for Windows 2.0.1/ .0. and full support of the more powerful Intel 386 processor.

http://cnx. It completed a project Microsoft began in the late 1980s to build an advanced new operating system from scratch. operating system power. and remote access service (RAS). domain server security.1.11 A superset of Windows 3. such as centralized conguration and security. It added features of special interest to corporate users. performance. marked an important milestone for Microsoft. For the rst time. support for multiple processor architectures. desktop scalability. and reliability with a range of key new features. signicantly improved support for Novell NetWare networks.1 The release to manufacturing of Microsoft Windows NT ® on July 27.11 added peer-to-peer workgroup and domain networking support.0 featured a new File Manager Table 3 1993: Windows for Workgroups 3. Windows for Workgroups 3.Connexions module: m14425 9 Windows 3. Windows NT was the rst Windows operating system to combine support for high-end client/server business applications with the industry's leading personal productivity applications. 1993. 1993: Windows NT 3.1/ . Windows PCs were natively network-aware and became an integral part of the emerging client/server computing evolution. The operating system broke new ground in security. Windows for Workgroups was used in local area networks (LANs) and on stand-alone PCs and laptop computers. integrated networking. "Windows NT represents nothing less than a fundamental change in the way that companies can address their business computing requirements. and the NTFS le system. These included a pre-emptive multitasking scheduler for Windows-based Windows for Workgroups also oered the performance benets of Microsoft's new 32-bit le system. OS/2 and POSIX subsystems.

engineering.1/ . Windows NT was a strategic platform that could integrate client/server applications with existing Windows-based desktop applications. including support for NetWare le and print servers. The 32-bit operating system also oered enhanced multimedia capabilities. and rich Microsoft Win32 (API)a combination that made it easier to support powerful programs. The desktop version was well received by developers because of its security. The product also oered 32-bit performance improvements. and business-critical tasks. and improved productivity features. better application support. it did not include support for such features as system-level security or Unicode. dial-up networking. and integrated networking. nancial analysis. In order to keep memory requirements to a minimum. or function as a technical workstation to run high-end engineering or scientic applications. more powerful features for mobile computing. Windows for scientic.1 Table 4 The new operating system began with version 3.5 supported the OpenGL graphics standard.1. which came later. 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.5 Windows NT Workstation 3. such as the capability to give les 255-character names. and MS-DOS. ® application programming interface http://cnx. which at the time was a well-established operating system for both home and business users.1 in order to maintain consistency with Windows 3.5 release provided the highest degree of protection yet for critical business applications and data. 1993: Windows NT Workstation 3.1 contained overlapping windows and other features similar to Windows 3.1. The Windows NT Workstation 3. and new Plug and Play capabilities that made it easy for users to install hardware and software. which helped power high-end applications for software development. stability.Connexions module: m14425 10 Windows NT 3. Windows 95 included an integrated 32-bit TCP/IP stack for built-in Internet support. 1995: Windows 95 Windows 95 was the successor to Microsoft's three existing general-purpose desktop operating systems Windows 3.

It oered consumers a variety of new and enhanced hardware compatibility and Internet-related features. Described as an operating system that "Works Better. and it included support for reading DVD discs and connecting to universal serial bus (USB) devices.0 included the popular Windows 95 user interface and improved networking support." and ® version 3.1/ .org/content/m14425/1. 2000: Windows Millennium Edition (Windows Me) Windows Me oered consumers numerous music. Windows 98 SE delivered an improved online experience with Internet Explorer 5 browser software and Microsoft Windows NetMeeting NT.0 conferencing software. save. and play digital media. Windows Movie Maker provided users with the tools to digitally edit. and share home Microsoft Windows Media — Player 7 technologies allowed users to easily nd. Windows 98 enabled users to nd PC. It also included Microsoft DirectX ® API 6. In October 1998. and a complete set of tools for developing and managing intranets. was an incremental update to Windows 98. which delivered a variety of Windows multimedia improvements. video. videos. providing secure.or Internet-based information easily. higher network throughput.0 This upgrade to Microsoft's business desktop operating system brought increased ease of use and simplied management. 2000: Windows 2000 Professional Figure 1 http://cnx. Plays Better. as it was often abbreviated. 1998: Windows 98 Windows 98 was the upgrade to Windows 95. organize. Microsoft announced that all future operating system products would be based on the Windows NT and Windows 2000 kernel." Windows 98 was the rst version of Windows designed specically for consumers. easy access to the Internet and corporate intranets. Windows Me was the last Microsoft operating system to be based on the Windows 95 kernel. and oered home networking capabilities through Internet connection sharing (ICS). Microsoft announced that Windows NT would no longer carry the initials that the next major version of the operating system would be called Windows 2000.Connexions module: m14425 11 1996: Windows NT Workstation 4. Windows NT Workstation 4. 1999: Windows 98 Second Edition Microsoft Windows 98 SE. System Restore let users roll back their PC software conguration to a date or time before a problem occurred. Windows 98 SE was also Microsoft's rst consumer operating system capable of using device drivers that also worked with the Windows NT business operating system. and home networking enhancements and reliability improvements. it opened and closed applications more quickly.1.

while adding new tech-support technology. The entry point for a Windows program is a function named WinMain. 1. a mouse click. and system memory protection.0 code base. simplied visual design that makes frequently accessed features more accessible. Windows Messenger. Microsoft Windows Media — Player.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.4. Windows 98. The product oers many enhancements aimed at home users such as the Network Setup Wizard. Windows XP Professional also oers a redesigned interface and includes features for business and advanced home computing. An event could be a keystroke. and security that business users beneted from in Windows 2000.1x networking support. fault tolerance. Microsoft succeeded in merging its two Windows operating system lines for consumers and businesses. Windows XP 64-Bit Edition. Windows XP also includes the broad base of application and hardware compatibility of Windows 98 and Windows Me.Connexions module: m14425 12 Windows 2000 Professional was the upgrade to Windows NT Workstation 4. and support for mobile computing. including advanced networking and wireless products. and infrared devices. but the path remains fairly predictable.0 on all business desktops and laptops. Windows Movie Maker. Windows XP Professional and Windows XP Home Edition. but most of the action takes place in a http://cnx. ease of use. It also oers numerous key enhancements such as wireless 802. a fresh user interface. Windows 2000 Professional was designed to replace Windows 95. Windows 2000 Professional also made hardware installation much easier than it was with Windows NT Workstation 4. Remote Assistance. and Windows NT Workstation 4. encrypting le system. for power users with workstations that use the Intel Itanium 64-bit processor. in which applications respond to events by processing messages sent by the operating system. consumers and home users now have performance. USB devices.0. but it was more than just that.0 by adding support for a wide variety of new Plug and Play hardware. system restore and advanced networking features. IEEE 1394 devices. Built on top of the proven Windows NT Workstation 4. Internet compatibility. Windows XP is available in two main versions. main might call other functions and these functions might call even more functions. The path taken from start to nish may vary with each invocation of the program depending on the input it receives or the conditions under which it is run. as well as a 64-bit edition.1/ . In a C program. and enhanced digital photo capabilities. and many other improvements that make it easier to use for a broad range of tasks. including preemptive multitasking. Windows 2000 added major improvements in reliability. uniting them around the Windows NT and Windows 2000 code In between. 2001: Windows XP Professional Windows XP Professional benets from the long track record of Microsoft Windows NT technology: superior operating system performance. and the System Restore feature. Windows programs operate dierently. but ultimately it is the programnot the operating systemthat determines what gets called and when. execution begins with the rst line in the function named main and ends when main returns. With Windows XP. They use the event-driven programming model illustrated in Figure 1. including Remote Desktop. or a command for a window to repaint itself. among other things. 2001:WindowsXPHomeEdition Windows XP Home Edition oers a clean. 2001: Windows XP Windows XP is a unifying leap forward for desktop operating systems. stability. With the release of Windows XP Home Edition and Windows XP Professional in October 2001.

signaling that it's time for the application to end. and in between Dynamic Link Library (DLL) Dynamic Link Library (DLL) is a collection of software routines programmed in a language such as C or When the message loop ends.Connexions module: m14425 13 function known as the window procedure. or selected Close from the window's system menu. alternately retrieving messages and dispatching them to the window procedure. Messages wait in a message queue until they are retrieved.4 Windows Programming Model The window procedure processes messages sent to the window.1/ . application terminates. This message usually appears because the user selected Exit from the File menu. The message loop ends when a WM_QUIT message is retrieved from the message queue. it does little except wait for the next message to arrive. WinMain creates that window and then enters a message loop. Figure 1. WinMain returns and the http://cnx. A typical Windows application performs the bulk of its processing in response to the messages it receives. clicked the close button (the small button with an X in the window's upper right corner). 1.

In this scenario. did not conict with a DLL for another purpose with the same name.e. Naturally enough.1/ . which. a DLL is replaced that brings it into conict with other DLLs it must work with. If a problem arose. notwithstanding its reputation for stability and resilience. • • • • On several occasions Microsoft has created and distributed DLL les that instantaneously broke every Windows application in the world. All the elements of the service pack must simultaneously be present in their most recent form or the system will crash. The DLL was uniquely named. even by Microsoft itself.0. An application should only place a DLL in the central repository if: • • • The DLL was newer and/or better than the ones already there. it might be usable by an author of a Windows Help hyper book. Then the user installs an application that blithely replaces one or more of the DLLs from the service pack. This is obviously impossible. thus saving greatly on duplication of eort and storage space. but it failed to take into account the imperfections in the human character. the DLL system is a weak version of the object-programming paradigm. Microsoft releases a service pack that updates all key system DLLs. will fail utterly and completely. the originator of the idea. These functions are implemented in DLL. If the DLL replaced another with the same then the code in the DLL would be exhaustively tested. Applications that used the DLL system would behave exactly the same as all other applications that used it. Over time. in particular 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. thus mysteriously bringing down the system until an expert can sort it out. so that on replacement. For example. Regularly. It isn't. Here are the advantages: • • • Applications would link to this code library. The original idea for the DLL system was that there would be a central repository of code. The solution to these problems is to go back to the system that preceded the DLL system. To write a DLL. These are les with extension . In windows programming DLL plays an important part. The idea was sound. http://cnx. those imperfections that inuence the creation and operation of computer programs. the "synchronization" problem becomes more severe. 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.EXE. Every application should place as many DLL les as possible in its own directory (some DLL les are part of Windows itself. along with these advantages came some responsibilities. By compiling this as a DLL. even on Windows NT 4. without them having to know anything about the programming. In this scenario. Result  system failure. it could be written once and all would benet. Windows provides function calls to implement its user interface and display text and graphics on the video display.DLL or . other applications could use it in the same way as its predecessor. In time.Connexions module: m14425 14 Pascal. end users will install an application that has a DLL with the same name as a "system" DLL. In this sense. a C programmer might write a routine that accesses a laser disc player. or a new feature was desired. This is an example of a collision between an idea and reality. which has been packaged especially for use from another program. a key element in the human drama. all these rules have been broken. i. Many applications (including Microsoft's own) have rendered systems unstable or unusable through this reasoning. The service pack problem is becoming severe. you must imagine the eect of your changes and additions on every computer program that uses it. these must be accessed in common).

Connexions module: m14425


3.6 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 signicant 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. Specically 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 dierent in C#. Most of the advanced languages support API programming. performing fast operations on database. The Microsoft Foundation Class Library (MFC) framework encapsulates a large portion of the Win32 (API). ODBC API Functions are useful for 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 specic 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' prex after the library name e.g. KERNEL32, USER32 etc. . .

Connexions module: m14425


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. such as : This allows managing the entire user interfaces

• • • •

Windows Menus Dialog Boxes Icons etc.

e.g. The DrawIcon function draws an icon or cursor into the specied device context. GDI (Graphical Device Interface) This is the library named "GDI32.dll" in Win32. draws windows, menus and dialog boxes. It is Graphic output library. Using GDI Windows

• •

It can create Graphical Output. It can also use for storing graphical images.

e.g. The CreateBitmap function creates a bitmap with the specied 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 les 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 dene 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. programs, the clock and various utilities. The Start Menu  A one button approach to accessing programs, help, and system settings. It contains icons representing all active

Connexions module: m14425


GUIs oer 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 eld (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 les, options and settings when an option is selected, the one previously selected is turned o ). Check Lists (from which the user can make multiple selections as in specifying print or le 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 dierent 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 benet of GUI is that the user can learn a second application faster because he or she is familiar with the environment. Note that the benet 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. familiarity with the environment. Drawing and CAD programs are the best suited to GUI. Since, by their nature they manipulate objects lines and curves, ll closed areas with color. However they can use GUIs eectively to: For database programs, such manipulation is not as useful. The consistency oered by a GUI trades on the users

• • •

Specify data elds 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 nal benet of GUI is that it lets you see the nal 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 ts 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 sucient 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

rather than waiting in a loop for the switch to close. the program is accepting your keys and entering the characters into your document.h> WINDOWS. for example. some of which also include other header les. While events most often originate from the outside your program. events can also generated by other parts of the program. The WinMain function appears like this: http://cnx. In order to meet this requirement.H Graphics device interface functions. at the next it has. All of these operating systems. A service is what you do in response to the event. you could also react to another event while you were waiting for the switch to close. If it is in the menu bar. the service can not to go into a state where it is waiting for some long or indeterminate time.H is a master le that includes other Windows header les. In order for this approach to work. so that the program can get back to checking for events. If the mouse pointer is at another place in your document. They are important part of Windows documentation. must also be capable of dealing with the same kind of variable input that the VCR must handle.Connexions module: m14425 18 or any number of other actions. like the VCR. In this way. WINGDI. 1. Event Checkers An event. 1. 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. by its nature. So how to deal with the need to wait for the switch close? You make the switch closure an event. This program structure is generally called event driven programming. an indenite loop is referred to as `Blocking ` code. You can also click with the mouse at any place on the screen. the events must checked continuously and often.H Basic type denitions. have adopted a common program structure to deal with the need to respond to many asynchronous (not time sequence) inputs. it may change the format of the next character entered. The switch being open or closed does not represent an event. the event has not occurred . or most other programs running under Windows. The event is marked by the transition from open to closed. you must only write `Non-Blocking' code. the point of insertion moves. a switch closure. what we need is a program structure that will allow us to respond to a multitude of possible inputs. In order for the even t driven programming model to work. the program structure is divided into two rough groups. represents a discrete point in time. An event represents the occurrence of something interesting. This kind of program structure. Clearly. WINBASE. WINNT.9 Header Files Windows programs begin with a processor directive at the top such as : #include <windows. data structures and constant identiers. The program cannot move to only looking for the channel select buttons while you are programming. a menu will drop down. These header les dene all the Windows data types. In the case of a switch. executing the associated service. Then. X-Windows or any other modern Graphical User Interface(GUI). WINUSER.H Type denitions for Unicode support.H Kernel functions. when an event is detected. While this problem is very common in embedded systems.10 Program Entry Point In windows program the entry point is WinMain similar to the main function in C program. it is also very common in modern desktop computers. At one instant.H User interface functions.1/ . the opening or closing of the switch represents an event. function calls. such a mouse click. Events and Services. If it is over a formatting button. The program executes by constantly checking for possible events and. or it would miss the end of tape sensor for the rewinding tape. MacOS. any of which may arrive at unpredictable times and in an unpredictable sequence. The most important and most basic of these header les are: • • • • • WINDEF. Your word processor. Under the event driven programming model. and many embedded applications. Think about using a word processor. This implies that the services must execute quickly. While you are typing. The most common example of this would be a while loop where the condition for termination was not under program

EXE(executable) le.12 MessageBox Function The MessageBox function is designed to display short messages.exe from the Build menu by pressing Ctrl+F5 or click the Execute program icon.H like so (line breaks and all) : int WINAPI WinMain( HINSTANCE hInstance.LIB. The rst argument to MessageBox is normally a window handle. In early versions of windows when you run the same program concurrently more than once. and GDI32. In windows programming a handle is simply a number that an application uses to identify something. In 32 bit versions this concept has been abandoned. It is required as an argument to some other windows function calls.H. HINSTANCE hPrevInstance. They contain the dynamic-ling library names and reference information that is bound in to the . Alternatively you can execute samplewinprg.DLL dynamic link libraries.DLL and GDI32. These are import libraries for the three major Windows subsystems. You can see a list of these library les by selecting settings from the Project tab and clicking the Link tab. From the Build toolbar.DLL.OBJ(object) le from the C source code le.11 Compile. A message will be displayed asking if you want to build the program. HINSTANCE hPrevInstance. int nCmdShow) It is declared in WINBASE. A program can determine if other instances of itself are running by checking the hPrevInstance parameter. The appearance of this icon is shown in the Build menu. By default these are http://cnx. During compilation the compiler generates an .LIB.exe from the Build menu or press F7. The window that a MessageBox displays is considered to be a dialog box. This declaration uses a system called Hungarian notation through which the variable name is indicated with a short prex that indicates the variables data type. During the ling stage the linker combines the . multiple instances of that program will be created. called Debug and Release. or select the Build icon from the Build toolbar.LIB. int nShowCmd ).OBJ le with .Connexions module: m14425 19 int WINAPI WinMain(HINSTANCE hInstance.1/ . The rst parameter to WinMain is an instance handle. LPSTR szCmdLine. In particular you'll notice KERNEL32. The list of buttons that can appear in dialog box are: MB_OK MB_OKCANCEL MB_ABORTRETRYIGNORE MB_YESNO MB_YESNOCANCEL The third parameter to WinMain is The fourth parameter to WinMain indicates how the program should be initially displayed either normally or maximized to ll the window or minimized to be displayed Developer Studio. you can compile and link the program in dierent congurations. USER32. in the task list bar.EXE le. Pick Build or Build MiniBar. 1.LIB(library) les to create the . The second parameter to WinMain is always NULL (dened 0). The fourth parameter can be any of the combination of constants beginning with the prex MB_ that are dened in the WINUSER. 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. USER32. Link and Run Windows program When you are ready to compile your program named samplewinprg. This notation will be discussed later. command line used to run the program. LPSTR lpCmdLine. In this case the handle uniquely identies the program. If the Build toolbar is not currently displayed you can choose Customize from the tools menu and select the Toolbars tab. Windows uses this information to resolve calls from the program to In Visual C++ function in the KERNEL32. you can select Build samplewinprg.

and HPEN is the handle to PEN. a window.13 Data Types Windows programming has a reputation for its variety of data types. but it is more proper to say that it returns IDOK. it uses all C data types and also introduces a few data types of its own. which is dened in running copy of a program is called an instance.h as equaling 1. Program Windows Kernel Memory HandleHandle TablePhysical Address Figure 2. There are a number of related data types for describing dierent kinds of handles. A handle is an unsigned integer that Windows uses internally to keep track of objects in memory. All objects in windows are referred to by handles.HINSTANCE hPrevInstance. A handle is simply a number assigned by the system to a particular entity. To refer to a particular instance of a program. In the program shown above. Figure 2.h> int WINAPI WinMain(HINSTANCE hInstance. } Figure 2."Application executing". hInstance is the handle that identies the current instance of the application and hPrevInstance contains the hInstance value for the last copy of application. a handle is required. The sample windows application illustrated in this chapter uses a few of the Windows data types.1/ .10(a) # include <windows. Internally the Kernel of windows maintains tables that allow windows to convert handles to physical memory addresses. It serves to identify the entity. windows moves and object in memory.PSTR szCmdLine. the handle table is updated. every window on the screen has a unique window handle. the pointer will be invalid when the object is moved by windows as a part of its memory management. A handle is a pointer to a memory location. return(0). All these data types begin with the letter H. MessageBox(0. For example. Thus pointers can be dereferenced whereas handles will http://cnx."Application". Handles are also used to keep a track of running applications.10(a) Sample Output In this program. 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. allocated memory blocks and a host of other objects.10(b) displays a representation of handles in the memory. no matter where the object is moved in memory.10(b) Handles in the Memory If a pointer was used to refer to an object in memory. int nCmdShow) {int i. a control or a block of memory. the MessageBox function returns the value 1. The following code displays a message as displayed in gure 2.Connexions module: m14425 20 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. programs and so on) in memory to make room for others. Thus. whether it is an instance.MB_OK). Handles are a replacement of pointers. The reason for this complexity is that If windows moves objects (memory blocks. HWND is the data type for a window handle.

LPSTR is another new windows data type that is used. BYTE(unsigned character) Char(character) DWORD(double word) Function Handle int(integer) Long Short(int) or near pointer Pointer Character string Character string terminated by zero Word(two bytes) Table 5 1. it is used to store a Long Pointer to a String same as the char data type of C. The Table 1.Gets the length of a string in characters. 7 lstrcpyn . in honor of its inventor Charles Simonyi. which will dismiss the MessageBox as specied by the MB_OK parameter. 6 lstrcmp  Compares two strings. 9 lstrlen .Compares two strings. 1. copy string.15 Windows String Functions 4 The collection of string functions included in windows to calculate string length. 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. with the specied title and message text. Table 1. The variable here can take either True or False values. The comparison is not case sensitive. concatenate strings and compare strings are listed below: 5 lstrcmpi .Connexions module: m14425 21 continue to be valid since the handle to pointer table will be updated automatically by windows whenever it moves an object in memory.14 represents the Hungarian notations.1/ . with a maximum the message displayed will show an OK button also.14 Hungarian Naming Convention The names of the variables used in a window program follow a naming convention called Hungarian notation. 10 lstrcmpi Compares two character strings. http://cnx. ignoring case.Copies one string to another. In the above program. 8 lstrcpy .14 Variable Name Codes in Hungarian Notation Variable Name PrexCode b by c dw fn h i l n p s sz w Data Type BOOL(Boolean). The MessageBox function of the Win32 API displays a message on the screen.Copies one string to another.

The second parameter lpszString2 is the pointer to the null-terminated wide string to be copied.Connexions module: m14425 22 Syntax int lstrcmpi(LPSTR lpszString1. Syntax LPSTR lstrcpy(LPSTR lpszString1.LPSTR lpszString2). and so on until it nds an inequality or reaches the ends of the strings. which could result in the source string being truncated. The lstrcmp function compares two strings by checking the rst characters against each string to be copied. 11 lstrcmp Compares two strings. The lstrcmpi function compares two wide strings by checking the rst characters against each other.LPSTR lpszString2). the second characters against each other. Similarly two wide strings can be compared ignoring case using the function lstrcmpW. Similarly two wide strings can be copied using the function lstrcpyW. 12 lstrcpy Copies a string to a buer. nonzero. up to a specied number of characters. The second parameter lpszString2 is the Pointer to the second null-terminated wide string to be compared. This function returns zero if the strings are equal. The rst parameter lpszString1 is the pointer to the rst null-terminated string to be iMaxLength). If iMaxLength is The third parameter iMaxLength gives the maximum number of characters to copy. up to a specied number of wide characters. The buer must be large enough to contain the string. The second parameter lpszString2 is the pointer to the second null-terminated string to be compared. The rst parameter lpszString1 is the pointer to a buer to receive the contents of the string that the lpszString2 parameter points to. 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). Returns a positive value if the string that lpszString1 points to is greater than the string that lpszString2 points to. including the The second parameter lpszString2 is the pointer to the null-terminated This function returns a pointer to the buer. and so on until it nds an inequality or reaches the ends of the strings. The rst parameter lpszString1 is the Pointer to a buer to receive the contents of the string pointed to by the lpszString2 parameter.1/ . The rst parameter lpszString1 is the Pointer to the rst null-terminated wide string to be compared. terminating wide null character. including the terminating wide null character. The comparison is case sensitive. 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. Syntax int lstrcmp(LPSTR lpszString1. the second characters against each other. This function returns a pointer to the buer.LPSTR lpszString2. including a terminating null character.LPSTR lpszString2). Similarly lstrcpynW copies a wide string to a buer. lstrcpyn always inserts a terminating null character in the destination string. Returns zero if the strings are equal. The buer must be large enough to contain the string. Syntax LPSTR lstrcpyn(LPSTR lpszString1. 13 lstrcpyn Copies a string to a buer. 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. lstrlen http://cnx.

program. LRESULT CALLBACK wndproc(HWND. int nCmdShow) { wc. wc. wc.LPARAM). If the function succeeds. This involves a bit of overhead that appears in almost every windows The program shown below is a simple program that handles only three windows messages(two mouse click messages and a quit message).NULL). HWND hwnd.HINSTANCE|CS_VREDRAW. http://cnx.16 The Sample SDK Program Creating a window rst requires registering a window class and that requires a window procedure to process messages to the window.IDC_ARROW). MSG msg.AsampleSDK Window. wc. Figure 1.hCursor=LoadCursor(hInstance. hwnd=CreateWindow(Sample. 1.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH).lpszClassName ="Sample".lpfnWndProc=wndproc.LPSTR lpCmdLine.lpszMenuName =NULL.UINT.16 (a) A Minimal Windows Program written using SDK // Sample SDK program to display window #include <windows.Connexions module: m14425 23 Retrieves the length of the specied string.16(a) shows the applications only window. Syntax int lstrlen(LPSTR lpszString). Figure wc. wc. Similarly lstrlenW retrieves the length of the specied wide string.hInstance=hInstance.h> WNDCLASS wc. int WINAPI WinMain(HINSTANCE hInstance. the return value species the length of the string.hIcon=LoadIcon(hInstance. wc. wc. The rst parameter lpszString is the pointer to a null-terminated wide string.1/ . if (!RegisterClass(&wc)) return false.

//creation parameters ShowWindow(hwnd. char right[]="You have pressed right mouse button". } return(DefWindowProc(hwnd.wp.0)) { TranslateMessage(&msg).1/ . } default: break."About". //initial y size NULL.left. break.right.//window style CW_USEDEFAULT. UpdateWindow(hwnd). //initial x size CW_USEDEFAULT. } case WM_RBUTTONDOWN: { MessageBox(GetFocus().//window menu handle HINSTANCE.MB_OK|MB_ICONINFORMATION).lp)). return 0. DispatchMessage(&msg). //initial x position CW_USEDEFAULT. } return true. while(GetMessage(&msg.LPARAM lp) { char left[]="You have pressed left mouse button".MB_OK|MB_ICONINFORMATION). } LRESULT CALLBACK wndproc(HWND hwnd.NULL. switch(wm) { case WM_LBUTTONDOWN: { MessageBox(GetFocus(). //initial y position module: m14425 24 WS_OVERLAPPEDWINDOW.UINT wm. } case WM_DESTROY: { PostQuitMessage(0).nCmdShow).WPARAM wp."About".//program instance handle NULL).wm. break. } http://cnx.//parent window handle NULL.

structure of a window class looks like this: typedef struct_WNDCLASS {UINT style. ShowWindowShows the window on the screen. Load CursorLoads a mouse cursor for use by a program. UpdateWindowDirects the window to paint itself. Then the two SDK functions declared are: the program entry point WinMain() and the application's window procedure in this case wndproc.Connexions module: m14425 25 Figure 1.h>. //window procedure The http://cnx. GetStockObjectObtains a graphic object in this case a brush used for painting the windows background. API prototypes and everything else that the SDK program needs.16 (b) The sample SDK program responding to a left mouse click message 1. //window class style WNDPROC lpfnWndProc. DefWindowProc Performe default processing of messages. RegisterClassRegisters a window class for the program's window MessageBoxDisplays a message box.16. GetMessageObtains a message from message queue. These functions with a brief description are: However there is a reference to wndproc in WinMain. DispatchMessage Sends a message to a window procedure. PostQuitMessage To insert a quit message in to the message queue. macros. Window Class Structure(WNDCLASS) The WNDCLASS structure is used to dene all windows that you can view on your monitor.1/ . The program starts with #include<windows. • • • • • • • • • • • • • Load IconLoads an icon for use by a program.1Dissecting the Program The code for this program deserves a closer examination. CreateWindowCreates a window based on a window class. which is why the function is declared near the top of the program. This statement includes the main windows header le(WINDOWS. Windows function calls The sample SDK windows program makes calls to fewer windows that in turn includes all the windows header le that contain structures. TranslateMessage Translates some keyboard messages.

A window class must be initialized and registered when the rst instance begins execution. // icon handle HCURSOR hCursor. In some sample windows programs you may see the following code in WinMain: If(!hPrevInstance) {wc.1/ .style=CS_HREDRAW | CS_VREDRAW. Message Structure Because almost everything in windows happens in response to messages. //extra class bytes int The identiers contain a two-letter or three-letter prex 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.Connexions module: m14425 26 int cbLlsExtra. Here is the way to handle the RegisterClass function call: if(!RegisterClass(&wc) return false. // background brush color LPCTSTR lpszMenuName. // additional information about the message DWORD time. // handle of the windows to retrieve messages UINT message. belongs. // cursor handle HBRUSH hbrBackground. 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. Uppercase Identiers These identiers are dened in the windows header les. // message value for each windows identied by macros in WINDOWS.H WPARAM wp. the windows message structure MSG is extremely important. //extra window bytes HANDLE hInstance. //time at which the message was posted to the queue POINT pt. // window class name }WNDCLASS . The prex indicates a general category to which the constant • • • • • • • • • 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. // screen coordinates of the cursor when the message was posted }MSG. // menu resource LPCTSTR lpszClassName. This structure is dened as follows: typedef Struct tagMsg {HWND hwnd. http://cnx. // instance handle HICON hIcon.

The window class can be registered only if hPrevInstance was NULL. 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. hwnd=CreateWindow( SZAPPNAME. Finally a creation parameter is set to NULL. http://cnx. system menu button to the left of the title bar. a thick window sizing border and minimize. They are: ShowWindow(hwnd. // window class name SZAPPTITLE. By using the identier CW_USEDEFAULT to indicate (initial x . y size) we are indicating that we want windows to use the default position for an overlapped minimized or maximized. // initial x position CW_USEDEFAULT. UpdateWindow(hwnd). // window style CW_USEDEFAULT. } This declaration is necessary only for 16 bit version of windows. Normally. y position and initial x . Displaying the Window After the CreateWindow call returns the window has been created internally in windows. // window caption WS_OVERLAPPEDWINDOW.. // program instance handle NULL). The rst argument is the handle to the window just created by CreateWindow. whether it is normal. The program instance handle is set to the instance handle passed to the program as a parameter of WinMain. // window menu handle HINSTANCE.nCmdShow). minimized or maximized. This can be done by dening the second parameter to have one of the elds given below: • • • • SW_SHOWMAXIMIZED . It will have a title bar. // parent window handle NULL. It is dened to be of type HWND (handle to a window). Creating the Window The application window is created by calling the API function CreateWindow(). But in 32 bit versions of windows hPrevInstance is always NULL. SW_SHOWMINOACTIVE  To display the window in task bar. 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. However the windows do not yet appear on the video display. The ShowWindow call determines how to display the window on the screen. it is not necessary to check hPrevInstance. two more calls are needed. maximize and close buttons to the right of the title bar. // initial x size CW_USEDEFAULT. SW_SHOWMINIMIZED  To display minimized window.To display maximized window. // initial y position CW_USEDEFAULT. This is the standard style for windows. 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. // initial y size NULL. indicating no other instances of the program were running. SW_SHOWNORMAL  To display normal window. Here's the CreateWindow call with comments identifying the parameters. //creation parameters The window created by this program is a normal overlapped window.Connexions module: m14425 27 [ other wndclass initialization] RegisterClass(&wc). The CreateWindow function call returns a handle to created window which is stored in the variable hwnd. The argument marked parent window handle is to set to NULL when creating a top level window such as an application window. The CreateWindow() function takes 11 parameters.1/ .

This is dened with the identiers beginning with the prex WM(Window Message) for each type of message. The window procedure can be dened like this: LRESULT CALLBACK wndproc(HWND hwnd. wndproc chooses to process four messages: WM_CREATE. The messages can be dened like this: switch(msg) { case WM_CREATE: [process WM_CREATE message] return 0. The rst parameter hwnd is the handle to window receiving the message.NULL. LPARAM lp) These parameters are identical to the rst four elds of the MSG structure. the window procedure should return 0. If a program creates multiple windows based on the same window class and hence the same window procedure. } return DefWindowProc(hwnd. This can be done through switch and case statement. hwnd identies the particular window receiving the message. The last two parameters are 32 bit message parameters that provide more information about the message. case WM_DESTROY : [process WM_DESTROY message] return 0. Message queue is maintained for each windows program currently running under windows. DispatchMessage(&msg).lp). In the sample windows program. WM_LBUTTONDOWN. The messages can be retrieved from the message queue by executing the message loop: While(GetMessage(&msg.1/ . WPARAM wp.msg. case WM_RBUTTONDOWN : [process WM_RBUTTONDOWN message] return 0. case WM_LBUTTONDOWN : [process WM_LBUTTONDOWN message] return 0.0. WM_RBUTTONDOWN and WM_DESTROY. The TranslateMessage call passes the msg structure back to windows for some keyboard translation. } The GetMessage call retrieves a message from a message queue and passes to window a pointer to a MSG structure named msg. The DispatchMessage call passes the msg structure back to windows and the windows then sends the message to the appropriate window procedure for processing. When an input event occurs windows translates the event in to a message that it places in the message queue. All the messages not to be processed must be passed to a windows function named The program must now make itself ready to read input from the user through mouse and keyboard. The value returned from DefWindowProc must be returned from the window procedure. The function call UpdateWindow causes the client area to be painted.Connexions module: m14425 28 If the second argument to ShowWindow is SW_SHOWNORMAL the client area of the window is erased with background brush specied in the window class. Windows Messages http://cnx. The second parameter is a number that identies the message.wp. Window Procedure The window procedure determines what the window displays in its client area and how the window responds to user input.0)) { TranslateMessage(&msg). UINT message. Handling Messages in Window Procedure After the UpdateWindow call the window is fully visible in the screen. Every message that window procedure receives is identied by a number. To process a message. A windows program can contain more than one window procedure.

Chapter  2 Basics of GDI and DC 14 2. Dierentiate Structured Programming and Object Oriented Programming. 3. WM_CHAR Message This message is used to retrieve ASCII keyboard inputs such as letters. 14. WM_CHAR. and fonts to write text. Message structure and explain them. paths. The color and style of the items you draw depends on the drawing objects  that is. An application creates a DC by using device context functions. This message is generated when the user presses a character with an ASCII value on keyboard. The device context is a GDI-managed structure containing information about the device. using the http://cnx. WM_QUIT Message This message indicates a request to terminate an application and is done when the application calls the PostQuitMessage The return statement exits from WinMain and terminates the program. You can use pens to draw lines and curves. 15. prex. 13. Write about the Windows Messages. closed gures. brushes. numbers and printable symbols. What is API? 6. and other devices. 7.Connexions module: m14425 29 Windows messages are sent by Windows to your application. Dene Object and Class. and fonts  that you create.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. What is DLL? 5. Applications direct output to a specied device by creating a device context (DC) for the device. The message is sent after the window image is removed from the screen. Explain the Message function calls used in Windows Programming. GDI returns a device context handle. These messages begin with the WM_ The WM_* messages are sent by windows and are usually handled by windows and views. For example WM_DESTROY is sent to the parent window before a child window is destroyed. 11. 2. WM_DESTROY Message This message noties the program that a window is being destroyed after it is removed from the screen. a child window control or has used an accelerator key. 4. 8. and bitmap images. Explain how to register the Window class. printers. WM_DESTROY and WM_QUIT message. Using GDI functions. some of the commonly processed windows messages are: WM_COMMAND. curves. Write short notes on Window Procedure. 12. pens. Explain the Windows Programming Model. such as its operating modes and current selections. you can draw lines. For example. Explain the GUI concepts. Write the Window Class structure. List out the options available to display the Window.1/ . Write short notes on Event Driven Programming. WM_COMMAND Message This message noties the program that the user has selected a menu item. What is Hungarian Notation? 9. which is used in subsequent calls to identify the device. Write short notes on Windows String Functions. It causes the GetMessage function to return a zero and drop out from message loop. Exercises 1 1. text. brushes to ll the interiors of closed gures. 10. An accelerator key is a key combination which is used to invoke the options of a menu and other controls.

With the InvalidateRect() function. it can play that metale any number of times.Connexions module: m14425 30 Every non-control window in common graphics (and every lisp-widget window) is automatically assigned a device-context.2 Device Context Returns an integer that identies the device-context of window if it has one.1 shows the diagrammatic representation of GDI. such as its technology type (display. 2. A devicecontext is a construct used in the Windows API to specify a set of parameters that are used when drawing on a window. but if you need to pass the window to a WINAPI function that calls for the window's device-context (or hDC).3 The WM_PAINT message The WM_PAINT message is a request to repaint the window.2 2. the mixing mode (also called the binary raster operation) that species how colors in a pen or brush combine with colors already on the display surface.1/ . 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.1 Graphics Device Interface 14. you can tell that the contents of a window are no longer valid so that it will need to be redrawn. If you do want to draw directly on a non-lisp control. Controls supplied by the OS (all controls except lisp-widgets). Applications use attribute functions to set the operating modes and current selections for the device. or other device) and the dimensions and resolution of the display surface. which it keeps until it is closed.4 Getting a Device Context Handle You can do this with the http://cnx. are not automatically given device-contexts in lisp since it is normally only the OS rather than lisp that draws on the control. it is also possible to trigger WM_PAINT from inside the application. In most cases. Logical devices give applications the means to store output in a form that is easy to send subsequently to a physical device. the WM_PAINT message will be triggerd from the outside. Applications can direct output to a physical device. an application can retrieve information about the capabilities of the device. you might want to send an immediate redraw request. then you must give the window of the control a device-context while drawing on it. such as a memory device or metale. Functions Figure 2. This means that the application will have to keep track of the current state. With the Invalidate() function. and the mapping mode that species how GDI maps the coordinates used by the application to the coordinate system of the device. printer. so that only that part will be redrawn. Every application is responsible for redrawing its window(s). on the other hand. you can specify that only part of the window content is invalid. sending the output to any number of physical devices. A common graphics application does not normally need to deal with a window's device-context directly. However. or nil otherwise. or to a "logical" device. The operating modes include the text and background colors. 14. UpdateWindow() function. After an application records output in a metale. such as a display or printer. Figure 2. Because paint message have very low priority. then you should pass the integer returned by this function for that argument. In this way. you can prevent the ickering of the screen when redrawing. so that it knows that to draw. The current selections identify which drawing objects are used when drawing output.1 2.

This value is nonzero if the application should erase the background.5 The Paint Structure(PAINTSTRUCT) The PAINTSTRUCT structure contains information for an application. fRestore Reserved. RECT rcPaint.Connexions module: m14425 31 There are two methods in getting a Device Context handle. This function lls the elds of the paint structure. statement like this: wndclass. Many windows This is indicated in the program with the http://cnx. rgbReserved Reserved used internally by the system. which has to be dened in window procedure like so: HDC hdc. These functions require the handle to window. [ GDI functions] EndPaint (hwnd. see the description of the hbrBackground member of the WNDCLASS structure. After the denition of HDC the program can use functions like TextOut. BYTE rgbReserved[32]. BOOL fErase. This value can be stored in a variable commonly named as hdc. The call to EndPaint releases the device context handle. Windows erases the background using the brush specied in the hbrBackground eld of the WNDCLASS structure that is used when registering the window class during WinMain initialization. used internally by the system. • • hdc Handle to the display DC to be used for painting. Two functions involved in this process are BeginPaint and EndPaint. This information can be used to paint the client area of a window owned by that application. 15 2. which is passed to the window procedure as an argument and the address of a structure variable of type PAINTSTRUCT which has to be dened within the window procedure like so: PAINTSTRUCT ps. BOOL fIncUpdate. • • • • rcPaint Species a RECT structure that species the upper left and lower right corners of the rectangle in which the painting is requested. BOOL fRestore. // handle to DC HDC is a data type dened as a 32 bit integer. fIncUpdate Reserved used internally by the system. 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. return 0.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) . The value returned by BeginPaint is a device context handle. // where ps is the paint structure variable While processing a WM_PAINT message the window procedure rst calls the function BeginPaint which causes the background of the invalid region to be erased and prepare the window for painting.&ps). For more information. This can be done with the statement like this: hdc = GetDC (hwnd) . The application is responsible for erasing the background if a window class is created without a background brush. The processing of WM_PAINT message looks like this: case WM_PAINT: hdc = BeginPaint(hwnd. The rst method is by processing WM_PAINT messages. typedef struct tagPAINTSTRUCT { // ps HDC hdc. } PAINTSTRUCT. fErase Species whether the background must be . programs specify a white brush for the windows background.&ps).

Do not call GetDC in one message and ReleaseDC in another message. 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. LONG tmAveCharWidth. LONG tmAscent. a program can determine font sizes by calling GetTextMetrics.1/ . BOOL TextOut( HDC hdc. In earlier versions of windows the system font was a xed pitch font in which all the characters had the same width.6 TextOut The TextOut function writes a character string at the specied location. 16 2. But now the system font is a raster font which means that the characters are dened as blocks of pixels. While GetDC returns a device context handle for writing on the client area of the window. The size of a character is based on the size of the video display. A function similar to GetDC is GetWindowDC. The fourth argument lpsring is a pointer to character string and the last argument cbString indicates the number of characters in the string. The second and third arguments x and y denes the starting point of the character string within the client area. typedef struct tagTEXTMETRIC { LONG tmHeight. Eg: TextOut (hdc.7 System Font and Text Metrics The device context denes the font that windows uses to display the text when TextOut function is called.y.x. LONG tmDescent. The rst 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. background color. LONG tmInternalLeading.17).Connexions module: m14425 32 [ GDI functions] ReleaseDC (hwnd. 2. LONG tmMaxCharWidth. GetDC is used while processing message and ReleaseDC is used to exit the window procedure. // x-coordinate of starting position int y.hdc). // y-coordinate of starting position LPCTSTR lpString. LONG tmExternalLeading. // pointer to string int cbString // number of characters in string ). GetWindowDC returns a device context handle for writing on the entire window. [ other structure elds] } To use the GetTextMetrics function a structure variable tm should be dened.LeftButtonPressed. TEXTMETRIC tm. menus and dialog boxes. GetTextMetrics requires a handle to a device context because it returns information about the font currently selected in the device context. using the currently selected font. The default font is a system font which is used by windows for text strings in title bars. and text color.To use the function GetWindowDC your program has to process WM_NCPAINT (non client paint) message. // handle to device context int x. The TEXTMETRIC structure has 20 elds but only the rst seven elds are essential. Just as a program can determine information about the sizes or metrics of user interface items by calling the GetSystemMetrics function. The functions GetDC and ReleaseDC should be called in pairs like BeginPaint and EndPaint.

The TEXTMETRIC structure contains two elds that describes the character width one is tmAveCharWidth eld which is a weighted average of lowercase characters and another is tmMaxCharWidth which is the width of the widest character in the font. see the following Remarks section. icon height. If the function succeeds.8 (a) nIndex parameter values Value SM_ARRANGE Meaning Flags specifying how the system arranged minimized windows. ReleaseDC (hwnd. continued on next page http://cnx. int GetSystemMetrics ( int nIndex) The nIndex parameter can be one of the following values. System metrics also describe other aspects of the system. the return value is zero. the return value is the requested system metric or conguration setting. respectively. These two values represent the maximum vertical extents of characters in the font above and below base line. Table 2. If the function fails. double-byte characters are supported. Typical system metrics include the window border width. The header le SYSMETS. 17 2. The term leading refers to the space that the printer inserts between the lines of text. scroll bars. It is an amount of space that the designer of the font suggests be added between successive rows of displayed System metrics are the dimensions of various display elements. such as whether a mouse is installed. 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. Safe Mode.8 System Metrics Display elements are the parts of a window and the display that appear on the system display screen. The most important value in TEXTMETRIC is the tmHeight which is the sum of tmAscent and tmDescent. hdc). All dimensions retrieved by GetSystemMetrics are in pixels. Applications can also retrieve and set the color of window elements such as menus. SM_CLEANBOOT Value that species how the system was started: 0 Normal boot1 Fail-safe boot2 Fail-safe with network bootFail-safe boot (also called SafeBoot. and so on. Note that all SM_CX* values are widths and all SM_CY* values are heights. GetSystemMetrics The GetSystemMetrics function retrieves various system metrics (widths and heights of display elements) and system conguration settings. or Clean Boot) bypasses the user's startup les. &tm). The GetSystemMetrics function retrieves the specied system metric.Connexions module: m14425 33 To determine the text metrics you get a handle to a device context and call GetTextMetrics hdc = GetDC (hwnd) .1/ . For more information about minimized windows. and buttons by using the GetSysColor and SetSysColor functions. GetTextMetrics (hdc .H responds to GetSystemMetrics function call. System metrics may vary from display to display. or a debugging version of the operating system is installed.

org/content/m14425/1. It allows the user to click and release the mouse button easily without unintentionally starting a drag operation. This is equivalent to the SM_CXEDGE value for windows with the 3-D look. SM_CYFIXEDFRAME Thickness of the frame around the perimeter of a window that has a caption but is not sizable. SM_CXFIXEDFRAME. in pixels. These values are in pixels. SM_CXEDGE. SM_CYDOUBLECLK Width and height of the rectangle around the location of a rst click in a double-click sequence. SM_CYBORDER Width and height of a window border.1/ .) To set the width and height of the double-click rectangle. The system cannot create cursors of other sizes.Connexions module: m14425 34 SM_CMONITORS Windows 98/Me. SM_CYDLGFRAME Same as SM_CXFIXEDFRAME and SM_CYFIXEDFRAME. call SystemParametersInfo with the SPI_SETDOUBLECLKHEIGHT and SPI_SETDOUBLECLKWIDTH ags. Number of SM_CMOUSEBUTTONS Number of buttons on mouse. The second click must occur within this rectangle for the system to consider the two clicks a double-click. in pixels. These are the 3-D counterparts of SM_CXBORDER and continued on next page http://cnx. SM_CYCURSOR Width and height of a cursor. or zero if no mouse is installed. SM_CXFIXEDFRAME is the height of Same as the horizontal border and SM_CYFIXEDFRAME is the width of the vertical border. in pixels. SM_CXDLGFRAME. SM_CYBORDER. in pixels. SM_CXDRAG. SM_CXDOUBLECLK. in pixels. SM_CYEDGE Dimensions of a 3-D border. (The two clicks must also occur within a specied time. SM_CXCURSOR. Windows 2000/XP: display monitors on the desktop. SM_CXDLGFRAME and SM_CYDLGFRAME. SM_CXBORDER. 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.

SM_CXFULLSCREEN. A window can override these values by processing the WM_GETMINMAXINFO message. SM_CXMAXTRACK. in pixels. in pixels. in pixels. SM_CYMAXTRACK Default maximum dimensions of a window that has a caption and sizing borders. 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. SM_CXMAXIMIZED. in pixels. Each item ts into a rectangle of this size when arranged. The user cannot drag the window frame to a size larger than these dimensions. in pixels. in pixels.Connexions module: m14425 35 SM_CXFOCUSBORDER. SM_CXICONSPACING. SM_CXHSCROLL. SM_CYFRAME Same as SM_CXSIZEFRAME and SM_CYSIZEFRAME. and height of a horizontal scroll bar. call the SystemParametersInfo function with the SPI_GETWORKAREA value. To get the coordinates of the portion of the screen not obscured by the system taskbar or by application desktop toolbars. The LoadIcon function can load only icons of these dimensions. SM_CYMAXIMIZED Default dimensions. SM_CYHSCROLL Width of the arrow bitmap on a horizontal scroll bar. SM_CYICON Default width and height of an icon. This metric refers to the entire desktop. SM_CYICONSPACING Dimensions of a grid cell for items in large icon view. in pixels. of a maximized toplevel window on the primary display monitor.1/ . These values SM_CXFRAME. SM_CXHTHUMB Width of the thumb box in a horizontal scroll bar. are in pixels. SM_CXICON. These values are always greater than or equal to SM_CXICON and SM_CYICON. SM_CYFULLSCREEN Width and height of the client area for a full-screen window on the primary display monitor. in pixels. continued on next page

in pixels. and SM_CYSIZEFRAME is the height of the vertical border. SM_CYMINIMIZED. SM_CXSMICON. SM_CXMIN. continued on next page http://cnx. in pixels. Small icons typically appear in window captions and in small icon view. in Dimensions of a grid cell for a minimized window. in pixels. SM_CYMINTRACK Minimum tracking width and height of a window. SM_CYSMICON Recommended dimensions of a small icon. Dimensions of a minimized window. These are the same values obtained by calling GetDeviceCaps (hdcPrimaryMonitor. SM_CYMINIMIZED SM_CXMINSPACING SM_CYMINSPACING Minimum width and height of a window. SM_YVIRTUALSCREEN metrics are the coordinates of the top-left corner of the virtual screen. in pixels. tual screen is the bounding rectangle of all disThe SM_XVIRTUALSCREEN. Windows 2000/XP: Width and The virSame as SM_CXFRAME A window can override these values by processing the These values are always greater than or equal to SM_CXMINIMIZED and height of the virtual screen. SM_CYVIRTUALSCREEN Dimensions of small caption buttons. SM_CYSIZEFRAME Thickness of the sizing border around the perimeter of a window that can be resized. in pixels. Each minimized window ts into a rectangle this size when arranged. SM_CXMENUSIZE. SM_CYMIN SM_CXMINIMIZED. SM_CYSCREEN Width and height of the screen of the primary display monitor. and SM_CYFRAME. WM_GETMINMAXINFO message. in pixels.1/ . Windows 98/Me. SM_CXSIZE. SM_CYMENUCHECK Dimensions of the default menu check-mark bitmap. SM_CXSCREEN. in pixels. in pixels. HORZRES/VERTRES). SM_CYMENUSIZE Dimensions of menu bar buttons.Connexions module: m14425 36 SM_CXMENUCHECK. SM_CYSIZE Width and height of a button in a window's caption or title bar. SM_CXMINTRACK. such as the child window close button used in the multiple document interface. in pixels. play monitors. in pixels. SM_CXSIZEFRAME. SM_CXSIZEFRAME is the width of the horizontal border. in pixels. The user cannot drag the window frame to a size smaller than these dimensions. SM_CXSMSIZE SM_CYSMSIZE SM_CXVIRTUALSCREEN.

TRUE FALSE or or nonzero zero if In- put Method Manager/Input Method Editor feaotherwise. Height of a single-line menu bar. To ensure that a language-dependent IME works. SM_IMMENABLED indicates whether the system is ready to use a Unicode-based IME on a Unicode application. SM_MIDEASTENABLED TRUE if the system is enabled for Hebrew and Arabic languages. SM_DEBUG TRUE or nonzero if the debug version of User. SM_CYVSCROLL Width of a vertical scroll bar. SM_IMMENABLED Windows tures are 2000/XP: enabled. FALSE or zero if the menus are left-aligned. in pixels. SM_CYCAPTION SM_CYMENU SM_CYSMCAPTION SM_CYVTHUMB Height of a caption area. Windows TRUE or nonzero if a mouse with a wheel is installed. in pixels. Otherwise the ANSI-toUnicode conversion may not be performed correctly. continued on next page http://cnx. or some components like fonts or registry setting may not be present. and height of the arrow bitmap on a vertical scroll bar. FALSE or zero otherwise. FALSE or zero otherwise. FALSE or zero otherwise. check SM_DBCSENABLED and the system ANSI code page.0 and later.1/ .org/content/m14425/1. SM_MOUSEPRESENT TRUE or nonzero if a mouse is installed.exe is installed. SM_MOUSEWHEELPRESENT Windows 98/Me: NT 4. Height of the thumb box in a vertical scroll bar.exe is installed. in pixels. in pixels. in pixels. SM_MENUDROPALIGNMENT TRUE or nonzero if drop-down menus are rightaligned with the corresponding menu-bar item. FALSE or zero otherwise. in pixels. Height of a small caption. SM_DBCSENABLED TRUE or nonzero if the double-byte character-set (DBCS) version of User.Connexions module: m14425 37 SM_CXVSCROLL.

SM_SHUTTINGDOWN Windows XP: TRUE if the current session is shutting down. SM_SLOWMACHINE TRUE if the computer has a low-end (slow) processor. otherwise. FALSE otherwise.1/ . The other bits are reserved for future use. SM_REMOTECONTROL Windows XP: This system metric is used in a Terminal Services environment. FALSE otherwise. SM_PENWINDOWS TRUE or nonzero if the Microsoft Windows for Pen computing extensions are the red. the return value is zero. FALSE or zero otherwise.0: This system metric is used in a Terminal Services environment. Windows 2000/XP: TRUE if all If the calling process is associated with the Terminal the display monitors have the same color format. FALSE. FALSE or zero otherwise. SM_SECURE SM_SAMEDISPLAYFORMAT TRUE if security is present. and blue pixels can be encoded with dierent numbers of bits. but dierent color formats.Connexions module: m14425 38 SM_NETWORK Least signicant bit is set if a network is present. it is cleared. green. SM_REMOTESESSION Windows NT 4. FALSE otherwise. If the calling process is associated with a Terminal Services client session. FALSE otherwise. FALSE otherwise. or those bits can be located in dierent places in a pixel's color value. Note that two displays can have the same bit depth. For example. Windows 98/Me. Server console session. or zero. the return value is TRUE or nonzero. otherwise. continued on next page http://cnx. Its value is TRUE if the current session is remotely controlled. SM_SWAPBUTTON TRUE or nonzero if the meanings of the left and right mouse buttons are swapped. 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.

Display elements are the parts of a window and the display that appear on the system display screen. at the upper-right to corner of the | Equivalent ARW_STARTTOP SRW_STARTRIGHT. Table 7 Table 2. Arrange vertically. ARW_TOPRIGHT Start screen. Windows left side The of 2000/XP: and all the display are top virtual screen Coof is virtual bounding rectangle monthe The The starting position can be one of the following values.8(d). right to left. top to bottom. blue (RGB) color value of the given element. for the screen. the return value is zero. left to right. If the nIndex parameter is out of range. Value ARW_DOWN ARW_LEFT ARW_RIGHT ARW_UP Meaning Arrange vertically. Equivalent to ARV_STARTTOP. ARW_TOPLEFT Start at the upper-left corner of the screen.1/ . 98/Me. metrics SM_CYVIRTUALSCREEN width and height of the virtual screen. SM_YVIRTUALSCREEN Windows ordinates the the itors. Arrange horizontally. Equivalent to ARW_STARTRIGHT. Table 2.8 (b) Starting position values and direction of screen The SM_ARRANGE setting species how the system arranges minimized windows. Value ARW_BOTTOMLEFT Meaning Start at the lower-left corner of the screen (default position). ARW_BOTTOMRIGHT Start at the lower-right corner of the screen. and consists of a starting position and a direction. Table 6 GetSystemMetrics(SM_CMONITORS) counts only display monitors. The parameter nIndex is used to retrieve the color and can have one of the values listed in the Table 2.Connexions module: m14425 39 SM_XVIRTUALSCREEN. The function returns the red. ARW_HIDE Hide minimized windows by moving them o the visible area of the screen. Because zero is also a valid RGB value. bottom to top. Table 8 GetSysColor The GetSysColor function retrieves the current color of the specied display element.8 (c) Lists the values of the direction in which to arrange the window. green. you cannot use GetSysColor to determine http://cnx. Arrange horizontally.

continued on next page http://cnx. COLOR_BTNFACE Face color for three-dimensional display elements and for dialog box backgrounds. size box. Active window title bar. COLOR_BTNSHADOW Shadow color for three-dimensional display elements (for edges facing away from the light source). Text in caption. and scroll bar arrow box. the Windows 2000/XP: Right side color in the color gradient of an active wintitle COLOR_ACTIVECAPTION left side color. COLOR_APPWORKSPACE Background color of multiple document interface (MDI) applications. Table 2. Instead. which returns NULL if the color is not bar. COLOR_ACTIVEBORDER COLOR_ACTIVECAPTION Active window border. Windows dow's 98/Me.) COLOR_3DSHADOW. Text on push buttons.Connexions module: m14425 40 whether a system color is supported by the current platform. COLOR_DESKTOP COLOR_BTNTEXT COLOR_CAPTIONTEXT COLOR_GRADIENTACTIVECAPTION Desktop. COLOR_BTNHILIGHT. COLOR_3DHILIGHT. use the GetSysColorBrush function. COLOR_3DFACE. DWORD GetSysColor ( int nIndex).8 (d) Color values for GetSysColor function call Value COLOR_3DDKSHADOW Meaning Dark shadow for three-dimensional display ele- ments. dows 2000/XP: Windows 98/Me. COLOR_BACKGROUND.1/ . WinHighlight color for three-dimensional display elements (for edges facing the light source. with to Use the determine species SPI_GETGRADIENTCAPTIONS SystemParametersInfo function whether the gradient eect is enabled. COLOR_BTNHIGHLIGHT COLOR_3DLIGHT Light color for three-dimensional display elements (for edges facing the light source. COLOR_3DHIGHLIGHT.) Species the left side color in the color gradient of an active window's title bar if the gradient eect is enabled.

1/ . COLOR_INACTIVECAPTION species the left side color. Windows XP: The color used to highlight menu items when the menu appears as a at menu. COLOR_INACTIVEBORDER COLOR_INACTIVECAPTION Inactive window border. ground color of the menu popup. dows 2000/XP: Windows 98/Me. Menu background. Windows 98/Me. Text color for tooltip controls. COLOR_HIGHLIGHT COLOR_HIGHLIGHTTEXT COLOR_HOTLIGHT Item(s) selected in a control. The highlighted menu item is outlined with COLOR_HIGHLIGHT. Text of item(s) selected in a control. COLOR_GRAYTEXT Grayed (disabled) text. Windows 2000/XP: executes the item. bar when menus appear as at menus. Windows 2000/XP: Right side color in the color gradient of an inactive window's title bar. Scroll bar gray area. COLOR_INACTIVECAPTIONTEXT COLOR_INFOBK COLOR_INFOTEXT COLOR_MENU COLOR_MENUHILIGHT Color of text in an inactive caption. COLOR_MENU continues to specify the back- continued on next page http://cnx.Connexions module: m14425 41 COLOR_GRADIENTINACTIVECAPTION Windows 98/ Single clicking a hot-tracked item Species the left side color in the color gradient of an inactive window's title bar if the gradient eect is enabled. COLOR_MENUTEXT COLOR_SCROLLBAR COLOR_WINDOW COLOR_WINDOWFRAME Text in menus. COLOR_MENUBAR Windows XP: The background color for the menu However. Inactive window caption. Background color for tooltip controls. Window background. This color is set to 0 if the current display driver does not support a solid gray color. WinColor for a hot-tracked item. Window frame.

The SetSysColors function changes the current session only. Similarly the approximate number of lowercase characters that can be displayed horizontally within the client area is equal to cxClient / cxChar This is used to display complex images on the monitor or printer. zero.9 Client area The client area is the portion of a window where the application displays output. such as text or graphics also called a client rectangle. These are: • Bitmaps: A bitmap is an array of bits that represent the attributes of the individual pixels in an image (1 bit per pixel in a black-and-white display. which supports only Unicode. which are called primitives. For Windows. It also directs the system to repaint the aected portions of all currently visible windows. Knowing the size of window's client area the user can display the text within the client area if the client area is not large enough to hold everything. the macro forces the compiler to convert ANSI characters to Unicode characters. The new colors are not saved when the system terminates 2. If the function succeeds.10 GDI Primitives The types of graphics displayed on the screen can themselves be divided in to several categories. return 0. If the function fails. These two variables are set static because they are set while processing one message and used while processing another message. cyClient . const COLOREF* lpargbvalues). Bitmaps are also used to display small images such as icons. For example. determining the size of the client area is to process the WM_SIZE message whenever there is a change in window size. The number of full lines of text displayable within the client area can be calculated using the formula : cyClient / cyChar This is zero if the height of the client area is too small to display a full character. The dimensions of the client A better method in area is available from the GetSystemMetrics call (SM_CXFULLSCREEN and CY_FULLSCREEN). The second parameter is a pointer to an array of integers that specify the display elements to be changed. For this two static variable has to be dened in the window procedure as follows: static int cxClient.Connexions module: m14425 42 COLOR_WINDOWTEXT Text in windows. cyClient = HIWORD (lparam). Display elements are the various parts of a window and the display that appear on the system display screen. The GetClientRect function can be used to determine the dimensions of the client area. • Text: A Win32 macro that exists so that code can be compiled either as American National Standards Institute (ANSI) text or as Unicode. The rst parameter cElements indicates the number of display elements in the lpaElements array. BOOL SetSysColors ( int cElements . green. The lparam variable passed to the window procedure contains the width of the client area in the low word and the height in the high word. passing the ANSI http://cnx. The WM_SIZE message can be dened as: case WM_SIZE : cxClient = LOWORD (lparam). Table 9 SetSysColors The SetSysColors function sets the colors for one or more display elements. mouse cursors and buttons that appear in the toolbar. const INT* lpaElements. multiple bits per pixel in a color or grayscale display).1/ . The third parameter is a pointer to an array of COLORREF values that contain the new red. the return value is a nonzero value. blue (RGB) color values for the display elements in the array pointed to by the lpaElements parameter. the return value is The SetSysColors function sends a WM_SYSCOLORCHANGE message to all windows to inform them of the change in color.

rectangles. a pattern (which can be a series of horizontal. GDI supports straight lines.11 Drawing vertical or diagonal hatch marks) or a bitmapped image that is repeated vertically or horizontally within the area.1/ . Paint programs that oer a variety of brush shapes can produce brushstrokes of varying width and. 2. in some cases.Connexions module: m14425 43 string "Hello Windows  through the TEXT macro converts all characters in the string to 16-bit wide characters. • Filled areas: To sketch or ll in areas of a drawing with the color and pattern. ellipses. shadowing or calligraphic eects. • Lines and Curves: A line is a set of highlighted pixels on a video display (or a series of dots on a printed page) that is dened by two points: a starting point and an ending point. brush is the tool used. Line and Curve Windows can draw straight lines. arcs that are partial curves on the ellipse and Bezier splines. Dierent type of curve can be drawn as a polyline which is a series of very short lines that dene curve. A brush can be solid color. Furthermore GDI draws lines using pen selected in the device context. curved lines and Bezier splines through the following functions: • • • • • SetPixelDraws a single point MoveToSets the current position in preparation for drawing LineToDraws a line from the current position to the end of the line PolylineConnects a set of points with line segments PolylineToConnects a set of points with line segments beginning with the current position and moves the current position to the end of the polyline • ArcDraws an arc ArcTo draws an arc and moves the current position to the end of the arc • • PolyBezierDraws one or more Bezier splines PolyBezierToDraws one or more Bezier splines and moves the current position to the end of the nal spline • PolyDrawDraws a series of line segments and Bezier splines through a set points and moves the current position to the end of the nal line segment or spline The functions that draw lines but that also ll the enclosed area within the gure they draw are as follows: • ChordDraws a closed gure bounded by the intersection of an ellipse and a line • • • • • EllipseDraws a circle or an ellipse PieDraws a pie shaped wedge PolygonConnects a set of points to form a polygon RectangleDraws a rectangle with square corners RoundRectDraws a rectangle with rounded corners http://cnx.

..12 Using Stock Pens The pen determines the lines color. The Ex functions pass the x.. Under Windows 3. You can dene a variable for using this type denition: HPEN hpen.and y-coordinates are 16 bits each and are packed into the 32-bit (DWORD) function return value. the x..x support these new functions. Now the BLACK_PEN is the current pen. . The type HPEN is a handle to pen.-. Note that the information returned by MoveToEx is ignored: MoveToEx ( hDC. totaling 64 bits. If you want to use the WHITE_PEN then you can get that handle to that stock object and select in to the device context in one statement: SelectObject (hdc .. you can pass NULL to this parameter.and y-coordinates returned by the Windows 3. NULL_PEN is the pen that doesn't draw. .Connexions module: m14425 44 Default line color is black and ll color is white.hpen).-. Each Ex function includes an additional parameter that points to a location to receive data. PS_DASHDOT-. .-. PS_SOLID____________________________ PS_DASH PS_DOT. GetStockObject (WHITE_PEN)). In windows program pen can be referred using a handle.-. . this data provides the same information as the corresponding function's return value. After releasing the device context you can delete the pen by calling DeleteObject.x function is replaced by a Win32 function with the same name. ..1/ . The iPenStyle argument determines whether the pen draws a solid line or line with dash and dots. . iWidth. . . but with an Ex sux added. NULL ).-.x version. y ). .-.. the coordinates are 32 bits each.-. GetStockObject (BLACK_PEN)). The default pen is BLACK_PEN which draws a solid black line. and are thus too large to t into a single return value. 2. . The rst function species the point at which the line begins and the second function species the end point of the line: In Windows 3.. . You can also create your own customized pens.13..-.. x. . . . If you do not need this information. Selecting and Deleting Pens Apart from solid BLACK_PEN and WHITE_PEN you can create your own pens using CreatePen function call.-.x..and y-coordinates using an additional parameter instead of a return 2. Each Windows 3. . Apart from BLACK_PEN windows provides other two pens such as WHITE_PEN and NULL_PEN. .. For example if you want to use the stock pen called BLACK_PEN you can dene the handle like this: hpen = GetStockObject (BLACK_PEN) To select that pen in to Device Context use the denition: SelectObject (hdc. . After doing so the pen is no longer valid. The argument may be any one of the pen styles listed in gure 2. a call to the MoveTo function can be written as follows: MoveTo( hDC. In the portable version supported by both versions of Windows. .x.-.. crColor). . . . . Instead of dening hpen variable explicitly you can combine the StockObject and SelectObject call in to one statement: SelectObject (hdc.-.-.-. The GetStockObject function call is used to obtain the handle to one of the stock pens. the call to MoveTo is rewritten as follows. . . After the function call. Both Win32 and Windows 3.13 Creating. After this call any line you draw will use the BLACK_PEN until you select another pen or release the device context handle.-.-.-. pass NULL as the last parameter unless you need to use the x. the largest valid size.-.. . x. dotted or dashed. PS_NULL PS_INSIDEFRAME____________________ http://cnx.-. y. width and style which can be solid. . As a general rule. To draw straight line you must call two functions.-.-.-. . The syntax for CreatePen looks like this: hpen = CreatePen ( iPenStyle .-. You can select the pen in to the device context by calling the SelectObject and then draw lines using new pen. In Win32.

[line drawing functions] You can delete the pens by processing WM_DESTROY message: DeleteObject(hpen1). wc. hpen2 = CreatePen (PS_SOLID.hIcon = LoadIcon(NULL. The current background color can be obtained by calling the GetBkColor function. First you have to dene static variables for storing the handles to these pens: Static HPEN hpen1 .cbSize = sizeof(WNDCLASSEX). When you draw lines you will be using red dashed pens by executing the above = 0. a red pen of width1 and a black dotted pen. Now an empty project without using MFC classes is created.TRANSPARENT) .hInstance = hInstance. Similarly the background color can be changed using the command: SetBkColor (hdc. The default background mode is opaque which uses the default background color white. Enter the code given below in the implementation le (Graph.lpfnWndProc = WndProc. hpen3 = CreatePen(PS_DOT. During processing of WM_CREATE you can create the three pens: hpen1 = CreatePen (PS_SOLID.1. int nCmdShow) {WNDCLASSEX wc.cpp). For example if your program uses three pens . DeleteObject(hpen2). HWND hwnd. wc. wc.3. HINSTANCE hPrevInstance.1/ . Example program using pen styles in drawing shapes Create an application named GraphicsDemo by selecting the project type Win 32 Application in the appwizard and click OK. Click File->New and then select the option C++ Source File and give a name to the . The PS_INSIDEFRAME is the only pen style which uses dithered color only when the width is greater than 1.13 Pen Styles The iWidth argument is the width of the pen. DeleteObject(hpen3). Furthermore the coloring of the gaps between the dashes and the dots needs two attributes such as the background mode and the background color. MSG Msg. a black pen of width 3. You can also change the background mode to be transparent which prevents the windows from lling in the gaps by using the command: SetBkMode (hdc.cpp implementation le (here the name is Graph.0.0). hpen2 . During processing of WM_PAINT message you can select one of these pens in to the device context and draw with it: SelectObject (hdc.RGB(255.CreatePen(PS_DASH. The stock pens are one pixel wide. The current background mode can be obtained by calling GetBkMode. wc. LPSTR lpCmdLine.0. If the value of iWidth argument is zero then Windows can use one pixel for the pen width. int WINAPI WinMain(HINSTANCE hInstance. You can also combine the CreatePen and SelectObject calls in the same statement: SelectObject (hdc.Connexions module: m14425 45 Figure 2. wc.cbClsExtra = 0.0)). hpen3.0. http://cnx.IDI_APPLICATION).hpen1).cbWndExtra = 0.hpen2) [ line drawing functions ] SelectObject(hdc.0).cpp).crColor). The crColor argument species the color of the pen.0)). wc.0.RGB(255.

wc. return 0. "Window Registration Failed!". if(!RegisterClassEx(&wc)) {MessageBox(NULL. "Graphics Demo Program". } return Msg. wc. DispatchMessage(&Msg).hbrBackground = (HBRUSH)(COLOR_WINDOW+1). 0. Build and Execute the program. NULL. nCmdShow). > 0) http://cnx. 0) {TranslateMessage(&Msg). You will get dierent shapes in the output window as shown in gure 2. NULL. g_szClassName. "Error!". IDI_APPLICATION). NULL). CW_USEDEFAULT.hCursor = LoadCursor(NULL.lpszClassName = g_szClassName. } In this application Pen style is used to draw shapes. if(hwnd == NULL) {MessageBox(NULL.lpszMenuName = NULL. CW_USEDEFAULT.hIconSm = LoadIcon(NULL. return 0. "Window Creation Failed!". "Error!". MB_ICONEXCLAMATION | MB_OK). IDC_ARROW). NULL.wParam. } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE. } ShowWindow(hwnd. wc. while(GetMessage(&Msg.13. 240. 120. hInstance. WS_OVERLAPPEDWINDOW. UpdateWindow(hwnd). Compile. MB_ICONEXCLAMATION | MB_OK).1/ .Connexions module: m14425 46 wc.

Connexions module: m14425 47 Figure 2. Polygon Where HBRUSH is a handle to the brush. The gure is lled with the current brush selected. To draw the gure without border NULL_PEN can be used as: SelectObject (hdc.) with the current pen selected as well as with the current background mode and background color. BLACK_BRUSH and HOLLOW_BRUSH or NULL_BRUSH. for example the BLACK_BRUSH by calling the GetStockObject: hbrush = GetStockObject ( BLACK_BRUSH). To draw the outline of the gure without lling the interior NULL_BRUSH can be used as: SelectObject(hdc. You can select the brush in to the device context with the function SelectObject. You can get any one of the brush. The function to create a logical brush is: http://cnx. You can then select in to the device context by calling the SelectObject as: SelectObject(hdc. First you have to dene a variable for the brush handle: HBRUSH hbrush.13 Running Instance of Graphics Demo Program 2. Any one of the brush can be selected as the same way as you select the stock pen. LTGRAY_BRUSH. DKGRAY_BRUSH..1/ . The interiors of the gures can be lled with the current brush selected in the device context. Chord. Ellipse. Apart from the default brush windows uses ve more brushes such as: GRAY_BRUSH.14 Filling Enclosed Areas Windows can draw the outline of the gure (Rectangle.hbrush). RoundRect. Now when you draw a Rectangle the interior will be black.GetStockObject (NULL_PEN)). The default brush is the WHITE_BRUSH.GetStockObject(NULL_BRUSH)).

POINT parray[10]={10.GetStockObject(GRAY_BRUSH)).70. break. } int WINAPI WinMain(HINSTANCE hInstance.70.90.&ps). Click File->New and then select the option C++ Source File and give a name to the .90. case WM_CLOSE: DestroyWindow(hwnd). You can later delete a created brush with DeleteObject function: DeleteObject(hbrush).crColor) The hatchstyle argument species one of the hatch styles shown below.70. PAINTSTRUCT ps. Polygon(hdc.30}.//rst parameter handle to device context. return 0. Once you have a handle to the brush you can select the brush in to the device context using SelectObject: SelectObject(hdc.cpp). LPARAM lParam) {HDC hdc.Connexions module: m14425 48 hbrush = CreateSolidBrush (crColor) . function for creating the hatch brush is: hbrush = CreateHatchBrush (hatchstyle. UINT msg.10). HINSTANCE hPrevInstance. WPARAM wParam. case WM_DESTROY: PostQuitMessage(0).cpp implementation le (here the name is Filling.50.&ps).parray. third count of polygon's vertices EndPaint(hwnd.30.1/ .50. msg. You can also create a brush with hatch marks made up of horizontal. #include <windows. break.50.cpp). SetPolyFillMode(hdc.10. Now an empty project without using MFC classes is created. lParam).30.10. Enter the code given below in the implementation le (Filling.90.second CONST POINT //*lpPoints pointer to polygon's vertices. SelectObject(hdc.70. LRESULT CALLBACK WndProc(HWND hwnd.h> const char g_szClassName[] = "myWindowClass".ALTERNATE).hbrush). switch(msg) { case WM_PAINT: hdc=BeginPaint(hwnd.90. } return 0.50.30. default: return DefWindowProc(hwnd. Example Program for lling the area of shapes Create an application named FillArea by selecting the project type Win 32 Application in the appwizard and click OK. vertical or diagonal lines. The • • • • • • HS_HORIZONTAL: Horizontal Hatch HS_VERTICAL: Vertical Hatch HS_FDIAGONAL: Upward hatch (left to right) at 45 degrees HS_BDIAGONAL: Downward hatch (left to right) at 45 degrees HS_CROSS: Horizontal and vertical crosshatch HS_DIAGCROSS: Crosshatch at 45 degrees The crColor argument species the color of the hatch lines. wParam.

lpszMenuName = NULL.hInstance = hInstance. DispatchMessage(&Msg). "Error!". CW_USEDEFAULT. if(!RegisterClassEx(&wc)) {MessageBox(NULL. "Filled Area". MB_ICONEXCLAMATION | MB_OK).1/ . NULL. wc. 240. MSG Msg. > 0) http://cnx.cbWndExtra = 0. wc. IDC_ARROW). } In this application brush style is used to ll the area of polygon. if(hwnd == NULL) {MessageBox(NULL. wc. NULL. NULL).Connexions module: m14425 49 LPSTR lpCmdLine. wc. hInstance.cbSize = sizeof(WNDCLASSEX). Build and Execute the program you will get the output as shown in gure 2. } ShowWindow(hwnd. return 0.cbClsExtra = 0.lpfnWndProc = WndProc.hIconSm = LoadIcon(NULL. } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE. WS_OVERLAPPEDWINDOW. 120. MB_ICONEXCLAMATION | MB_OK).14. } return Msg. wc. 0) {TranslateMessage(&Msg).style = 0. NULL. wc. UpdateWindow(hwnd). wc. g_szClassName. "Window Registration Failed!".wParam. "Error!".IDI_APPLICATION). return 0. "Window Creation Failed!".org/content/m14425/1. while(GetMessage(&Msg. wc. wc. wc. Compile. HWND hwnd.hIcon = LoadIcon(NULL. nCmdShow). int nCmdShow) { WNDCLASSEX wc. wc. wc.lpszClassName = g_szClassName. 0.hbrBackground = (HBRUSH)(COLOR_WINDOW+1). IDI_APPLICATION).hCursor = LoadCursor(NULL. CW_USEDEFAULT.

are more important to windows than to windows applications. For these keys windows generates only keystroke messages. For keystroke combinations that result in displayable characters windows sends both keystroke and character messages.Connexions module: m14425 50 Figure 2. and keyboard equivalents for the virtual-key codes used by the Windows operating system.15 Virtual Key Codes Symbolic constant VK_LBUTTON VK_RBUTTON VK_CANCEL VK_MBUTTON  VK_BACK VK_TAB Value (Hex) 01 02 03 04 0507 08 09 Mouse or keyboard equivalent Left mouse button Right mouse button Control-break processing Middle mouse button (three-button mouse) Undened BACKSPACE key TAB key continued on next page http://cnx. There are two types of keystrokes such as System keystroke and Nonsystem keystroke. WM_SYSKEYUP. The codes are listed in numeric order in Table 2. hexadecimal values. The following table shows the symbolic constant names.1/ .15 Keyboard Messages The message that an application receives from windows about the keyboard events shows the dierence between keystrokes and characters. Virtual Key Codes The virtual key code identies the key being pressed or released. The SYS in WM_SYSKEYDOWN and WM_SYSKEYUP stands for system and refers to system keystrokes that Nonsystem keystroke messages refer to messages such as WM_KEYDOWN and function keys. Table 2.14 Running Instance of FillArea Program 2. The virtual key code is stored in the wparam parameter . Keyboard is a collection of keys. WM_KEYDOWN. Pressing the key and releasing the key is called as a keystroke. WM_SYSKEYDOWN) wparam is a virtual key code that identies the key being pressed or released and lparam contains other data pertaining to keystroke.15. For all the four keystroke messages (WM_KEYUP. cursor movement keys do not generate characters. But some keys such as shift.

org/content/m14425/1.1/ .Connexions module: m14425 51  VK_CLEAR VK_RETURN  VK_SHIFT VK_CONTROL VK_MENU VK_PAUSE VK_CAPITAL   VK_ESCAPE  VK_SPACE VK_PRIOR VK_NEXT VK_END VK_HOME VK_LEFT VK_UP VK_RIGHT VK_DOWN VK_SELECT 0A0B 0C 0D 0E0F 10 11 12 13 14 1519 1A 1B 1C1F 20 21 22 23 24 25 26 27 28 29 2A Undened CLEAR key ENTER key Undened SHIFT key CTRL key ALT key PAUSE key CAPS LOCK key Reserved for Kanji systems Undened ESC key Reserved for Kanji systems SPACEBAR PAGE UP key PAGE DOWN key END key HOME key LEFT ARROW key UP ARROW key RIGHT ARROW key DOWN ARROW key SELECT key OEM specic EXECUTE key PRINT SCREEN key for Windows 3.0 and later INS key DEL key VK_EXECUTE VK_SNAPSHOT VK_INSERT VK_DELETE 2B 2C 2D 2E continued on next page http://cnx.

Connexions module: m14425 52 VK_HELP VK_0 VK_1 VK_2 VK_3 VK_4 VK_5 VK_6 VK_7 VK_8 VK_9 2F 30 31 32 33 34 35 36 37 38 39 3A40 HELP key 0 key 1 key 2 key 3 key 4 key 5 key 6 key 7 key 8 key 9 key Undened A key B key C key D key E key F key G key H key I key J key K key L key M key N key O key P key VK_A VK_B VK_C VK_D VK_E VK_F VK_G VK_H VK_I VK_J VK_K VK_L VK_M VK_N VK_O VK_P 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 continued on next page .

1/ .Connexions module: m14425 53 VK_Q VK_R VK_S VK_T VK_U VK_V VK_W VK_X VK_Y VK_Z VK_LWIN VK_RWIN VK_APPS 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E5F Q key R key S key T key U key V key W key X key Y key Z key Left Windows key (Microsoft Natural Keyboard) Right Windows key (Microsoft Natural Keyboard) Applications key (Microsoft Natural Keyboard) Undened Numeric keypad 0 key Numeric keypad 1 key Numeric keypad 2 key Numeric keypad 3 key Numeric keypad 4 key Numeric keypad 5 key Numeric keypad 6 key Numeric keypad 7 key Numeric keypad 8 key Numeric keypad 9 key Multiply key Add key Separator key Subtract key VK_NUMPAD0 VK_NUMPAD1 VK_NUMPAD2 VK_NUMPAD3 VK_NUMPAD4 VK_NUMPAD5 VK_NUMPAD6 VK_NUMPAD7 VK_NUMPAD8 VK_NUMPAD9 VK_MULTIPLY VK_ADD VK_SEPARATOR VK_SUBTRACT 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D continued on next page

1/ .Connexions module: m14425 54 VK_DECIMAL VK_DIVIDE VK_F1 VK_F2 VK_F3 VK_F4 VK_F5 VK_F6 VK_F7 VK_F8 VK_F9 VK_F10 VK_F11 VK_F12 VK_F13 VK_F14 VK_F15 VK_F16 VK_F17 VK_F18 VK_F19 VK_F20 VK_F21 VK_F22 VK_F23 VK_F24 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80H 81H 82H 83H 84H 85H 86H 87H 888F Decimal key Divide key F1 key F2 key F3 key F4 key F5 key F6 key F7 key F8 key F9 key F10 key F11 key F12 key F13 key F14 key F15 key F16 key F17 key F18 key F19 key F20 key F21 key F22 key F23 key F24 key Unassigned NUM LOCK key VK_NUMLOCK 90 continued on next page

break. } return Also called a client rectangle.Connexions module: m14425 55 VK_SCROLL 91 SCROLL LOCK key Table 10 2.MB_OK|MB_ICONINFORMATION).MB_OK|MB_ICONINFORMATION). LPARAM lParam) { switch(msg) {case WM_LBUTTONDOWN: MessageBox(GetFocus(). A window's nonclient area consists of the border."About". The parts of a window that are not a part of the client area. #include <windows. and scroll bar.16 Mouse Messages Windows sends keyboard messages only to the window that has the input focus. There are two types of mouse messages such as client area mouse messages and Non client area mouse messages. title bar. Now an empty project without using MFC classes is created. Enter the code given below in the implementation le (Mouse. case WM_DESTROY: PostQuitMessage(0)."You have pressed left mouse button".MB_OK|MB_ICONINFORMATION). such as text or graphics. case WM_RBUTTONDOWN: MessageBox(GetFocus()."You have pressed right mouse button". menu bar. break.h> const char g_szClassName[] = "myWindowClass". Click File->New and then select the option C++ Source File and give a name to the . case WM_KEYDOWN: MessageBox(0.16 (a) Client area mouse messages Button Pressed Released Pressed (second click) LeftWM_LBUTTONDOWN WM_LBUTTONUP WM_LBUTTONDBLCLK MiddleWM_MBUTTONDOWN WM_MBUTTONUP WM_MBUTTONDBLCLK RightWM_RBUTTONDOWN WM_RBUTTONUP WM_RBUTTONDBLCLK Table 2. break. default: return DefWindowProc(hwnd. But mouse messages are dierent. UINT msg.1/ . break. } http://cnx. lParam). a window procedure receives mouse messages whenever the mouse passes over the window or clicked within the window."About".cpp). wParam."You have pressed down arrow key". break."About". Table 2. The client area is the portion of a window where the application displays output.16 (b) Non Client area mouse messages Button Pressed Released Pressed (second click) LeftWM_NCLBUTTONDOWN WM_NCLBUTTONUP WM_NCLBUTTONDBLCLK Middle WM_NCMBUTTONDOWN WM_NCMBUTTONUP WM_NCMBUTTONDBLCLK RightWM_NCRBUTTONDOWN WM_NCRBUTTONUP WM_NCRBUTTONDBLCLK Example program for mouse and keyboard messages Create an application named MouseKeyMsg by selecting the project type Win 32 Application in the appwizard and click OK. case WM_CLOSE: DestroyWindow(hwnd). msg. WPARAM wParam.cpp).cpp implementation le (here the name is Mouse. LRESULT CALLBACK WndProc(HWND hwnd.

NULL. while(GetMessage(&Msg.cbSize = sizeof(WNDCLASSEX). return 0. MSG Msg. int nCmdShow) { WNDCLASSEX wc. } ShowWindow(hwnd. MB_ICONEXCLAMATION | MB_OK).hIconSm = LoadIcon(NULL. if(!RegisterClassEx(&wc)) {MessageBox(NULL. hInstance. > 0) http://cnx. wc. NULL). wc. NULL. DispatchMessage(&Msg). 0. "Error!". The output of the program is shown in gure 2.hInstance = hInstance. } Compile. Build and Execute the program. wc. "Window Registration Failed!". HWND hwnd.IDI_APPLICATION).style = 0. IDC_ARROW).hCursor = LoadCursor(NULL. NULL. CW_USEDEFAULT. "Error!". LPSTR lpCmdLine. return 0. UpdateWindow(hwnd). g_szClassName. wc. wc. 240. MB_ICONEXCLAMATION | MB_OK). CW_USEDEFAULT. wc. "Mouse and Key operations". WS_OVERLAPPEDWINDOW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1).cbWndExtra = 0. wc.wParam.hIcon = LoadIcon(NULL.lpfnWndProc = WndProc. wc. IDI_APPLICATION). wc.lpszClassName = g_szClassName.1/ . } return wc.16. wc. if(hwnd == NULL) {MessageBox(NULL.Connexions module: m14425 56 int WINAPI WinMain(HINSTANCE hInstance. } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE. wc.cbClsExtra = 0. nCmdShow). 120. 0) {TranslateMessage(&Msg). HINSTANCE hPrevInstance.lpszMenuName = NULL. "Window Creation Failed!".

But in reality you should put them in a dialog box.CreateWindowEx. 3. Write a Windows Program to draw a Bezier Spline. 12. if you want to create a button. 8.1 Child Window Controls Windows provides several predened window classes which we can readily use in our own programs.Connexions module: m14425 57 Figure 2. The control ID must be unique among the controls. Dene DC. List the Paint Structure (PAINTSTRUCT) and explain it. What are the GDI Primitives? 9. In order to use a child window control. Controls can be placed on a normal window by using the Create command with various styles to design them. 11. Write the syntax of TextOut function.16 Running Instance of MouseKeyMsg Program Exercises 2 1. The other parameters you must ll in are the parent window handle and the control ID.CreateWindowEx. 10. Dene System Metrics. The class name parameter MUST be the predened class name. They relieve the burden from programmers enormously so you should use them as much as possible. The child window controls process their own mouse and keyboard messages and notify the parent window when their states have changed. List out the Pen and Brush Styles. radio checkboxes. Note that you don't have to register the window class since it's registered for you by Windows.CreateWindow or win. List out the Mouse and Keyboard Messages. http://cnx. you must create it with win. edit controls. You use it to dierentiate between the controls. What is GDI? 2. 6. What is Client area and Non Client area. 5. you must specify "button" as the class name in win. Examples of predened window classes are buttons. etc. Write a Windows Program to draw a Sine Wave. Say. listbox.1/ . What is WM_PAINT Message? 4. The control ID is the ID of that control. 7. Most of the time we use them as components of a dialog box so they're usually called child window controls. Chapter 3 Windows Controls and Resources 3.

Each child window control has dierent notication codes. it will send messages notifying the parent window when its state has changed. They can have a variety of styles as shown below: • • BS_AUTOCHECKBOX Same as a check box.2 Button Class Buttons are Windows Controls that respond to user clicks. Any text associated When combined with a radio-button or check-box style.2. 3. button by pressing the ENTER key. It's an extremely useful function since it can send messages to any window provided you know its window handle. BS_AUTORADIOBUTTON style in the same group. Radio buttons are usually used in groups of related but mutually exclusive • BS_3STATE Same as a check box. automatically highlights itself and removes the selection from any other radio buttons with the same • • • BS_AUTO3STATE user selects it. the parent window must process win. The examples in this chapter uses dialog box to place various controls. BS_DEFPUSHBUTTON (the default option). Normally. They are created with the CreateWindow or CreateWindowEx Window function. except that a check mark appears in the check box Same as a radio button. the check mark disappears the next time the user selects the box. This style enables the user to quickly select the most likely option • • • • BS_GROUPBOX BS_LEFTTEXT Creates a rectangle in which other buttons can be grouped. by calling win.SendMessage function sends the specied message with accompanying values in wParam and lParam to the window specied by the window handle. except that the box can be dimmed as well as checked. the button when the user selects the box. combined with the BS_LEFTTEXT style). the notication code in the high word of wParam. BS_CHECKBOX Same as a three-state check box. So.Connexions module: m14425 58 After the control was created. the text appears on the Creates a pushbutton that posts a WM_COMMAND message to the owner Creates a small circle that has text displayed to its right (unless this style is with this style is displayed in the rectangle's upper-left corner. left side of the radio button or check box.1/ . you create the child windows during win. The possible button notication messages are: BN_CLICK BN_DBCLICK BN_PAINT BN_KILLFOCUS BN_HILITE BN_UNHILITE http://cnx. BS_PUSHBUTTON BS_RADIOBUTTON window when the user selects the button. The child window sends win. WM_COMMAND messages to be able to receive notication codes from the child windows. except that the box changes its state when the Creates a small square that has text displayed to its right (unless this style is Creates a button that has a heavy black border.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 user can select this combined with the BS_LEFTTEXT style).SendMessage function.WM_COMMAND messages to the parent window with its control ID in the low word of wParam. The notication code indicates in more detail what the message means. The parent window can send commands to the child windows too.WM_CREATE message of the parent window. win. 3. The program traps the WM_COMMAND message and displays the values of wparam (child window ID and notication code) and lparam (child window handle). and its window handle in lParam. after creating the child windows. refer to your Win32 API reference for more information. except that when the user selects it. The dimmed state typically is used to show that a check box has been disabled.

must be zero The BM_SETCHECK and BM_GETCHECK messages are not used by push button because they do not retain on/o information. The rectangle takes up the full height and width of the dimension given in the CreateWindow.3 Check Boxes An interactive control found in graphical user interfaces.Connexions module: m14425 59 BN_PUSHED BN_UNPUSHED BN_DISABLE BN_SETFOCUS BN_KILLFOCUS In addition to the notication messages mentioned above there are also button messages each begins with letter BM. It has no eect on the check state or a radio button or check box. An application sends a BM_SETSTATE message to change the highlight state of a button. When an option is selected. The hwndButton window handle is the value returned from the CreateWindow call.2. The value TRUE is returned if the button is depressed and FALSE if it is not depressed. // not used. 3. You can also send a BM_GETSTATE message to push button. // not used. BM_SETSTATE message syntax: wParam = (WPARAM) fstate.2 Push Buttons A small rectangular control that a user can turn on or o. An application sends a BM_GETSTATE message to determine the state of a button or check box.2. This call causes the button to be depressed: SendMessage(hwndButton. // highlight state lParam = 0. has a raised appearance in its default o 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/o indication. The highlighting is removed when http://cnx. the user releases the mouse button.0). an X or a check mark appears in the box. Check boxes are used to enable or disable one or more features or options from a set. must be zero where fState is the value of wParam and species whether the button is to be highlighted. This message always returns zero. The two most common styles of check box are BS_CHECKBOX and BS_AUTOCHECKBOX.1. A push To return to the normal state the call to be used is: SendMessage(hwndButton. You can set the check state of the check box with the message BM_SETCHECK. The highlight state indicates whether the button is highlighted as if the user had pushed it. Most applications do not require this information.0). The button messages are: BM_GETCHECK BM_GETIMAGE BM_GETSTATE BM_SETCHECK BM_SETIMAGE BM_SETSTYLE BM_CLICKED 3.0. must be zero lParam = 0. A value of FALSE or zero removes any highlighting. also known as a command button. A value of TRUE or nonzero highlights the button.BM_SETSTATE. BM_GETSTATE message syntax: wParam = 0.1/ .BM_SETSTATE. Highlighting only aects the appearance of a button. There are two types of push buttons BS_PUSHBUTTON and BS_DEFPUSHBUTTON where DEF stands for default. These messages are used by the window procedure to send messages to the child window control. // not used. BM_SETCHECKMESSAGE has two parameters: A button is automatically highlighted when the user positions the cursor over it and presses and holds the left mouse button.

change the text of a control in another application. or a bitmap.2.5 Group Boxes The group box which has the BS_GROUPBOX style is a rectangular area within a dialog box in which you can group together other controls that are semantically related. Table 11 You can initialize a check box with a check mark by sending BM_SETCHECK message: SendMessage(hwndButton. The label may be text.1. Any text associated with the group box is displayed in its upper-left corner. SetWindowText( HWND hwnd.4 Radio Buttons A small round button with a label next to it. 3.BM_SETCHECK. but mutually exclusive options.0).4. Radio In the program given below dialog box is used to place various controls. representing a set of related.0). When a user selects an option button or radio button.BM_SETCHECK.2.2. all other option buttons in the same group is automatically unselected. indicating an indeterminate state.3.BM_SETCHECK. // check state lParam = 0.0). are usually grouped together in a group box.3 Values for fCheck Parameter Value BST_CHECKED BST_INDETERMINATE Meaning Sets the button state to checked. The value of iCheck is TRUE or nonzero if the button is checked and FALSE or 0 if not checked. an icon. The two most common styles of radio buttons are BS_RADIOBUTTON and BS_AUTORADIOBUTTON. SetWindowText cannot http://cnx.0).2. For BS_AUTOCHECKBOX style the button control itself toggles the check mark on and o.2. For all other radio buttons in the same group you can turn o the checks by sending them BM_SETCHECK messages with wparam equal to 0: SendMessage(hwndButton. // not used. // handle to window or control LPCTSTR lpstring // address of string ). This parameter can be one of the values mentioned in Table 3. The details regarding the dialog box creation and usage is given in section 3. However. 3.BM_SETCHECK. It neither processes mouse or keyboard input nor sends WM_COMMAND message to its parent.0. When you receive a WM_COMMAND message from a radio button you should display its check by sending it a BM_SETCHECK with wparam equal to 1: SendMessage(hwndButton.3. BST_UNCHECKED Sets the button state to cleared.1.1/ .6 Changing the Button Text and Input Focus The text in the button can be changed by calling SetWindowText. The controls are grouped by drawing a rectangular border around them. When the current state of the button is needed send the control a BM_GETCHECK message: iCheck = (int) SendMessage(hwndButton. Use this value only if the button has the BS_3STATE or BS_AUTO3STATE style. Table 3.0. Sets the button state to grayed.Connexions module: m14425 60 wParam = (WPARAM)fcheck. must be zero where fCheck is the value of wParam. also known as option buttons. 3.and species the check state.

This parameter must be one of the values mentioned in Table 3.8 return 0. 17. When the window switches the input focus from one window (parent) to another (child).7 System Colors The parts of display can be painted using various system colors. 17. However the child window control responds only to the spacebar which now functions like the mouse. 17.3 The parameters hwnd is a handle to the window or control containing the text.2. it is truncated. 17.9 This method prevents the button from responding to the space bar because the button never gets input focus. // pointer to buer for text int nMaxCount // maximum number of characters to copy ).org/content/m14425/1. If the text exceeds this limit. lpstring is a pointer to the buer that will receive the text and nMaxCount species the maximum number of characters to copy to the buer.Connexions module: m14425 61 17. GetSysColor( int nIndex // display element ). 17.7 Values for nInex Parameter Value Meaning continued on next page http://cnx.1/ .4 The push buttons. it rst sends WM_KILLFOCUS message to the window losing the input focus.2.5 case WM_KILLFOCUS: 17.2.7 SetFocus (hwnd). Display elements are the parts of a window and the display that appear on the system display screen.10 3. When the child window control gets the input focus. GetSysColor and SetSysColor functions are used to set these colors. A better approach is to get input focus to the button and also include the facility to move from button to button using Tab key. including the NULL character. 17. Identiers dened in the windows header les specify the system color.7 Table 3. check boxes and radio buttons receive the input focus when they are clicked with the mouse. The parameter nIndex species the display element whose color is to be retrieved.2 You can also obtain the current text of a window by the command: GetWindowText( HWND hwnd.1 The parameters hwnd is a handle to the window or control whose text is to be changed and lpstring is a pointer to a null-terminated string to be used as the new title or control text. // handle to window or control with text LPTSTR lpstring. 17. the parent window loses it. The GetSysColor retrieves the current color of the specied display element.6 if (hwnd==GetParent ((HWND) wparam)) 17.

Inactive window caption.) COLOR_3DSHADOW. COLOR_3DFACE. COLOR_3DHILIGHT. Menu background. Background color for tooltip controls. Text on push buttons. Grayed (disabled) text. Highlight color for three-dimensional display elements (for edges facing the light source.Connexions module: m14425 62 COLOR_3DDKSHADOW Dark shadow for three-dimensional display ele- ments. COLOR_BTNSHADOW Shadow color for three-dimensional display elements (for edges facing away from the light source).) continued on next page http://cnx. This color is set to 0 if the current display driver does not support a solid gray color. . COLOR_DESKTOP COLOR_BTNTEXT COLOR_CAPTIONTEXT COLOR_GRAYTEXT Desktop. Color of text in an inactive caption. Background color of multiple document interface (MDI) applications. COLOR_BACKGROUND. COLOR_BTNFACE Face color for three-dimensional display elements and for dialog box backgrounds. COLOR_HIGHLIGHT COLOR_HIGHLIGHTTEXT COLOR_INACTIVEBORDER COLOR_INACTIVECAPTION COLOR_INACTIVECAPTIONTEXT COLOR_INFOBK COLOR_INFOTEXT COLOR_MENU COLOR_MENUTEXT Item(s) selected in a control. Text color for tooltip controls. size box. Text in caption. Text of item(s) selected in a control. Inactive window border. Active window title bar. Text in menus. COLOR_ACTIVEBORDER COLOR_ACTIVECAPTION COLOR_APPWORKSPACE Active window border. and scroll bar arrow box. COLOR_BTNHIGHLIGHT COLOR_3DLIGHT Light color for three-dimensional display elements (for edges facing the light source. COLOR_BTNHILIGHT.

2. and use GetDlgItem() to retreive the handle to the control. 3. as needed. and when an event occurs on the control it will send you a notication message back. such as associating some data with it. it will be WM_NOTIFY. Usually this will be things like a pointer to a struct containing more information. (LPARAM)"Hi there!").Connexions module: m14425 63 COLOR_SCROLLBAR COLOR_WINDOW COLOR_WINDOWFRAME COLOR_WINDOWTEXT Scroll bar gray area. generic messages like WM_SETTEXT are supported by almost all controls.11 Messages As you may remember from our earlier discussion of the message loop. LB_ADDSTRING. (LPARAM)nTimes).12 Adding Items to list box The rst thing you'll want to do with a listbox is add items to it. The messages you send are widely varied between each control. This is especially annoying with the listbox and combobox messages (LB_* and CB_*) which although they perform nearly identical tasks. 17. this is a pretty simple task.1/ . http://cnx. WINAPI SetSysColors( int cElements. A control is just a window after all. it's up to you. For the Common Controls which I may get to later. // address of array of elements CONST COLORREF *lpargbValues // address of array of RGB values ). Window frame. When a string is selected. it appears highlighted. IDC_LIST.8 List Box Class The list box is a window that displays a list of character strings. (WPARAM)index. the results of both methods are identical. Text in windows. IDC_LIST. Window background. You can use a vertical or horizontal scroll bar with a list box to scroll lists that are too long for the control window. 0. LB_SETITEMDATA. int index = SendDlgItemMessage(hwnd. // number of elements to change CONST int *lpaElements. The user selects a string from the list by tapping it with the stylus. are NOT the new item will be added in alphabetical order. As you can see. but in general they will only work on the control they are intended for. 17. and we can use this to perform other tasks on the item. The list box automatically hides or shows the scroll bar. If the listbox has the LBS_SORT style. or you can use SendDlgItemMessage() which does both steps for you. Once in a while the same message will be used for more than one kind of control.On the other hand. For the standard controls this notication will be a WM_COMMAND message as we've already seen with buttons and menus. Display elements are the various parts of a window and the display that appear on the system display screen. Table 12 The SetSysColors function sets the colors for one or more display elements. or maybe an ID that you will use to identify the item. windows communicate using messages. and each control has it's own set of messages. SendDlgItemMessage(hwnd. You can send messages using the SendMessage() API. you send them to get a control to do something. This message returns the index of the new item either way. otherwise it will just be added to the end of the list.

If it were a single selection listbox. int data = SendMessage(hList. case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_LIST: // It's our listbox. which tells us that the selection has been modied by the user. 0. and we need a second check to nd out what it's telling us. sometimes you want to be able to do something right away. However. sizeof(int) * count). Do stu with indexes GlobalFree(buf ). a list box sends WM_COMMAND for various reasons.. the other half of the parameter that gave us the control ID in the rst place. 0). (WPARAM)index. (WPARAM)count.13 Notications The whole purpose of listboxes is to allow the user to select things from a list. for example with our Remove button. do stu here. is retreive the data associated with each item. LB_GETITEMDATA. // ..1]. The Notication Code is passed as the HIWORD of wParam. 17. // . 0). or at the request of the user. http://cnx. HBITMAP hData = (HBITMAP)SendMessage(hList.Connexions module: m14425 64 17. } break. LB_GETSELITEMS.. (WPARAM)index. Now sometimes we don't care when exactly they do this. we just check when the user activates the button. we just send another message. SendMessage(hList. In this example. (LPARAM)buf ). perhaps display dierent or updated information based on what items are selected. 0). check the notication code switch(HIWORD(wParam)) { case LBN_SELCHANGE: // Selection changed. we need to get the selection from the listbox and do something useful with it. First we need to get the number of selected items. In order to do this we need to handle the notication messages that the listbox passes to us. HWND hList = GetDlgItem(hwnd. than you could simply send LB_GETCURSEL to retrieve the item index. and send LB_GETSELITEMS to ll in the array.. and do some processing with it. so getting the list of selected items is a little trickier. int *buf = GlobalAlloc(GPTR. so that we can allocate a buer to save the indexes in. Then we allocate a buer based on the number of items.. buf[0] is the rst This is just as simple as setting the data was originally.1/ . LB_GETSELCOUNT.. In this example I've used a multiselection list box.14 Getting Data from the ListBox Now that we know the selection has changed. In this case. If the data was some other type of value (anything that is 32-bits) you could simply cast to the appropriate type. other controls } break. which are usually only in response to a click. and so on up to buf[count . LB_GETITEMDATA. int count = SendMessage(hList. IDC_LIST). we are interested in LBN_SELCHANGE. For example if you stored HBITMAPs instead of ints. break. we don't need to know when the selection changes right away. LBN_SELCHANGE is sent via WM_COMMAND but unlike handling the WM_COMMAND from buttons or menu's. One of the things you would likely want to do with this list of indexes.

LPSTR lpCmdLine.h) to your project by clicking Project->Add to Project- >Files. LRESULT CALLBACK wndproc(HWND hwnd.HINSTANCE hPrevInstance. WNDCLASS wc.8(a) Dialog design for ControlDemo program Change the ID for the controls as shown below: Control TypeID Edit ControlID_CNAME List BoxID_ITEM Option button (Cash)ID_CASH Option button(Cheque)ID_CHEQUE Select Insert-> resource from the menu and then select the option Menu from it. Now select the . Include this le and the resource header le (resource.h le for your project and click OK.h> #include "resource. Now the resource is included in your project workspace. int APIENTRY WinMain(HINSTANCE hInst. The menu contains two options named (Item and Exit). MSG msg. Now an empty project without using MFC classes is # include <windows. HWND hwnd. Design the dialog as shown in gure 3.LPARAM lp).LPARAM lp).2.cpp).cpp).Connexions module: m14425 65 Example Program illustrating the use of Controls Create an application named ControlDemo by selecting the project type Win 32 Application in the appwizard and click OK. If the Item option is clicked Dialog box containing the controls will be displayed. If the Exit option is selected from the menu the output window will be closed. Now close your dialog window and save your design by giving a name to the Script. Enter the code given below in the implementation le (Control.WPARAM wp.1/ .UINT wm.UINT wm. Click File->New and then select the option C++ Source File and give a name to the . Figure 3.h" HINSTANCE hInstance.2. This will be stored in .WPARAM wp. Click Insert->Resource from the menu and then select the Dialog option.cpp implementation le (here the name is Control.rc extension. LRESULT CALLBACK item(HWND hDlg.rc and resource. int nCmdShow) { //TODO :place code here http://cnx.

} break. wc. wc.NULL.WPARAM wp.lpfnWndProc=wndproc.LPARAM lp) {DLGPROC dlgproc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH).0)) DispatchMessage(&msg). "Scanner".hCursor=LoadCursor(hInstance. wc.Connexions module: m14425 66 if(hPrevInstance==NULL) { memset(&wc.UINT wm.sizeof(wc)). break. wc. } return(DefWindowProc(hwnd.NUL while(GetMessage(&msg.lpszMenuName=MAKEINTRESOURCE(IDR_MENU1). DialogBox(hInstance. case WM_DESTROY : PostQuitMessage(0).lp)). wc. } LRESULT CALLBACK wndproc(HWND hwnd. wc.LPARAM lp) hwnd=CreateWindow("Sample".1/ .WS_OVERLAPPEDWINDOW.hInstance=hInstance.UINT wm. } char itm[5][10]={ "Hard Disk".NULL. "Keyboard"}.hIcon=LoadIcon(hInstance.wp.500. return true. if(!RegisterClass(&wc)) return false. case ID_EXIT: DestroyWindow(hwnd). "Printer".nCmdShow). //return 0. } ShowWindow(hwnd. LRESULT CALLBACK item(HWND hDlg. wc.WPARAM wp.hInst. "Monitor".MAKEINTRESOURCE(IDD_DIALOG1).NULL.10. break.lpszClassName="Sample". return 0. break.NULL).10.dlgproc).0.hwnd. wc. UpdateWindow(hwnd).IDC_CROSS). switch(wm) { case WM_COMMAND: switch(wp) { case ID_ITEM: dlgproc=(DLGPROC)"Control Demo".

MessageBox(hDlg. wsprintf(str."Item details". http://cnx.0).str."Cheque")."%s is purchased from %s . cash=SendDlgItemMessage(hDlg.2. return true.0. Payment is by %s".2. cheque=SendDlgItemMessage(hDlg.ID_ITEM.0).8(b).LB_GETCURSEL. EndDialog(hDlg.cheque.LB_GETTEXT.ID_CNAME.sel. if(cash==BST_CHECKED) strcpy(payment.cname. case WM_COMMAND: switch(wp) { case IDOK: sel=SendDlgItemMessage(hDlg. The output window appears as shown in gure 3.ID_ITEM.ID_ITEM.0.false). return 1. } GetDlgItemText(hDlg.8(b).0.i<5. A message is displayed as shown in gure 3. switch(wm) { case WM_INITDIALOG: for(i=0.0).30).str[100]. The dialog resource appears. return 1."Cash").payment). int i.BM_GETCHECK.BM_GETCHECK. } break. case IDCANCEL: EndDialog(hDlg. char cname[30].ID_CASH.(LPARAM)(LPCTSTR)itm[i]).optionsel.payment[10].Select any one of the item from the list box .true). Now Compile.optionsel[10].Connexions module: m14425 67 {static HWND hlist.sel.1/ . SendDlgItemMessage(hDlg.i++) SendDlgItemMessage(hDlg.LB_ADDSTRING. Click the Item option from else {if(cheque==BST_CHECKED) strcpy(payment. } return 0. Enter the Company name and click OK.(LPARAM)(LPCTSTR)optionsel). }.0).0. Build and Execute the

char* buf.. IDC_TEXT. do stu with text . } > 0) http://cnx. IDC_TEXT)).Connexions module: m14425 68 Figure 3. len + 1). the EDIT control. copy. although slightly more work than setting it. modify.. //. BUTTONs and so on).. GetDlgItemText(hwnd.. text. GlobalFree((HANDLE)buf ). Running Instance of ControlDemo Program 17. "This is a string").. len + 1). STATICs. Here is the code used to interface with the edit control in this example: SetDlgItemText(hwnd. buf = (char*)GlobalAlloc(GPTR. buf. Retrieving the text from the control is easy as well.15 3. IDC_TEXT.9 Edits One of the most commonly used controls in the windows environment. That's all it takes to change the text contained in the control (this can be used for pretty much any control that has a text value associated with it.2...1/ . int len = GetWindowTextLength(GetDlgItem(hwnd. is used to allow the user to enter. if(len { int i..2. Windows Notepad is little more than a plain old window with a big edit control inside it.

IDC_NUMBER. is the number of characters copied. int nTimes = GetDlgItemInt(hwnd. BOOL bSuccess. In the example code. it converts it internally into an integer and returns the value to you. otherwise it's not much good. It allocates some memory. You must be careful when dealing with string sizes in windows. There are dierent ags you can pass as the rst parameter to make it behave dierently for dierent purposes. To 17. which we ignored here. Here I've added a check to see if there is any text to begin with. Now that we have the length. but what if you want the user to enter in a number? allocation. since you can't enter any other characters. meaning they don't change or really do anything else very special. You may be or become aware of a second set of APIs named LocalAlloc(). some APIs and messages expect text lengths to include the null and others don't. except that instead of copying the string to a buer.16 3. Note that I added 1 to the length in two places. which allows only the characters 0 through 9 to be entered. However you can make them slightly more useful by assigning them a unique ID (VC++ assigns a default ID of IDC_STATIC. There isn't a GetDlgItemTextLength(). we call GlobalAlloc() to allocate some memory. always read the docs thoroughly. accomplish this. what's up with that? Well. causing an access violation. The return value. but the null terminator would overow the memory block. &bSuccess. In order to do this. This is very handy if you only want positive integers. the Local* and Global* memory functions are identical. as well as converting the string to an integer value. we can allocate some memory. but there is a GetWindowTextLength(). and takes a pointer to a BOOL. This call expects the size of the buer INCLUDING the null terminator. GlobalAlloc() is equivalent to calloc(). they're largely for displaying text to the user. but this is the only way I will be using it in this tutorial. the text would t. initializes it's contents to 0 and returns a pointer to that so all we need to do it get the handle to the control yourself using GetDlgItem(). The third parameter is optional. sometimes you might.. Static controls are usually just that. and fortunately there is an API to make this simpler. or any number of other bad things. etc. If you are ne with a value of 0 in the event of an error. Since the function returns 0 on failure. it won't just return us a pointer to the string already in memory. (comma). then feel free to ignore this parameter. This means that if we were to allocate a string without adding 1. which are legacy APIs from 16-bit windows.Connexions module: m14425 69 First of all. In Win32. Assuming that there is something there to work with. which is -1 and eectively means "No ID") and then setting the text at runtime to present dynamic data to the user. This is a pretty common task.1/ .1 Edits with Numbers Entering text is all well and ne. GetWindowTextLength() returns the number of characters of text the control contains NOT INCLUDING the null terminator. (decimel) or . possibly corrupting other data. I use one to display the data of the item selected in the list box.10 Statics Like buttons.. GetDlgItemInt() works much like GetDlgItemText(). FALSE). including .(minus) ..2.15. we need to free up the memory that we allocated so that it doesn't leak out and drip down onto the CPU and short circuit your computer. if you're used to DOS/UNIX coding. http://cnx. Finally we can call GetDlgItemText() to retrieve the contents of the control into the memory buer that we've just allocated. static. we rst need to know how much memory to allocate.. we simply call GlobalFree() and pass in our pointer. which takes care of all the memory 17. since most likely you don't want to be working with an empty string. static controls are largely trivial. we need to allocate some memory to store the string in. but for the sake or being complete I include them here. there is no way to tell just from that whether or not the function failed or the user just entered 0. NOT including the null terminator. but that's up to you.After we're all done using the text (which we'll get to in a moment). LocalFree(). assuming one and only one is selected. Another useful feature is the ES_NUMBER style for edit controls.

Scroll bars often have four active areas: two scroll arrows for moving line by line.11 Scroll Bar Class In some graphical user interfaces.SB_CTL. you must always specify the x. #include<windows.cpp implementation le (here the name is Scroll. nval[i]=0.30.UINT wm. r.NULL). FALSE). data.0. Now an empty project without using MFC classes is created. However.FALSE).i<3.cpp). switch(wm) { case WM_COMMAND: case WM_CREATE: for(i=0. 3. IDC_SHOWCOUNT.255.hwnd. r. scroll bar control can have a number of styles to control the orientation and position of the scroll bar.1/ .WPARAM wp.i++) { hscroll[i]=CreateWindow("scrollbar". Example Program to change the Color of the Text using Scroll bar Create an application named ScrollBar by selecting the project type Win 32 Application in the appwizard and click OK.SB_CTL. int key=0. Click File->New and then select the option C++ Source File and give a name to the . SetScrollRange(hscroll[i].h> HINSTANCE hinst.i3=255. r.and y-coordinates and the other dimensions of the scroll bar. HBRUSH hbrush. int h=0.left=0.LPARAM lp) { HDC hdc. RECT r. You add the window scroll bar by including the identier WS_VSCROLL or WS_HSCROLL or both in the window style. Some of the styles create a scroll bar control that uses a default width or height.WS_CHILD.hinst.10+40*i.SB_CTL. a sliding scroll box for moving to an arbitrary location in the display area.cpp).SW_SHOW). PAINTSTRUCT ps. You specify the styles that you want when you call the CreateWindowEx function to create a scroll bar control.hwnd1. LRESULT CALLBACK wndproc(HWND int and the gray areas in the scroll bar for moving in of one-window increments. case WM_HSCROLL: switch(LOWORD(wp)) http://cnx.right=800.NULL. Two commonly used scroll bar styles are SBS_VERT and SBS_HORZ. a vertical or horizontal bar at the side or bottom of a display area that can be used with a mouse for moving around in that area."".2. HWND hscroll[3]. 130. int nval[3].Connexions module: m14425 70 SetDlgItemInt(hwnd. ShowScrollBar(hscroll[i]. int i. r.0. Enter the code given below in the implementation le (Scroll. SetScrollPos(hscroll[i]. } break.

j<3.j++) { if(hscroll[j]==hwnd) break.j<3.1/ . for(j=0.j<3. for(j=0. h=nval[j]. break. case SB_LINEDOWN: hwnd1=(HWND)lp. h=nval[j].j<3. } nval[j]-=10. break. for(j=0. break.j++) { if(hscroll[j]==hwnd1) break. nval[j]=h. case SB_PAGEUP: hwnd1=(HWND)lp.j++) { if(hscroll[j]==hwnd1) break. } nval[j]+=10. for(j=0. for(j=0.Connexions module: m14425 71 { case SB_LINEUP: hwnd1=(HWND)lp. } nval[j]-=1.j++) { if(hscroll[j]==hwnd1) break. } nval[j]+=1. case SB_THUMBPOSITION: hwnd1=(HWND)lp. break. h=nval[j]. } http://cnx.j< { if(hscroll[j]==hwnd1) { h=HIWORD(wp). h=nval[j]. case SB_PAGEDOWN: hwnd1=(HWND)lp. break.

nval[1]. InvalidateRect([0]. hdc=GetDC(hwnd). SetScrollPos(hwnd1.SB_CTL. wc.h."the Color of the text is changing". wc.100. wc.SW_SHOW).wp. wc. case WM_PAINT: hdc=BeginPaint(hwnd.TRUE).&ps).nval[2])). wc. int nCmdShow) { WNDCLASSEX wc. LPSTR lpCmdLine.(LONG)CreateSolidBrush(RGB(nval[0]. wc.lp).GCL_HBRBACKGROUND. } int WINAPI WinMain(HINSTANCE hInstance. wc. } else { i1=nval[0]. i3=nval[2].cbWndExtra = 0.lpszClassName = "scroll bar".style = 0.Connexions module: m14425 72 } break. MSG Msg.nval[1]. SetClassLong(hwnd. wc. IDC_ARROW).TRUE).hCursor = LoadCursor(NULL.lpfnWndProc = wndproc.SB_CTL.1/ .cbClsExtra = 0.IDI_APPLICATION).nval[2])). HWND hwnd.nval[2]))). i2=nval[1].wm. break. wc.33). break. wc.RGB(nval[0]. } return 0. HINSTANCE hPrevInstance.hIcon = LoadIcon(NULL.nval[1]. case WM_DESTROY: PostQuitMessage(0). default: return DefWindowProc(hwnd.&ps).lpszMenuName = NULL. } break. EndPaint(hwnd.hdc). http://cnx.&r. TextOut(hdc. if(key==0) { SetTextColor(hdc.200.cbSize = sizeof(WNDCLASSEX). ReleaseDC(hwnd. SetBkColor(hdc. wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1).hInstance = hInstance. } ShowScrollBar(hwnd1.

MB_ICONEXCLAMATION | MB_OK). "scroll bar". MB_ICONEXCLAMATION | MB_OK).2. DispatchMessage(&Msg).org/content/m14425/1. "Window Creation Failed!". NULL. IDI_APPLICATION). 240. nCmdShow). } ShowWindow(hwnd. return 0. if(hwnd == NULL) { MessageBox(NULL. NULL. hInstance.wParam. NULL). As you scroll the scroll bars the color of the text will be changed. WS_OVERLAPPEDWINDOW. UpdateWindow(hwnd). CW_USEDEFAULT.2. CW_USEDEFAULT. NULL. } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE.Connexions module: m14425 73 wc. 120.11 Running Instance of ScrollBar Program http://cnx. "Scroll bar Program".hIconSm = LoadIcon(NULL. 0) { TranslateMessage(&Msg). 0. } return Msg. Build and Execute the program. if(!RegisterClassEx(&wc)) { MessageBox(NULL. return 0. } Compile.11. The output of the program is shown in gure 3. > 0) Figure 3. "Error!". "Window Registration Failed!". while(GetMessage(&Msg. "Error!".1/ .

org/content/m14425/1. open the Resource view in the project workspace and then open the icon folder. right click the icon folder in the resource view and select insert icon from pop up menu. keyboard accelerators. keyboard accelerator tables. Windows displays the program's icon in the upper left corner of the main window title bar.1 Icons An icon is a small bitmap that represents another object in a windows program. but they do not reside in the executable program's data area.3. You can use the Developer Studio image editor to edit or create new icons for your project. In this section the resources such as icons. bitmaps.rc resource script that equates the icon le with an identier (IDI_ICON). AppWizard creates a set of default icons for your project automatically.Connexions module: m14425 74 3. These icons are 48x48 pixels in size and never displayed as a program's icon when the window is minimized. cursors. menus. Creating Icons Using Image Editor When creating a new project. loading and displaying it can be bone through LoadIcon command. When you are using the explorer. There are four dierent types of icons such as: • • • Large Icons: Used for most programs written for windows before the release of Windows 95.exe. Developer studio has put a line in the . menus. Small Icons: First introduced with Windows 95. string table entries. Icons are used to When Icons are widely used by windows itself. The header le resource. Windows provides functions that explicitly or implicitly load a programs resource in to memory so that they can be used. Double click any icon resource contained in the folder to open the editor. and user-dened data. The text resource script is converted in to a binary form which is a le with extension . dialog boxes and bitmaps are described. this opens the image editor with a blank icon ready for editing. these icons are usually a smaller 16x16 pixels version of a program's large icon. Developer studio compiles resources by using the resource compiler rc. • Monochrome Icons: These icons support only two colors and are 32x32 pixels. 256 Color Icons: These icons support more than the standard 16 colors available to other types of icons.3 Windows Resources Windows resources include icons.1 The standard 32x32 Icon le as displayed in Developer Studio The program can be compiled and run now. Loading an Icon in your programs After you have added an icon to a project. Resources are data that are stored in program's . cursors. these icons are 32x32 pixels in size and support 16 colors.exe le. character strings. the icon representing an application associated with each le is displayed next to the le's name. Figure 3. message table entries. A program can obtain a handle to icon by calling LoadIcon: http://cnx. fonts. To open the image editor. version data.res. To insert a new icon resource in to an existing project. a program is minimized its icon is displayed in the windows task bar. represent minimized child windows in MDI application.h contains the denition of IDI_ICON. 3.1/ . dialog boxes.3.

Example program for icon demo Create an application named IconDemo by selecting the project type Win 32 Application in the appwizard and click OK.1(a). It obtains the size of the icon. Hand-shaped icon. Same as IDI_WARNING.16.1.3. Same as IDI_ERROR.16. set the hInstance parameter to NULL and the second parameter to one of the values in Table 3. To use one of the predened icons.hIcon). gure 3. The rst SM means system metrics and the second SM means small. Design the Icon as shown in http://cnx. 17. Exclamation point icon. Asterisk icon. The smaller icon size can also be obtained from the system metrics SM_CXSMSIZE and SM_CYSMSIZE indices.3.Connexions module: m14425 75 hIcon = LoadIcon (hInstance. Same as IDI_INFORMATION. a handle to an icon. Table 13 The icon created can be displayed in its client area.3.1/ . This parameter must be NULL when a standard icon is being loaded and MAKEINTRESOURCE contains the name of the icon resource to be loaded. Now an empty project without using MFC classes is created. cyIcon = GetSystemMetrics (SM_CYICON).1 Second Parameter values for LoadIcon Value IDI_APPLICATION IDI_ASTERISK IDI_ERROR IDI_EXCLAMATION IDI_HAND IDI_INFORMATION IDI_QUESTION IDI_WARNING IDI_WINLOGO Description Default application icon. 17. Question mark icon. Windows logo icon. y .org/content/m14425/1.1 LoadIcon returns a value of type HICON.MAKEINTRESOURCE (IDI_ICON)). x . The program can then display the icon with multiple calls to DrawIcon (hdc . Where x and y coordinates of where the upper left corner of the displayed icon is positioned.2 Table 3. Click Insert->Resource from the menu and then select the Icon option. The parameters hInstance is a handle to an instance of the module whose executable le contains the icon to be loaded. repeated horizontally and vertically using the statement LoadIcon and obtains a handle to the icon using the statements: cxIcon = GetSystemMetrics (SM_CXICON).

static int cxIcon.y<cyClient. return 0. return 0.hIcon). 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 .y+=cyIcon) for(x=0.3. switch(msg) { case WM_CREATE: hInstance=((LPCREATESTRUCT)lParam)->hInstance.Connexions module: m14425 76 Figure 3.cyClient.x<cxClient. Enter the code given below in the implementation le (Icon.rc and resource. cxIcon=GetSystemMetrics(SM_CXICON). HINSTANCE hInstance.cxClient. case WM_DESTROY: http://cnx.1/ .cpp). HDC hdc.y.&ps). case WM_SIZE: cxClient=LOWORD(lParam).cpp). for(y=0. #include <windows.x+=cxIcon) DrawIcon( int x.MAKEINTRESOURCE (IDI_ICON)). cyIcon=GetSystemMetrics(SM_CYICON).&ps). case WM_CLOSE: DestroyWindow(hwnd). cyClient=HIWORD(lParam). LPARAM lParam) {static HICON hIcon. case WM_PAINT: hdc=BeginPaint(hwnd.x.y. return 0. LRESULT CALLBACK WndProc(HWND hwnd. hIcon=LoadIcon(hInstance.h" const char g_szClassName[] = "myWindowClass". PAINTSTRUCT ps.cpp implementation le (here the name is Icon.h header le to your project workspace. EndPaint(hwnd.cyIcon. WPARAM wParam.1(a) Icon design for the program Save the icon design in your project and then include the . UINT msg. break.h> #include "resource.

"Window Creation Failed!". NULL. WS_OVERLAPPEDWINDOW. wc.hInstance = hInstance. wc. NULL.3.lpszClassName = g_szClassName. "Window Registration Failed!". wc. wc. DispatchMessage(&Msg). wc.hIconSm = LoadIcon(NULL. wc. } Compile. IDC_ARROW).cbSize = sizeof(WNDCLASSEX). CW_USEDEFAULT. LPSTR lpCmdLine.hIcon = LoadIcon(hInstance. NULL). "Icon Demo Program". MB_ICONEXCLAMATION | MB_OK). msg. "Error!".wParam.MAKEINTRESOURCE(IDI_ICON)). IDI_APPLICATION). } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE. break.1/ . wc.cbWndExtra = 0.lpfnWndProc = WndProc. wc. } ShowWindow(hwnd. UpdateWindow(hwnd).1(b). lParam). Build and Execute the program. if(hwnd == NULL) {MessageBox(NULL. wParam. if(!RegisterClassEx(&wc)) {MessageBox(NULL. } int WINAPI WinMain(HINSTANCE hInstance. CW_USEDEFAULT. "Error!".org/content/m14425/1. hInstance. } return 0. The output is as shown in gure 3. return = 0. wc. int nCmdShow) { WNDCLASSEX wc. return 0.hbrBackground = (HBRUSH)(COLOR_WINDOW+1). default: return DefWindowProc(hwnd. wc. HINSTANCE hPrevInstance. 0. wc. MSG Msg.lpszMenuName = NULL.hCursor = LoadCursor(NULL. g_szClassName. } return Msg. > 0) http://cnx. 240.cbClsExtra = 0. wc.Connexions module: m14425 77 PostQuitMessage(0). HWND hwnd. 120. while(GetMessage(&Msg. NULL. nCmdShow). MB_ICONEXCLAMATION | MB_OK). 0) {TranslateMessage(&Msg).

but for this example I will show the text of the . loading and displaying it can be bone through LoadCursor command.exe.h le.rc le.3.rc le so you can add it in manually. GRAYED END http://cnx.h" #dene IDR_MYMENU 101 #dene IDI_MYICON 201 #dene ID_FILE_EXIT 9001 #dene ID_STUFF_GO 9002 Not much there.2 Cursors Cursors represent the position of a pointing device.c source les. First the . Usually called "resource. commercial compilers will have a resource editor that you can use to create your menus. such as a mouse. For this example you can start with the window code from simple_window and add this code into it as module: m14425 78 Figure 3.1(b) Running Instance of IconDemo Program 3. #include "resource.rc le and my . ID_FILE_EXIT END POPUP "&Stu" BEGIN MENUITEM "&Go".hCursor = LoadCursor (hInstance. This is rather compiler specic.3.h le as well which is included in both my . 0.3 Menus A menu is probably the most important of the consistent user interface that windows programs oer. Now we write our . and adding a menu to your program is a relatively easy part of windows programming. SetCursor (hCursor). ID_STUFF_GO MENUITEM "G&o somewhere else". The names and values here are up to you for the choosing. This will be created as . If you separate your client area in to smaller logical areas without using child windows.rc le and will be compiled and linked into your . 3. Whenever the mouse is positioned over a window created based on this class the cursor associated with IDC_CURSOR or szCursor will be displayed. You can create a cursor in the same way as an icon by selecting resource from insert menu and selecting cursor. This le contains the identiers for controls and menu items etc.3.szCursor).h" IDR_MYMENU MENU BEGIN POPUP "&File" BEGIN MENUITEM "E&xit". I usually have an . but our menu will be pretty simple.1/ . After you have added a cursor to a project. wndclass. you can use SetCursor to establish the cursor shape.

IMAGE_ICON. WM_SETICON. 16.h" in your source le (. Be aware that icon les and resources can contain multiple images. Change that and see what happens. program. "&File").1/ . hIcon=LoadImage(NULL. we need to use LoadImage(). underneath your #includes.lpszMenuName=MAKEINTRESOURCE(IDR_MYMENU). like this: wc. (LPARAM)hIconSm). } Next we add the Your window should now have a File and Stu menu with the That is assuming your . The easiest way to attach the menu and icon to your window is to specify them when you register the window class. you could choose to store your icon as a separate le and load it at runtime. "Could not load small icon!". respective items underneath.ico". hMenu = CreateMenu(). hSubMenu = CreatePopupMenu(). You can also use icons that aren't stored as resources. ICON_BIG. "Error". #dene ID_FILE_EXIT 9001 #dene ID_STUFF_GO 9002 Put these two id's at the top of your .h or . "&Go"). ID_FILE_EXIT.c le this time. SetMenu(hwnd. else MessageBox(hwnd. (UINT)hSubMenu. 16. hSubMenu = CreatePopupMenu()."Could not load large icon!".32. 16. Start again from simple_window without the . MAKEINTRESOURCE(IDI_MYICON). MB_OK | MB_ICONERROR).Connexions module: m14425 79 END IDI_MYICON ICON "menu_one.32. however it will only load icons at the default resolution of 32x32.(UINT)hSubMenu. hIconSm = LoadImage(NULL. 0). MAKEINTRESOURCE(IDI_MYICON)). An alternative to using a menu resource is to create one on the y (or when your program runs). so in order to load the smaller image. This is a bit more work programming wise. hSubMenu. AppendMenu(hSubMenu.rc le was properly compiled and linked into your http://cnx.MF_STRING| MF_POPUP. MF_STRING.c) so that the menu command identiers and the menu resource id will be dened. AppendMenu(hMenu.ico". if(hIconSm) SendMessage(hwnd. following code into our WM_CREATE handler.hIconSm=(HICON)LoadImage(GetModuleHandle(NULL). else MessageBox(hwnd. AppendMenu(hSubMenu. I've used LoadIcon() to load the large icon because it's simpler.LR_LOADFROMFILE). hIconSm. "Error".rc le to your project or makele depending on what tools you are using. WM_SETICON. MB_OK | MB_ICONERROR). ICON_SMALL. HICON hIcon. or something to that eect. if(hIcon) SendMessage(hwnd. AppendMenu(hMenu. IMAGE_ICON. wc. (LPARAM)hIcon). IMAGE_ICON. MF_STRING. but adds exibility and is sometimes necessary. and in this case the ones I've supplied contain the two sizes that I'm loading. "menu_two. Now we will handle the WM_CREATE message and add a menu to our window. ID_STUFF_GO. hMenu). LR_LOADFROMFILE). "E&xit")." "&Stu"). You also want to #include "resource. wc. 16.MF_STRING|MF_POPUP. case WM_CREATE: { HMENU hMenu. This would also give you the option of allowing the user to select an icon of their choice with the common dialogs discussed later.hIcon=LoadIcon(GetModuleHandle(NULL).rc added.ico" You will want to add the .

hSubMenu = CreatePopupMenu()."&File"). hMenu). then you'll need to copy the icon le into that directory in order for the program to nd it. We can't use LoadIcon() at all because it will only load resources. hSubMenu = CreatePopupMenu(). "Could not load large icon!". Finally.IMAGE_ICON.MF_STRING|MF_POPUP. We specify NULL for the instance handle parameter because we aren't loading a resource from our module. Note that the LoadImage() calls will fail if the icon le isn't in the current working directory of the program. A menu that is assigned to a window is automatically removed when the program terminates. not les. LR_LOADFROMFILE). hMenu = CreateMenu(). we could use GetMenu() and DestroyMenu(). If all else fails. AppendMenu(hMenu. the current working directory will be the one the project le is in. LR_LOADFROMFILE). MB_OK | MB_ICONERROR). if(hIconSm) SendMessage(hwnd. (LPARAM)hIcon). "menu_two.ico". ID_FILE_EXIT. This is pretty simple. we pass in the LR_LOADFROMFILE ag to indicate that we want the function to treat the string we give it as a lename and not a resource name. 32. AppendMenu(hSubMenu. hIcon = LoadImage(NULL. and instead of a resource ID we pass in the name of the icon le we want to load. hSubMenu. This creates a menu almost the same as the one we had in the resource and attaches it to our window.ico". The code for the icons is pretty simple. Now that we have our menu. Else MessageBox(hwnd. (UINT)hSubMenu. MF_STRING. LRESULT CALLBACK WndProc(HWND hwnd. MB_OK | MB_ICONERROR). case WM_COMMAND: switch(LOWORD(wParam)) { case ID_FILE_EXIT: http://cnx. UINT Message. and if it fails we pop up a message box letting us know something went wrong. Also we'll need to check which command we are getting and act accordingly. "C:\\Path\\To\\Icon. MF_STRING. if(hIcon) SendMessage(hwnd.(UINT)hSubMenu. AppendMenu(hMenu.1/ . "Error". specify the full path to the icon. (LPARAM)hIconSm). "&Stu"). hIconSm=LoadImage( we call LoadImage() twice.16. If each call succeeds we assign the icon handle to our window with WM_SETICON. 32. WM_SETICON. we need to make it do something.16.Connexions module: m14425 80 break. else MessageBox(hwnd. all we need to do is handle the WM_COMMAND message. SetMenu(hwnd. "Could not load small icon!". LPARAM lParam) { switch(Message) { case WM_CREATE: { HMENU hMenu. ICON_BIG. "&Go"). However if you run the program from the Debug or Release directories from explorer or the command shell.ico".MF_STRING|MF_POPUP."menu_two. WPARAM wParam. If you are using VC++ and you run the program from the IDE. WM_SETICON. Now our WndProc() should look something like this. ID_STUFF_GO. ICON_SMALL. IMAGE_ICON. to load the icon as both a 16x16 size and a 32x32 size. so we don't need to worry about getting rid of it later. "E&xit"). "Error". AppendMenu(hSubMenu. If we did though. } break.

Your WM_COMMAND handler should now look like this: case WM_COMMAND: switch(LOWORD(wParam)) { case ID_FILE_EXIT: PostMessage(hwnd.h> #include "resource. 0. } return 0. } break. extension and then include this .rc Under the option File->Exit is included. Message. Enter the code given below in the implementation le (Menu. WPARAM wParam. Similarly open the Icon resource and make a design of your own.1/ . Example Program to illustrate menu design Create an application named ModalDialog by selecting the project type Win 32 Application in the appwizard and click OK. LRESULT CALLBACK WndProc(HWND hwnd. and it even has another switch() in it. Change the ID for menu as IDR_MENU1. WM_CLOSE. The Icon which you design will appear on the top of the window. 0. break.h header le in your project. PostMessage(hwnd. wParam.cpp). Change the ID of Icon as IDI_MYICON.rc le and resource. Under the option Stu options Go and GoSomewhereElse are After designing the menu save the script with . lParam). included. default: return DefWindowProc(hwnd. UINT Message. 0). case WM_DESTROY: PostQuitMessage(0). break. This switch()'s on the value of the low word of wParam. 0). WM_CLOSE.cpp implementation le (here the name is Menu. ID_FILE_EXIT handler you can use the following code to do just that.cpp). So in the break. case ID_STUFF_GO: break. Design the Menu resource with the options Stu and File. } As you can see we've got our WM_COMMAND all set up.Connexions module: m14425 81 break. Click File->New and then select the option C++ Source File and give a name to the .h" const char g_szClassName[] = "myWindowClass". } break. case ID_STUFF_GO: break. #include <windows. which in the case of WM_COMMAND contains the control or menu id that sent the message. We obviously want the Exit menu item to close the program. LPARAM lParam) {switch(Message) { case WM_COMMAND: switch(LOWORD(wParam)) http://cnx. Now an empty project without using MFC classes is created. case WM_CLOSE: DestroyWindow(hwnd).

case WM_DESTROY: PostQuitMessage(0). CW_USEDEFAULT. 16. = 0. WS_OVERLAPPEDWINDOW. } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE. 0.Connexions module: m14425 82 { case ID_FILE_EXIT: PostMessage(hwnd. HWND hwnd.1/ . IDC_ARROW). wc. int nCmdShow) {WNDCLASSEX wc. NULL). break. } return 0. } int WINAPI WinMain(HINSTANCE hInstance.hInstance = hInstance. hInstance.hCursor= LoadCursor(NULL. lParam). NULL.lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU). MB_ICONEXCLAMATION | MB_OK). wc.lpszClassName = g_szClassName. HINSTANCE hPrevInstance. wc.cbClsExtra = 0. case ID_STUFF_GO: MessageBox(hwnd. CW_USEDEFAULT. MAKEINTRESOURCE(IDI_MYICON). return 0. 16. g_szClassName. wc. "Woo!". "You clicked Go!".org/content/m14425/1. "Window Registration Failed!". wc. MAKEINTRESOURCE(IDI_MYICON)). } break. default: return DefWindowProc(hwnd.cbSize = sizeof(WNDCLASSEX). MSG Msg. 0). if(!RegisterClassEx(&wc)) {MessageBox(NULL.hIconSm =(HICON)LoadImage(GetModuleHandle(NULL). NULL. case WM_CLOSE: DestroyWindow(hwnd). IMAGE_ICON. wc.lpfnWndProc = WndProc. LPSTR lpCmdLine. Message. if(hwnd == NULL) http://cnx. wParam. wc. WM_CLOSE. 0). MB_OK).hbrBackground = (HBRUSH)(COLOR_WINDOW+1). wc. "A Menu". 120. 240.hIcon=LoadIcon(GetModuleHandle(NULL). break. wc. wc. wc.cbWndExtra = 0. break. "Error!". break.

cutting down on the amount of code you must write. UpdateWindow(hwnd). } ShowWindow(hwnd. The message is displayed as shown in gure 3. one that probably allows you to select a le to be opened.3. Click the menu item Stu.1/ . You can use it to display status information and to get user input. 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. return 0. The modal dialog box is the most common. One thing to remember is that dialogs are just windows. and handling tab order. Dialogs aren't limited to the standard open le ones. The dierence between a dialog and a "normal" window is that the system does some additional default processing for dialogs. MB_ICONEXCLAMATION | MB_OK).3(b) Running Instance of Menu program 3.3. and vice versa! There are two types of dialog box such as modal and modeless dialog box.4 Dialog Box 18 A dialog box is a temporary window that contains controls. Just go File -> Open in any text editor or any other kind of editor. } Compile.Connexions module: m14425 83 {MessageBox(NULL. DispatchMessage(&Msg). they can look like and do whatever you choose.3. "Error!". When your program displays a modal dialog box the user http://cnx. such as creating and initializing controls. Build and Execute the Program. nCmdShow).3(a) Running Instance of Menu program Figure 3.3(b) > 0) Figure 3. 0. you are presented with a dialog box.3.3(a) and 3. } return Msg. 0) {TranslateMessage(&Msg) Nearly all APIs that are applicable to "normal" windows will work just as well on dialogs.3. "Window Creation Failed!". NULL. while(GetMessage(&Msg. The output is as shown in gures 3.3(b).3.

so that by pressing Alt+O the user can activate this control (part of the default processing I mentioned). case WM_COMMAND: http://cnx. Top. 239. UINT Message. expecially if you have no visual editor. The four numbers at the end are the left.18.. If you have a large font selected.h or afxres.rc le and let you incorporate it into your project. You usually don't need to worry about that though.rc le. width and height.IDCANCEL. or in the case of VC++. Two of the controls have an ID of IDC_STATIC (which is -1).IDC_STATIC. The user can switch to another program while the dialog box is still displayed. winres. Here I will show you the plain text of the dialog in the . Now we have the list of controls to create on the dialog: DEFPUSHBUTTON "&OK".7. If you use the resource editor these les will certainly be included automatically if needed. LPARAM lParam) { switch(Message) { case WM_INITDIALOG: return TRUE.174.IDOK.52 CTEXT "An example program showing how to use Dialog Boxes\r\n\r\n by Avanija".174. As with any resource how you do this will depend on your compiler/IDE.rc le we need to write a Dialog Procedure to process message for this box. and the four number are the Left. 0. These should be explained under CreateWindow() in your help les. In order to use the predened constants you may need to add #include "windows. This is important as it makes sure that all of the controls are the proper size to display their text in the current font. as you almost always use a resource editor to create dialogs.16.174. These ARE NOT PIXELS. so they have no need of an identier.7. However it doesn't hurt to give them an ID and your resource editor might do so automatically.14 Here's the line for the OK button. if you use a smaller font. IDOK is pre-dened so we don't need to #dene it ourselves.18. but knowing how to do it from text is sometimes necessary. The CAPTION line should be self explanatory.". So! Having added that to your .50. The "\r\n" in the text of the static control is a CR-LF pair.50. This might not end up exactly the same on each computer as dierent people will have dierent fonts and may have specied dierent font sizes. Don't worry this is nothing new. the dialog will be that much smaller.1/ .144.h" to your . The second line starts with STYLE and follows with the window styles that will be used to create the dialog.h will do.IDC_STATIC. they are in Dialog Units. the dialog will be large. WPARAM wParam. which are based on the size of the font used by the system (and chosen by the user). DISCARDABLE tells the system it may swap the resource memory to disk when it's not being used in order to conserve system resources (essentially pointless). IDD_ABOUTDLG is the id of the resource. You can convert dialog units to pixels at runtime using MapDialogRect(). The rst step is to create the dialog resource.IDOK. Width and Height co-ordinates. IDOK is the control identier. this is used to indicate we never need to access them.33 END On this rst line. it's practicly the same as our main Window Procedure (but not exactly). The & in this case like with menus underlines the next letter "O".18. all in dialog units.50.225. BOOL CALLBACK AboutDlgProc(HWND hwnd. 66 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "My About Box" FONT 8. The FONT line species the size and name of the font you wish to use for this dialog box..Connexions module: m14425 84 must explicitly end the dialog box by clicking a push button marked either OK or Cancel. DIALOG is the resource type.14 GROUPBOX "About this PUSHBUTTON "&Cancel".35. the way windows represents a new line. IDD_ABOUT DIALOG DISCARDABLE 0. top. This information should be purely academic. "MS Sans Serif" BEGIN DEFPUSHBUTTON "&OK".

Connexions module: m14425


switch(LOWORD(wParam)) { case IDOK: EndDialog(hwnd, IDOK); break; case IDCANCEL: EndDialog(hwnd, IDCANCEL); break; } break; default: return FALSE; } return TRUE; } There are a few important dierences between a dialog procedure and window procedure. One is that you DO NOT call DefWindowProc() for message you don't handle. With dialogs this is done automatically for you (and will really screw things up if you do it). Secondly, in general you return FALSE for messages you don't process, and TRUE for messages you do process, UNLESS the message species you return something else. Note that this is what we do above, the default is to do nothing and return FALSE, while messages we do handle break the switch() and return TRUE. Thirdly, You do not call DestroyWindow() to close a dialog, you call EndDialog(). The second parameter is the value that is returned to whatever code called DialogBox(). Finally, instead of handling WM_CREATE, you handle WM_INITDIALOG to do any processing that needs to be done before the dialog appears, and then return TRUE to have the keyboard focus set to the default control. (You can actually handle WM_CREATE as well, but it is sent BEFORE any of the controls have been created, so you can't access them. In WM_INITDIALOG the controls have already been created). case WM_COMMAND: switch(LOWORD(wParam)) { case ID_HELP_ABOUT: { int ret = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc); if(ret == IDOK){ MessageBox(hwnd, "Dialog exited with IDOK.", "Notice", MB_OK | MB_ICONINFORMATION); } else if(ret == IDCANCEL){ MessageBox(hwnd, "Dialog exited with IDCANCEL.", "Notice", MB_OK | MB_ICONINFORMATION); } else if(ret == -1){ MessageBox(hwnd, "Dialog failed!", "Error", MB_OK | MB_ICONINFORMATION); } } break; // Other menu commands... }

Connexions module: m14425


break; This is the code used to create my about box, you can probably guess that this is to be merged into your WM_COMMAND handler, if you aren't clear on this aspect, you might want to review the section on menus. ID_HELP_ABOUT is the identier of my Help -> About menu item. Since we want the menu on our main window to create the dialog, we obviously want to put this code in the WndProc() of our main window, not the dialog proc. Now the return value is by making a call to DialogBox(), this is just so you can observe the eects of pressing the two buttons, hitting Esc, Enter etc... from inside the dialog. It also illustrates how to use the return value from a dialog box to check for success, failure, a users choice, or whatever other information you choose to send back to the caller from the Dialog Procedure. DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc); This is the only important part, and you can choose to put it wherever in your code that you want the dialog to come up. IDD_ABOUT is the id of the dialog resource. hwnd is the handle to the parent window of the dialog. AboutDlgProc() is of course the dialog procedure to use to control the dialog. A particularly astute reader might eventually wonder, if DialogBox() doesn't return until the dialog closes we can't process messages while it's up, so how does it work? Well the nifty thing about DialogBox() is that it has it's own message loop, so while the dialog is displayed, our message loop is out of the picture and the default loop is handled by windows. This loop also takes care of fun things like moving the keyboard focus from control to control when you press Tab. Another eect of using DialogBox is that your main window is disabled until the dialog is dismissed. Sometimes this is what we want, and sometimes it isn't, such as when we want to use a dialog as a oating toolbar. In this case we want to be able to interact with both out dialog and our main window. Example program for Modal dialog box Create an application named ModalDialog by selecting the project type Win 32 Application in the appwizard and click OK. Now an empty project without using MFC classes is created. Design the Menu resource with the options Help and File. Under the option Help->About and under File->Exit are included. After designing the menu open the dialog resource and design it as shown in gure 3.3.4(a). Next step is to save the script with .rc extension and then include this .rc le and resource.h header le in your project. Change the ID for menu as IDR_MYMENU and the ID for dialog as IDD_ABOUT.

Figure 3.3.4(a) Dialog design for ModalDialog Program. Click File->New and then select the option C++ Source File and give a name to the .cpp implementation le (here the name is Dialog.cpp). Enter the code given below in the implementation le (Dialog.cpp). #include


#include "resource.h" const char g_szClassName[] = "myWindowClass"; BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch(Message) {

Connexions module: m14425


case WM_INITDIALOG: return TRUE; case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: EndDialog(hwnd, IDOK); break; case IDCANCEL: EndDialog(hwnd, IDCANCEL); break; } break; default: return FALSE; } return TRUE; } LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch(Message) { case WM_COMMAND: switch(LOWORD(wParam)) { case ID_FILE_EXIT: PostMessage(hwnd, WM_CLOSE, 0, 0); break; case ID_HELP_ABOUT: { int ret = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc); if(ret == IDOK){ MessageBox(hwnd, "Dialog exited with IDOK.", "Notice",MB_OK | MB_ICONINFORMATION); } else if(ret == IDCANCEL){ MessageBox(hwnd, "Dialog exited with IDCANCEL.", "Notice", MB_OK | MB_ICONINFORMATION); } else if(ret == -1){ MessageBox(hwnd, "Dialog failed!", "Error", MB_OK | MB_ICONINFORMATION); } } break; } break; case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY:

} return 0. CW_USEDEFAULT. "The title of my window". MB_ICONEXCLAMATION | MB_OK). > 0) http://cnx. wc. 120. MSG Msg.lpszClassName = WS_OVERLAPPEDWINDOW. g_szClassName. "Window Registration Failed!". int nCmdShow) {WNDCLASSEX wc. wc.cbWndExtra = 0. if(hwnd == NULL) {MessageBox(NULL. NULL. } ShowWindow(hwnd. Build and Execute the program. NULL. wc. nCmdShow). hInstance.hIcon = LoadIcon(NULL. } return Msg. MB_ICONEXCLAMATION | MB_OK). "Window Creation Failed!". HWND hwnd. wc. break. CW_USEDEFAULT. wc.hIconSm = LoadIcon(NULL. wc. wc.cbSize = sizeof(WNDCLASSEX). } Compile.lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU). wc.cbClsExtra = 0. } int WINAPI WinMain(HINSTANCE hInstance. DispatchMessage(&Msg).wParam.4(b) through 3. NULL.hInstance = hInstance. NULL). UpdateWindow(hwnd). wc. IDI_APPLICATION). wc.3. default: return DefWindowProc(hwnd. IDC_ARROW). return 0. lParam). wc.hCursor = LoadCursor(NULL. 0.4(d).lpfnWndProc = WndProc. } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE. 0) {TranslateMessage(&Msg).style = 0. 240.3. The output is shown through gures 3. if(!RegisterClassEx(&wc)) {MessageBox(NULL. HINSTANCE hPrevInstance. "Error!". IDI_APPLICATION). "Error!". while(GetMessage(&Msg.1/ . Message.hbrBackground = (HBRUSH)(COLOR_WINDOW+1). LPSTR lpCmdLine.Connexions module: m14425 88 PostQuitMessage(0). return 0. wc. wParam.

0. DialogBox()'s sister CreateDialog() acts more like a window created with CreateWindowEx() in that it returns immediately and depends on your message loop to pump the messages as it does for your main window. This is termed Modeless.3.4(c) Running Instance of ModalDialog Program Figure 3.5 Modeless Dialogs Figure 2 Now we take a look at CreateDialog().3. 98. The dialog resource is created as follows: IDD_TOOLBAR DIALOGEX 0.Connexions module: m14425 89 Figure 3. whereas DialogBox() creates Modal dialogs. 52 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION EXSTYLE WS_EX_TOOLWINDOW http://cnx. you might also want to set the "Tool window" extended style to give it's title bar the typical smaller caption of toolbars.3.4(b) Running Instance of ModalDialog Program Figure 3.3. You can create the dialog resource just like you did for the last dialog example.4(d) Running Instance of ModalDialog Program 3. The dierence is that while DialogBox() implements it's own message loop and does not return until the dialog is closed.1/ .

7. WPARAM wParam. } http://cnx. BOOL CALLBACK ToolDlgProc(HWND hwnd.7. UINT Message. MB_OK | MB_ICONEXCLAMATION). case WM_CREATE: g_hToolbar = CreateDialog(GetModuleHandle(NULL). "This is a message". We show the window with ShowWindow(). "Bye!". } return TRUE. Next we want to create the dialog when our program runs with the help of the command WM_CREATE. with DialogBox() this isn't necessary since the system calls ShowWindow() for us. "MS Sans Serif" BEGIN PUSHBUTTON "&Press This Button". } else { MessageBox(hwnd.14 PUSHBUTTON "&Or This One".org/content/m14425/1. MAKEINTRESOURCE(IDD_TOOLBAR). } break.IDC_OTHER. } break.Connexions module: m14425 90 CAPTION "My Dialog Toolbar" FONT 8. break. "CreateDialog returned NULL". MB_OK | MB_ICONINFORMATION). "Warning!". hwnd. DialogBox() didn't return a handle to us since when DialogBox() returns the window has been destroyed.IDC_PRESS. if(g_hToolbar != NULL) { ShowWindow(g_hToolbar.1/ . HWND g_hToolbar = NULL. break.84.7.31. SW_SHOW). ToolDlgProc).84.14 END You may notice that the resource editor has replaced DIALOG with DIALOGEX indicating we want to set an EXSTYLE on our dialog. "This is also a message". LPARAM lParam) { switch(Message) { case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_PRESS: MessageBox(hwnd. case IDC_OTHER: MessageBox(hwnd. We also want to declare a global variable to hold the window handle returned from CreateDialog() so that we can use it later. Now we need a dialog procedure for our toolbar. "Hi!". default: return FALSE. MB_OK | MB_ICONEXCLAMATION).

and most (if not all) dialog APIs will work on any window. If you've run the program at this point and tried tabbing between the two buttons. neither does hitting Alt-P or Alt-O to activate the buttons. do the regular processing. don't call DefWindowProc(). return FALSE for messages you don't handle and TRUE for those you do. break. we want to be able to display and hide our toolbar whenever we choose so I've added two commands to my menu to do this. Last but not least. and handled them so: case WM_COMMAND: switch(LOWORD(wParam)) { case ID_DIALOG_SHOW: ShowWindow(g_hToolbar.. 0)) { if(!IsDialogMessage(g_hToolbar. or similar) and loop through it in your message loop passing each handle to IsDialogMessage() until the right one is found. an STL std::list. and main window at the same time. It's also worth noting that IsDialogMessage() can also be used with windows that aren't dialogs in order to to give them dialog-like behaviour.1/ . You should be able to create your own menu using the resource editor or manually.. In the main window's WndProc().. break. while(GetMessage(&Msg. SW_SHOW). by calling IsDialogMessage() in our message loop which will do the default processing for us. If the message is for another window we process as usual. we can use DestroyWindow() just like for regular windows. other command handlers } break. case WM_DESTROY: DestroyWindow(g_hToolbar).Now when you run the program. And that is pretty much all there is to modeless dialogs! One issue that may arise is if you have more than one toolbar. } } Here we rst pass the message to IsDialogMessage(). DispatchMessage(&Msg). Is this case the message has already been handled so we don't want to call TranslateMessage() or DispatchMessage(). CreateDialog() does not. if the message is destined for our toolbar (indicated by the window handle we pass in) the system will perform the default processing and return TRUE. SW_HIDE). PostQuitMessage(0). what do you do? Well one possible solution is to have a list (either an array. you should be able to access both the dialog window. 0. break. We can do it ourselves though. &Msg)) { TranslateMessage(&Msg). //. Example Program for Modeless dialog http://cnx. and if none. a dialog is a window.Connexions module: m14425 91 Most of the same message handling rules apply to dialogs created with CreateDialog() as with DialogBox().. One change is that we don't call EndDialog() for modeless dialogs. case ID_DIALOG_HIDE: ShowWindow(g_hToolbar. Why not? Whereas DialogBox() implements it's own message loop and handles these events by default. In this case I destroy the dialog when the main window is destroyed. you have probably noticed it doesn't work.. NULL.

WPARAM wParam. These two options is to make your dialog visible and invisible in the output window. LPARAM lParam) { switch(Message) { case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_PRESS: MessageBox(hwnd. } LRESULT CALLBACK WndProc(HWND hwnd. Figure 3.cpp). UINT Message. WPARAM wParam. BOOL CALLBACK ToolDlgProc(HWND hwnd. "Hi!". UINT Message. Design the Menu resource with the options Dialog and File.5(a). LPARAM lParam) http://cnx. break.cpp implementation le (here the name is ModelessDialog. "Bye!".3. MB_OK | MB_ICONEXCLAMATION). Under the option Dialog include the options Show and Hide.cpp).1/ .rc extension and then include this . } break. MB_OK | MB_ICONEXCLAMATION).5(a) Dialog design for ModelessDialog program Click File->New and then select the option C++ Source File and give a name to the . Now an empty project without using MFC classes is created. case IDC_OTHER: MessageBox(hwnd. #include <windows. "This is a message". break.rc le and resource. Under the option File include Exit to close the output window. Enter the code given below in the implementation le (ModelessDialog. } return TRUE.h header le in your project.h" const char g_szClassName[] = "myWindowClass".org/content/m14425/1.Connexions module: m14425 92 Create an application named ModelessDialog by selecting the project type Win 32 Application in the appwizard and click OK. After designing the menu open the dialog resource and design it as shown in gure 3.h> #include "resource. Change the ID for menu as IDR_MYMENU and the ID for dialog as IDD_DIALOG. default: return FALSE.3. Next step is to save the script with . HWND g_hToolbar = NULL. "This is also a message".

"CreateDialog returned NULL". PostQuitMessage(0).1/ .Connexions module: m14425 93 { switch(Message) { case WM_CREATE: g_hToolbar=CreateDialog(GetModuleHandle(NULL). hwnd. HINSTANCE hPrevInstance. MB_OK | MB_ICONINFORMATION). SW_SHOW). WM_CLOSE. break. wParam.cbSize = sizeof(WNDCLASSEX). if(g_hToolbar != NULL) { ShowWindow(g_hToolbar. break. Message. "Warning!". int nCmdShow) { WNDCLASSEX wc. case WM_DESTROY: DestroyWindow(g_hToolbar). MAKEINTRESOURCE(IDD_DIALOG).org/content/m14425/1.lpfnWndProc = WndProc. case WM_CLOSE: DestroyWindow(hwnd). 0). break. SW_HIDE). default: return DefWindowProc(hwnd. } break. HWND hwnd. case WM_COMMAND: switch(LOWORD(wParam)) { case ID_FILE_EXIT: PostMessage(hwnd. } else { MessageBox(hwnd. LPSTR lpCmdLine. http://cnx. } return 0. case ID_DIALOG_SHOW: ShowWindow(g_hToolbar. wc. wc. MSG Msg. 0. ToolDlgProc). break. lParam). SW_SHOW). } int WINAPI WinMain(HINSTANCE hInstance. } break. case ID_DIALOG_HIDE: ShowWindow(g_hToolbar. = 0. wc.

5(b) through 3. wc.lpszClassName = g_szClassName.hIcon = LoadIcon(NULL. } ShowWindow(hwnd. WS_OVERLAPPEDWINDOW. return 0.cbWndExtra = 0. } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE. wc. 0. if(hwnd == NULL) {MessageBox(NULL. } } return Msg. > 0) http://cnx. while(GetMessage(&Msg. DispatchMessage(&Msg). NULL.5(d). "Error!". MB_ICONEXCLAMATION | MB_OK). MB_ICONEXCLAMATION | MB_OK).org/content/m14425/1. IDI_APPLICATION). hInstance. NULL.3. nCmdShow). &Msg)) {TranslateMessage(&Msg). IDI_APPLICATION). NULL). "Error!".hIconSm = LoadIcon(NULL. "The title of my window". "Window Creation Failed!". 120.cbClsExtra = 0. UpdateWindow(hwnd). 240. The output is as shown in gures 3.hbrBackground = (HBRUSH)(COLOR_WINDOW+1). g_szClassName.Connexions module: m14425 94 wc. wc. "Window Registration Failed!". } Compile.hInstance = hInstance. wc.3.wParam. 0) { if(!IsDialogMessage(g_hToolbar.1/ .lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU). return 0. Build and Execute the program. NULL. CW_USEDEFAULT. wc. wc. CW_USEDEFAULT.hCursor = LoadCursor(NULL. if(!RegisterClassEx(&wc)) {MessageBox(NULL. wc. wc. IDC_ARROW).

3.5(c) Running Instance of ModelessDialog Program http://cnx.5(b) Running Instance of ModelessDialog Program Figure 3.3.1/ .Connexions module: m14425 95 Figure

pen.5(d) Running Instance of ModelessDialog Program 18.6 Bitmaps Bitmaps can be loaded much like icons in earlier examples. as you can write code that draws to an HDC and you can use it on a Window DC or a Memory DC without any checks or changes. One of the quirks of GDI is that you can't draw to bitmap objects (HBITMAP type) directly. As I mentioned. HDCs aren't the only GDI objects you need to be careful about releasing. none of the rest would be able to draw anything! Fortunately this isn't the case any longer. If your program runs ne for a few minutes and then starts drawing strangely or not at all. GDI objects are limited in number. which we'll talk about in a bit). it's very important to release it (just how you do that depends on how you got it.) at a time.3. but it's easy to forget to free GDI objects and they can quickly run your program out of GDI resources under Windows 9x. Theoretically you shouldn't be able to drain the system of GDI resources in NT systems (NT/2K/XP) but it still happens in extreme cases.bmp le just as it can for icons. this is actually a very convenient way of doing things. and when you http://cnx. and LoadImage() can be used to load bitmaps from a *. it's a good sign that you're leaking GDI resources. the resulting graphic operations are applied to the bitmap. and then select the HBITMAP into it with SelectObject().1/ . font.. Also.2 GDI Leaks Once you're nished with an HDC. an HDC can only contain one of each type of object (bitmap. Remember that drawing operations are abstracted by Device Contexts. there is LoadBitmap() for the most basic functionality of simply loading a bitmap resource. You do have the option of manipulating the bitmap data in memory yourself. You can do this with Device Independent Bitmaps (DIB). and you can even combine GDI and manual operations on the DIB. so in order to use these drawing functions on a bitmap. you need to create a Memory DC. but generally it's ok to keep things like bitmaps and fonts around for the entire lifetime of your program. 18.3.Connexions module: m14425 96 Figure since it's much more ecient than reloading them each time you need them. The eect is that the "device" that the HDC refers to is the bitmap in memory. In versions of windows prior to Windows 95.. so that if one program used up too many. and when you operate on the HDC. and you could get away with using up quite a lot of resources in Windows 2000 or XP before anything too bad happened..1 3. they were not only incredibly limited but also shared system wide.

sizeof(bm). When you draw something on the screen it is NOT permanent. The rst step is of course loading the bitmap. GetObject() works for various GDI object types which it can distinguish based on the value of the second parameter. Notice that the rst one is a BITMAP. "GetObjectInfo" would have been a more appropriate label.1/ .3. 18. but it's required for the call to BeginPaint(). it's also created with some default objects selected into it. bm. PAINTSTRUCT ps. The PAINTSTRUCT is a structure that contains information about the window being painted and what exactly is going on with the paint message.3 Displaying Bitmaps The simplest drawing operations on a window occur by handling WM_PAINT. 0.1 Getting the Window DC To start o we declare a couple of variables we need.. HDC hdc = BeginPaint(hwnd. SelectObject(hdcMem. When your window is rst displayed. When an HDC is created. restored from being you can simply ignore the information it contains. If you ignore it completely. case WM_CREATE: g_hbmBall = LoadBitmap(GetModuleHandle(NULL). EndPaint(hwnd. hdcMem. HDC hdcMem = CreateCompatibleDC(hdc). &ps). BeginPaint() as it's name suggests is designed specically for handling the WM_PAINT message. BitBlt(hdc. This will not only remove any of your own objects from the HDC (which is a good thing) but it will also cause the default objects to be properly disposed of when you release or destroy the HDC (a VERY good thing). 0. When not handling a WM_PAINT message you would http://cnx. "Error". and there are no signicant dierences from loading other resource types. MAKEINTRESOURCE(IDB_BALL)).Connexions module: m14425 97 select a new one in it will return the last one. &ps). g_hbmBall). HBITMAP hbmOld = SelectObject(hdcMem. BITMAP is a struct that holds information about an HBITMAP which is the actual GDI object. break.. Then we can get down to drawing. it's only there until something else draws over it. or uncovered from having another window on top of it. 0. "Could not load IDB_BALL!". For most simple tasks.. it will be lost and they will pile up in memory causing GDI leaks. GetObject(g_hbmBall. hbmOld). bm. It's very important that you deal with this object properly. this is quite simple with a bitmap resource. We need a way to get the height and width of the HBITMAP so we use GetObject() which contrary to it's name doesn't really get an object. HBITMAP g_hbmBall = NULL. but rather information about an existing one.bmWidth. case WM_PAINT: { BITMAP bm. DeleteDC(hdcMem). 18.. the size of the structure. not an HBITMAP. and at that point you need to draw it again when the time comes. 0. it's a good idea to store these when they are returned to you. MB_OK | MB_ICONEXCLAMATION). } break. &bm). and then when you are completed drawing with the HDC select them back into it. SRCCOPY). Windows sends the WM_PAINT message to the window to let it know that it needs to redraw it's contents. if(g_hbmBall == NULL) MessageBox(hwnd.

Now we call SelectObject() to select the bitmap into the DC being careful to store the default bitmap so that we can replace it later on and not leak GDI objects. which means replacing our bitmap with the default one that we saved. http://cnx. at the termination of our program. Click Insert->Resource from the menu and then select the Bitmap option. but in short they are: The destination. it's BeginPaint() returns us an HDC that represents the HWND that we pass to it. case WM_DESTROY: DeleteObject(g_hbmBall). important to use BeginPaint() and EndPaint(). Finally we release the Window DC we got from BeginPaint() using EndPaint(). Design the Bitmap as shown in gure 3.ReleaseDC() BeginPaint() . in order to draw on or with bitmaps.3.6(a).. we need to create a DC in memory. The rst thing to do is restore the Memory DC to the state it was when we got it.Connexions module: m14425 98 use GetDC() which we will see in the timer animation examples in a while. and nally the Raster Operation (ROP code). we want a simple exact copy of the source made. we want to free any resources that we allocated. we can call BitBlt() to copy the image from our Memory DC to the Window DC.4 Cleanup At this point the bitmap should be on the screen. Here's a list of the common methods of gaining an HDC.. PostQuitMessage(0). And no doubt. there are still bugs in windows especially older versions that won't clean up all of your GDI objects if you don't do a thorough job. the one that WM_PAINT is being handled for.3 Drawing Once we've gotten the dimensions of the bitmap lled into the BITMAP struct.DeleteDC() And nally. Now an empty project without using MFC classes is created. but it's always a good idea to keep track of your own objects because if get lazy and don't delete them they have a habit of getting loose. Any drawing operation we perform on this HDC will immediately display on the screen. and we need to clean up after ourselves. since modern Windows platforms are pretty good at freeing everything when your program exists. the easiest way to do that here is to CreateCompatibleDC() with the one we already have.3. 18. the source and source position. Destroying an HDC is a little confusing sometimes because there are at least 3 ways to do it depending on how you got it in the rst place. Example Bitmap Program Create an application named BitmapDemo by selecting the project type Win 32 Application in the appwizard and click OK. Technically speaking this isn't absolutely required.3. In this case. the position and size. BitBlt() is probably the all time happiest function in all of the Win32 API and is the staple diet of anyone learning to write games or other graphics applications in windows. no fancy stu. 18. which species how to do the copy. As always. This gives us a Memory DC that is compatible with the color depth and display properties of the HDC for the window. but in WM_PAINT..EndPaint() CreateCompatibleDC() . • • • GetDC() . you can look up each parameter in MSDN. thus displaying on the screen.1/ . Next we can delete it altogether with DeleteDC().2 Setting up a Memory DC for the Bitmap As mention above. 18.3. and how to release it when you're done.

6(a) Bitmap design for the program Save the Bitmap design in your project and then include the . case WM_PAINT: { // Just a note.3.1/ . hdcMem.cpp).bmHeight. switch(msg) { case WM_CREATE: hInstance=((LPCREATESTRUCT) lParam)->hInstance. bm. 0. break. bm. SRCCOPY). PAINTSTRUCT ps. sizeof(bm). 0.cpp implementation le (here the name is Bitmap.rc and resource. GetObject(g_hbmBall. 0. Enter the code given below in the implementation le (Bitmap. http://cnx. g_hbmBall). DeleteDC(hdcMem).cpp). g_hbmBall = LoadBitmap(hInstance. never use a MessageBox from inside WM_PAINT // The box will cause more WM_PAINT messages and you'll probably end up // stuck in a loop BITMAP bm. &ps). LPARAM lParam) { static HBITMAP g_hbmBall. &bm). UINT msg.Connexions module: m14425 99 Figure 3. HINSTANCE hInstance.h header le to your project workspace.h" const char g_szClassName[] = "myWindowClass". LRESULT CALLBACK WndProc(HWND hwnd. SelectObject(hdcMem. MAKEINTRESOURCE(IDB_BALL)). case WM_CLOSE: DestroyWindow(hwnd). WPARAM wParam. #include <windows.bmWidth. break. BitBlt(hdc.h> #include "resource. HDC hdc = BeginPaint(hwnd. HDC hdcMem = CreateCompatibleDC(hdc). Change the ID for Bitmap as IDB_BALL Click File->New and then select the option C++ Source File and give a name to the .

wc. wc. CW_USEDEFAULT. } break. return wc.hIcon = LoadIcon(NULL. NULL. "Window Registration Failed!". NULL. g_szClassName. HINSTANCE hPrevInstance. NULL).cbWndExtra = 0.hIconSm = LoadIcon(NULL. wc. "A Bitmap Program". wc. UpdateWindow(hwnd).Connexions module: m14425 100 EndPaint(hwnd.hbrBackground = (HBRUSH)(COLOR_WINDOW+1). LPSTR lpCmdLine.cbClsExtra = 0. wc. } hwnd = CreateWindowEx( WS_EX_CLIENTEDGE.hInstance = hInstance. &ps). "Error!". break. MB_ICONEXCLAMATION | MB_OK). if(hwnd == NULL) { MessageBox(NULL. } return 0. wc. nCmdShow). } int WINAPI WinMain(HINSTANCE hInstance. case WM_DESTROY: DeleteObject(g_hbmBall).style = 0. 240. MB_ICONEXCLAMATION | MB_OK). hInstance.lpfnWndProc = WndProc. wc. PostQuitMessage(0). } ShowWindow(hwnd. 120. WS_OVERLAPPEDWINDOW. default: return DefWindowProc(hwnd. int nCmdShow) { WNDCLASSEX wc. "Window Creation Failed!". msg. wc. MSG Msg. http://cnx. IDI_APPLICATION).1/ . wc.cbSize = sizeof(WNDCLASSEX). CW_USEDEFAULT. "Error!". wParam. IDC_ARROW). wc. wc.lpszClassName = g_szClassName. IDI_APPLICATION).hCursor = LoadCursor(NULL.lpszMenuName = NULL. if(!RegisterClassEx(&wc)) { MessageBox(NULL. return 0. lParam). HWND hwnd.

Explain the List Box and Scroll Bar Class. What are the advantages of using Dialog Box? 7. Figure 3. Explain SetMenu and LoadMenu functions. Write a Windows program to display a Bitmap in the centre of the screen. DispatchMessage(&Msg).6(b). 3. 0) { TranslateMessage(&Msg). Build and Execute the program. Write a Windows program to add and removo items in a List box. 5. The output is as shown in gure 3. NULL.1/ . 4.3. Explain the functions SetDlgItemText and GetDlgItemText. Explain the BitBlt function. } > 0) Compile. 9. } return Msg. What are the various button styles that can be used in Windows Programming? 2. 10. 8.3.6(b) Running Instance of Bitmap Program Exercises 3 0.wParam.Connexions module: m14425 101 while(GetMessage(&Msg. 6. Explain the LoadIcon and LoadBitmap functions. http://cnx. Dierentiate Modal Dialog and Modeless Dialog.

Sign up to vote on this title
UsefulNot useful