Copyrights © 2012 Jatin Kotadiya. All Rights Reserved . Powered by Blogger.

Tuesday, October 23, 2012

VC++

                             object-oriented programming (OOP)


Object-oriented programming can trace its roots to the 1960s. As hardware and software became increasingly complex, quality was often compromised. Researchers studied ways in which software quality could be maintained. Object-oriented programming was deployed in part as an attempt to address this problem by strongly emphasizing discrete units of programming logic and re-usability in software. Computer programming methodology focuses on data rather than processes, with programs composed of self-sufficient modules (objects) containing all the information needed to manipulate a data structure.
The Simula programming language was the first to introduce the concepts underlying object-oriented programming (objects, classes, subclasses, virtual methods, co routines, garbage collection, and discrete event simulation) as a superset of Algol. Simula was used for physical modeling, such as models to study and improve the movement of ships and their content through cargo ports. Smalltalk was the first programming language to be called "object-oriented".
The term “object-oriented” was coined by Alan Kay in 1967, who explains it in 2003 to mean “only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things”.
Object-oriented programming may be seen as a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a group of tasks to compute ("subroutines"). In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects.
Each object can be viewed as an independent little machine with a distinct role or responsibility. The actions or "operators" on the objects are closely associated with the object. For example, in object oriented programming, the data structures tend to carry their own operators around with them (or at least "inherit" them from a similar object or "class"). The traditional approach tends to view and consider data and behavior separately.

Fundamental concepts

A survey of computing literature identified a number of ‘quarks’, or fundamental concepts, found in the strong majority of definitions of OOP. They are the following:
Object 
Object is a representation of real world entity. A pattern (exemplar) of a class. The class of Dog defines all possible dogs by listing the characteristics and behaviors they can have; the object Lassie is one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur.
Class 
Defines the abstract characteristics of a thing (object), including the thing's characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context. Also, the code for a class should be relatively self-contained (generally using encapsulation). Collectively, the properties and methods defined by a class are called members. 
Instance 
One can have an instance of a class or a particular object. The instance is the actual object created at runtime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of the attributes of a particular object is called its state. The object consists of state and the behaviour that's defined in the object's class.
Method 
An object's abilities. In language, methods are verbs. Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may have other methods as well, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usually affects only one particular object; all Dogs can bark, but you need only one particular dog to do the barking.
Message passing 
“The process by which an object sends data to another object or asks the other object to invoke a method.” Also known to some programming languages as interfacing. E.g. the object called Breeder may tell the Lassie object to sit by passing a 'sit' message which invokes Lassie's 'sit' method. The syntax varies between languages, for example: [Lassie sit] in Objective-C. In Java code-level message passing corresponds to "method calling". Some dynamic languages use double-dispatch or multi-dispatch to find and pass messages.
Inheritance 
‘Subclasses’ are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.
For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In this case, Lassie would be an instance of the Collie subclass. Suppose the Dog class defines a method called bark() and a property called furColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever) will inherit these members, meaning that the programmer only needs to write the code for them once.
Each subclass can alter its inherited traits. For example, the Collie class might specify that the default furColor for a collie is brown-and-white. The Chihuahua subclass might specify that the bark() method produces a high pitch by default. Subclasses can also add new members. The Chihuahua subclass could add a method called tremble(). So an individual chihuahua instance would use a high-pitched bark() from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chihuahua object would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an ‘is-a’ relationship: Lassie is a Collie. A Collie is a Dog. Thus, Lassie inherits the methods of both Collies and Dogs.
Multiple inheritance is inheritance from more than one ancestor class, neither of these ancestors being an ancestor of the other. For example, independent classes could define Dogs and Cats, and a Chimera object could be created from these two which inherits all the (multiple) behavior of cats and dogs. This is not always supported, as it can be hard both to implement and to use well.
Abstraction 
Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.

For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to access Collie-specific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy's pets.

Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.
Encapsulation 
Encapsulation conceals the functional details of a class from objects that send messages to it.
For example, the Dog class has a bark() method. The code for the bark() method defines exactly how a bark happens (e.g., by inhale() and then exhale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface — those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending on those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clients. For example, an interface can ensure that puppies can only be added to an object of the class Dog by code in that class. Members are often specified as public, protected or private, determining whether they are available to all classes, sub-classes or only the defining class. Some languages go further: Java uses the default access modifier to restrict access also to classes in the same package, C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow one to specify which classes may access any member.
Polymorphism 
Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as ‘+’, to perform several different functions depending on the implementation. The ‘+’ operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the concatenation operator, ‘+’, to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism. Many OOP languages also support Parametric Polymorphism, where code is written without mention of any specific type and thus can be used transparently with any number of new types. Pointers are an example of a simple polymorphic routine that can be used with many different types of objects.
Decoupling 
Decoupling allows for the separation of object interactions from classes and inheritance into distinct layers of abstraction. A common use of decoupling is to polymorphically decouple the encapsulation, which is the practice of using reusable code to prevent discrete code modules from interacting with each other.
Not all of the above concepts are to be found in all object-oriented programming languages, and so object-oriented programming that uses classes is called sometimes class-based programming. In particular, prototype-based programming does not typically use classes. As a result, a significantly different yet analogous terminology is used to define the concepts of object and instance, although there are no objects in these languages.

Introduction of VC++
Introduction to C
C is a computer language that can be used to create applications that control the computer the computer and allow a person with interact wit the machine. To enhance it, another language, named C++, was developed from it, adding the concept of object-oriented programmi.
To make it possible to write programs that run on Microsoft Windows operating systems, Microsoft developed a library named Win32. This library is mainly a series objects and their behaviors that define how to create programs that allow a person to interact with a personal computer (PC).
A Compiler
 C++ is a computer language that uses specific syntaxes and rules to allow a person, called a user, to give instructions to the machine. To give these instructions, you write a mix of easy to identify and relatively easy to use words in a human language such as English. You create these instructions in a computer file and save them with the .cpp extension. There can also be other files with other types of extensions such as .h. When the instructions are ready, you submit them to a program called a compiler that will translate your instructions from English to a machine language.
The MFC Library
 As the Microsoft Windows 3.X and then 5.5 operating system was becoming popular, many programmers were interested in creating graphical programs. They had to use Win32, which made it possible only to use C to create programs. With this approach, everything was done manually, including the design and code writing, which was an increasing demanding task, wasting a good deal of time.
Win32 was written in C and had no native support for C++. Therefore, Microsoft created a library, named Microsoft Foundation Classes Library, and abbreviated MFC. This library was originally an “adaptation” or customization of Win32, adding object-orientation (classes and inheritance) to it.
Microsoft Visual C++
The MFC is a library and can be used to manually develop programs. To make the use of MFC friendlier, Microsoft developed Microsoft Visual C++. This is a graphical programming environment that allows designing Windows objects and writing code to implement their behavior. As its name indicates, this environment takes C++ as its base language. Fortunately, using MFC, it goes over some of the limitations of C++ and takes advantage of MFC’s classes.
·        Visual C++ is a powerful and complex tool for building 32-bit applications for Window95 and Windows NT.
·        These applications are much larger and more complex than their predecessors for 16-bit Windows or older programs that didn't use a graphical user interface.
·        Yet, as program size and complexity has increased, programmer effort has decreased, at least for programmers who are using the right tools.
·        Visual C++ is one of the right tools. With its code-generating wizards, it can produce the shell of a working Windows application in seconds.
·        The class library included with Visual C++, the Microsoft Foundation Classes (MFC), has become the industry standard for Windows software development in a variety of C++ compilers.
·        The visual editing tools make layout of menus and dialogs a snap. The time you invest in learning to use this product will pay for itself on your first Windows programming project.
VC ++ Features
VC++ Developer Studio
It’s an integrated application that provides a complete set of programming tools. The Developer Studio includes a project manager for keeping track of your program source files and build options, a text editor for entering program source code, and a set ofresource editors for designing program resources, such as menus, dialog boxes, and icons.

VC++ Runtime Libraries
The Visual C++ runtime libraries provide standard functions such as strcpy and sprintf, which you can call from either C or C++ programs

VC++ MFC and Template Libraries
The Microsoft Foundation Classes (the MFC) is an extensive C++ class library designed for creating Windows GUI (graphical user interface) programs. The MFC simplifies writing these programs, and it provides many high-level features that can save you considerable coding effort. Although you can build Windows GUI programs in C or C++ without using the MFC, this book (in Part III) teaches Windows GUI programming with the MFC, so be sure to install it for working with the book. You can also install the Microsoft Active Template Library (ATL), which is a set of template-based C++ classes that facilitate creating ActiveX controls and other types of COM (Component Object Model) objects.
The ATL provides an alternative to using the MFC to create COM objects. Objects created using the ATL tend to be smaller and faster than those created using the MFC. However, the ATL doesn’t provide the extensive set of built-in features or the ease of programming that the MFC offers.

VC++ Build Tools
This component of Visual C++ consists of the optimizing C/C++ compiler, the incremental linker, the resource compiler (for preparing program resources such as menus and dialog boxes), and the other tools required to generate 32-bit Windows programs. You generally run these tools through the Microsoft Developer Studio.

ActiveX
This component installs ActiveX controls that you can add to the Windows programs you create using the Microsoft Foundation Classes library. ActiveX controls are reusable software components that can perform a wide variety of tasks.

Data Access
The Data Access component includes database drivers, controls, and other tools that are used by Visual C++, and that allow you to develop Windows database programs.


There are several things to notice in this list:
·        First, most classes in MFC derive from a base class called CObject. This class contains data members and member functions that are common to most MFC classes.
·        The second thing to notice is the simplicity of the list. The CWinApp class is used whenever you create an application and it is used only once in any program.
·        The CWnd class collects all the common features found in windows, dialog boxes, and controls.
·        The CFrameWnd class is derived from CWnd and implements a normal framed application window.
·        CDialog handles the two normal flavors of dialogs: modeless and modal respectively.
·        CView is used to give a user access to a document through a window.
·        Finally, Windows supports six native control types: static text, editable text, push buttons, scroll bars, lists, and combo boxes (an extended form of list).
·        Once you understand this fairly small number of pieces, you are well on your way to a complete understanding of MFC.
·        The other classes in the MFC hierarchy implement other features such as memory management, document control, data base support, and so on.
·        To create a program in MFC, you either use its classes directly or, more commonly, you derive new classes from the existing classes. In the derived classes you create new member functions that allow instances of the class to behave properly in your application.

Control Usage In Application :
  • Static text labels
  • Editable text areas (single and multi-line)
  • Push buttons
  • List boxes
  • Combo boxes (a more advanced form of list)
  • Radio boxes
  • Check boxes
  • Scroll bars

Window Styles

  • WS_BORDER   Creates a window that has a border.
  • WS_CAPTION   Creates a window that has a title bar (implies the WS_BORDER style). Cannot be used with the WS_DLGFRAME style.
  • WS_CHILD   Creates a child window. Cannot be used with the WS_POPUP style.
  • WS_CLIPCHILDREN   Excludes the area occupied by child windows when you draw within the parent window. Used when you create the parent window.
  • WS_CLIPSIBLINGS   Clips child windows relative to each other; that is, when a particular child window receives a paint message, the WS_CLIPSIBLINGS style clips all other overlapped child windows out of the region of the child window to be updated. (If WS_CLIPSIBLINGS is not given and child windows overlap, when you draw within the client area of a child window, it is possible to draw within the client area of a neigh boring child window.) For use with the WS_CHILD style only.
  • WS_DISABLED   Creates a window that is initially disabled.
  • WS_DLGFRAME   Creates a window with a double border but no title.
  • WS_GROUP   Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style FALSE after the first control belong to the same group. The next control with the WS_GROUP style starts the next group (that is, one group ends where the next begins).
  • WS_HSCROLL   Creates a window that has a horizontal scroll bar.
  • WS_MAXIMIZE   Creates a window of maximum size.
  • WS_MAXIMIZEBOX   Creates a window that has a Maximize button.
  • WS_MINIMIZE   Creates a window that is initially minimized. For use with the WS_OVERLAPPED style only.
  • WS_MINIMIZEBOX   Creates a window that has a Minimize button.
  • WS_OVERLAPPED   Creates an overlapped window. An overlapped window usually has a caption and a border.
  • WS_OVERLAPPEDWINDOW   Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles.
  • WS_POPUP   Creates a pop-up window. Cannot be used with the WS_CHILD style.
  • WS_POPUPWINDOW   Creates a pop-up window with the WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to make the Control menu visible.
  • WS_SYSMENU   Creates a window that has a Control-menu box in its title bar. Used only for windows with title bars.
  • WS_TABSTOP   Specifies one of any number of controls through which the user can move by using the TAB key. The TAB key moves the user to the next control specified by the WS_TABSTOP style.
  • WS_THICKFRAME   Creates a window with a thick frame that can be used to size the window.
  • WS_VISIBLE   Creates a window that is initially visible.
  • WS_VSCROLL   Creates a window that has a vertical scroll bar.

Static text labels
The CStatic class provides the functionality of a Windows static control. A static control displays a text string, box, rectangle, icon, cursor, bitmap, or enhanced metafile. It can be used to label, box, or separate other controls. A static control normally takes no input and provides no output; however, it can notify its parent of mouse clicks if it's created with SS_NOTIFY style.
Create a static control in two steps. First, call the constructor to construct the CStatic object, then call the Create member function to create the static control and attach it to the CStatic object.
If you create a CStatic object within a dialog box (through a dialog resource), the CStatic object is automatically destroyed when the user closes the dialog box.
If you create a CStatic object within a window, you may also need to destroy it.
Member Function:
Construction
Constructs a CStatic object.

Initialization
Creates the Windows static control and attaches it to the CStatic object.

Operations
Specifies a bitmap to be displayed in the static control.
Retrieves the handle of the bitmap previously set with SetBitmap.
Specifies an icon to be displayed in the static control.
Retrieves the handle of the icon previously set with SetIcon.
Specifies a cursor image to be displayed in the static control.
Retrieves the handle of the cursor image previously set with SetCursor.

Example :

CStatic *myStatic = new CStatic;
// Create a child static control that centers its text horizontally.
myStatic->Create("my static", WS_CHILD|WS_VISIBLE|SS_CENTER, CRect(10,10,150,30), this);

Static Styles

·         SS_BLACKFRAME   Specifies a box with a frame drawn with the same color as window frames. The default is black.
·         SS_BLACKRECT   Specifies a rectangle filled with the color used to draw window frames. The default is black.
·         SS_CENTER   Designates a simple rectangle and displays the given text centered in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next centered line.
·         SS_GRAYFRAME   Specifies a box with a frame drawn with the same color as the screen background (desktop). The default is gray.
·         SS_GRAYRECT   Specifies a rectangle filled with the color used to fill the screen background. The default is gray.
·         SS_ICON   Designates an icon displayed in the dialog box. The given text is the name of an icon (not a filename) defined elsewhere in the resource file. The nWidth and nHeight parameters are ignored; the icon automatically sizes itself.
·         SS_LEFT   Designates a simple rectangle and displays the given text flush-left in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next flush-left line.
·         SS_NOPREFIX   Unless this style is specified, Windows will interpret any ampersand (&) characters in the control’s text to be accelerator prefix characters. In this case, the ampersand (&) is removed and the next character in the string is underlined. If a static control is to contain text where this feature is not wanted, SS_NOPREFIX may be added. This static-control style may be included with any of the defined static controls. You can combine SS_NOPREFIX with other styles by using the bitwise OR operator. This is most often used when filenames or other strings that may contain an ampersand (&) need to be displayed in a static control in a dialog box.
·         SS_RIGHT   Designates a simple rectangle and displays the given text flush-right in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next flush-right line.
·         SS_SIMPLE   Designates a simple rectangle and displays a single line of text flush-left in the rectangle. The line of text cannot be shortened or altered in any way. (The control’s parent window or dialog box must not process the WM_CTLCOLOR message.)
·         SS_WHITEFRAME   Specifies a box with a frame drawn with the same color as the window background. The default is white.
·         SS_WHITERECT   Specifies a rectangle filled with the color used to fill the window background. The default is white.





Editable text areas (single and multi-line)
The CEdit class provides the functionality of a Windows edit control. An edit control is a rectangular child window in which the user can enter text.
You can create an edit control either from a dialog template or directly in your code. In both cases, first call the constructor CEdit to construct the CEdit object, then call the Create member function to create the Windows edit control and attach it to the CEdit object.
Construction can be a one-step process in a class derived from CEdit. Write a constructor for the derived class and call Create from within the constructor.
CEdit inherits significant functionality from CWnd. To set and retrieve text from a CEdit object, use the CWnd member functions SetWindowText and GetWindowText, which set or get the entire contents of an edit control, even if  it is a multiline control.  Also, if an edit control is multiline, get and set part of the control’s text by calling the CEdit member functions GetLine, SetSel, GetSel, and ReplaceSel.
Member Functions
Construction
Constructs a CEdit control object.
Creates the Windows edit control and attaches it to the CEdit object.

CEdit Attributes
Retrieves the number of lines in a multiple-line edit control.
Determines whether the contents of an edit control have been modified.
Sets or clears the modification flag for an edit control.
Gets the formatting rectangle of an edit control.
Gets the starting and ending character positions of the current selection in an edit control.
Sets the maximum amount of text this CEdit can contain.
Gets the maximum amount of text this CEdit can contain.
Retrieves a line of text from an edit control.
Retrieves the password character displayed in an edit control when the user enters text.
Determines the topmost visible line in an edit control.

CEdit Operations
Limits the length of the text that the user may enter into an edit control.
Retrieves the character index of a line within a multiple-line edit control.
Retrieves the length of a line in an edit control.
Replaces the current selection in an edit control with the specified text.
Sets or removes a password character displayed in an edit control when the user enters text.
Sets the formatting rectangle of a multiple-line edit control and updates the control.
Selects a range of characters in an edit control.
Sets the tab stops in a multiple-line edit control.
Sets the read-only state of an edit control.

CEdit Clipboard Operations
Reverses the last edit-control operation.
Deletes (clears) the current selection (if any) in the edit control.
Copies the current selection (if any) in the edit control to the Clipboard in CF_TEXT format.
Deletes (cuts) the current selection (if any) in the edit control and copies the deleted text to the Clipboard in CF_TEXT format.
Inserts the data from the Clipboard into the edit control at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format.

Example :
CEdit* pEdit = new CEdit;
pEdit->Create(ES_MULTILINE | WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER, CRect(10, 30, 100, 100), this, 1);

Edit Styles

  • ES_CENTER   Centers text in a single-line or multiline edit control.
  • ES_LEFT   Left-aligns text in a single-line or multiline edit control.
  • ES_LOWERCASE   Converts all characters to lowercase as they are typed into the edit control.
  • ES_MULTILINE   Designates a multiple-line edit control. (The default is single line.) If the ES_AUTOVSCROLL style is specified, the edit control shows as many lines as possible and scrolls vertically when the user presses the ENTER key. If ES_AUTOVSCROLL is not given, the edit control shows as many lines as possible and beeps if ENTER is pressed when no more lines can be displayed. If the ES_AUTOHSCROLL style is specified, the multiple-line edit control automatically scrolls horizontally when the caret goes past the right edge of the control. To start a new line, the user must press ENTER. If ES_AUTOHSCROLL is not given, the control automatically wraps words to the beginning of the next line when necessary; a new line is also started if ENTER is pressed. The position of the wordwrap is determined by the window size. If the window size changes, the wordwrap position changes and the text is redisplayed. Multiple-line edit controls can have scroll bars. An edit control with scroll bars processes its own scroll-bar messages. Edit controls without scroll bars scroll as described above and process any scroll messages sent by the parent window.
  • ES_NOHIDESEL   Normally, an edit control hides the selection when the control loses the input focus and inverts the selection when the control receives the input focus. Specifying ES_NOHIDESEL deletes this default action.
  • ES_PASSWORD   Displays all characters as an asterisk (*) as they are typed into the edit control. An application can use the SetPasswordChar member function to change the character that is displayed.
  • ES_RIGHT   Right-aligns text in a single-line or multiline edit control.
  • ES_UPPERCASE   Converts all characters to uppercase as they are typed into the edit control.
  • ES_READONLY   Prevents the user from entering or editing text in the edit control.
  • ES_WANTRETURN   Specifies that a carriage return be inserted when the user presses the ENTER key while entering text into a multiple-line edit control in a dialog box. Without this style, pressing the ENTER key has the same effect as pressing the dialog box’s default pushbutton. This style has no effect on a single-line edit control.


Push buttons \ Radio buttons \ Check Box \ 3 state Buttons
The CButton class provides the functionality of Windows button controls. A button control is a small, rectangular child window that can be clicked on and off. Buttons can be used alone or in groups and can either be labeled or appear without text. A button typically changes appearance when the user clicks it.
Typical buttons are the check box, radio button, and pushbutton. A CButton object can become any of these, according to the button style specified at its initialization by the Create member function.
In addition, the CBitmapButton class derived from CButton supports creation of button controls labeled with bitmap images instead of text. A CBitmapButton can have separate bitmaps for a button's up, down, focused, and disabled states.
You can create a button control either from a dialog template or directly in your code. In both cases, first call the constructor CButton to construct the CButton object; then call the Create member function to create the Windows button control and attach it to the CButton object.
Member Functions
Construction
Constructs a CButton object.

Initialization
Creates the Windows button control and attaches it to the CButton object.

Operations
Retrieves the check state, highlight state, and focus state of a button control.
Sets the highlighting state of a button control.
Retrieves the check state of a button control.
Sets the check state of a button control.
Retrieves information about the button control style.
Changes the style of a button.
Retrieves the handle of the icon previously set with SetIcon.
Specifies an icon to be displayed on the button.
Retrieves the handle of the bitmap previously set with SetBitmap.
Specifies a bitmap to be displayed on the button.
Retrieves the handle of the cursor image previously set with SetCursor.
Specifies a cursor image to be displayed on the button.

Overridables
Override to draw an owner-drawn CButton object.
Example :
CButton *myButton1, *myButton2, *myButton3, *myButton4;
myButton1 = new CButton;
myButton2 = new CButton;
 myButton3 = new CButton;
 myButton4 = new CButton;

// Create a push button.
myButton1->Create("My button", WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,
   CRect(10,10,100,30), this, 1);

// Create a radio button.
myButton2->Create("My button", WS_CHILD|WS_VISIBLE|BS_RADIOBUTTON,
   CRect(10,40,100,70), this, 2);

// Create an auto 3-state button.
myButton3->Create("My button", WS_CHILD|WS_VISIBLE|BS_AUTO3STATE,
   CRect(10,70,100,100), this, 3);

// Create an auto check box.
myButton4->Create("My button", WS_CHILD|WS_VISIBLE|BS_AUTOCHECKBOX,
   CRect(10,100,100,130), this, 4);

Button Styles

  • BS_AUTOCHECKBOX   Same as a check box, except that a check mark appears in the check box when the user selects the box; the check mark disappears the next time the user selects the box.
  • BS_AUTORADIOBUTTON   Same as a radio button, except that when the user selects it, the button automatically highlights itself and removes the selection from any other radio buttons with the same style in the same group.
  • BS_AUTO3STATE   Same as a three-state check box, except that the box changes its state when the user selects it.
  • BS_CHECKBOX   Creates a small square that has text displayed to its right (unless this style is combined with the BS_LEFTTEXT style).
  • BS_DEFPUSHBUTTON   Creates a button that has a heavy black border. The user can select this button by pressing the ENTER key. This style enables the user to quickly select the most likely option (the default option).
  • BS_GROUPBOX   Creates a rectangle in which other buttons can be grouped. Any text associated with this style is displayed in the rectangle’s upper-left corner.
  • BS_LEFTTEXT   When combined with a radio-button or check-box style, the text appears on the left side of the radio button or check box.
  • BS_OWNERDRAW   Creates an owner-drawn button. The framework calls the DrawItem member function when a visual aspect of the button has changed. This style must be set when using the CBitmapButton class.
  • BS_PUSHBUTTON   Creates a pushbutton that posts a WM_COMMAND message to the owner window when the user selects the button.
  • BS_RADIOBUTTON   Creates a small circle that has text displayed to its right (unless this style is combined with the BS_LEFTTEXT style). Radio buttons are usually used in groups of related but mutually exclusive choices.
  • BS_3STATE   Same as a check box, except that the box can be dimmed as well as checked. The dimmed state typically is used to show that a check box has been disabled.

ComboBox

The CComboBox class provides the functionality of a Windows combo box.
A combo box consists of a list box combined with either a static control or edit control. The list-box portion of the control may be displayed at all times or may only drop down when the user selects the drop-down arrow next to the control.
The currently selected item (if any) in the list box is displayed in the static or edit control. In addition, if the combo box has the drop-down list style, the user can type the initial character of one of the items in the list, and the list box, if visible, will highlight the next item with that initial character.
The following table compares the three combo-box styles
Style
When is Combo box visible?
Static or edit control?
Simple
Always
Edit
Drop-down
When dropped down
Edit
Drop-down list
When dropped down
Static

You can create a CComboBox object from either a dialog template or directly in your code. In both cases, first call the constructor CComboBox to construct the CComboBox object; then call the Create member function to create the control and attach it to the CComboBox object.
Member Function
Construction
Constructs a CComboBox object.

Initialization
Creates the combo box and attaches it to the CComboBox object.
Preallocates blocks of memory for items and strings in the list-box portion of the combo box.

General Operations
Retrieves the number of items in the list box of a combo box.
Retrieves the index of the currently selected item, if any, in the list box of a combo box.
Selects a string in the list box of a combo box.
Retrieves the application-supplied 32-bit value associated with the specified combo-box item.
Retrieves the application-supplied 32-bit value associated with the specified combo-box item as a pointer (void*).
Returns the index of the first visible item in the list-box portion of the combo box.
Tells the list-box portion of the combo box to display the item with the specified index at the top.
Sets the width in pixels that the list-box portion of the combo box can be scrolled horizontally.
Returns the width in pixels that the list-box portion of the combo box can be scrolled horizontally.
Sets the minimum allowable width for the drop-down list-box portion of a combo box.
Retrieves the minimum allowable width for the drop-down list-box portion of a combo box.
Deletes (clears) the current selection (if any) in the edit control.
Copies the current selection (if any) onto the Clipboard in CF_TEXT format.
Deletes (cuts) the current selection, if any, in the edit control and copies the deleted text onto the Clipboard in CF_TEXT format.
Inserts the data from the Clipboard into the edit control at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format.
Limits the length of the text that the user can enter into the edit control of a combo box.
Sets the height of list items in a combo box or the height of the edit-control (or static-text) portion of a combo box.
Retrieves the height of list items in a combo box.
Gets a string from the list box of a combo box.
Gets the length of a string in the list box of a combo box.
Shows or hides the list box of a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

String Operations
Adds a string to the end of the list in the list box of a combo box or at the sorted position for list boxes with the CBS_SORT style.
Deletes a string from the list box of a combo box.
Inserts a string into the list box of a combo box.
Removes all items from the list box and edit control of a combo box.
Adds a list of filenames to the list box of a combo box.
Finds the first string that contains the specified prefix in the list box of a combo box.
Finds the first list-box string (in a combo box) that matches the specified string.
Searches for a string in the list box of a combo box and, if the string is found, selects the string in the list box and copies the string to the edit control.

Overridables
Called by the framework when a visual aspect of an owner-draw combo box changes.
Called by the framework to determine combo box dimensions when an owner-draw combo box is created.
Called by the framework to determine the relative position of a new list item in a sorted owner-draw combo box.


Example:
CComboBox* pmyComboBox;
 
pmyComboBox->Create(
      WS_CHILD|WS_VISIBLE|WS_VSCROLL|CBS_DROPDOWNLIST,
      CRect(10,10,200,100), this, 1);


Combo-Box Styles

  • CBS_AUTOHSCROLL   Automatically scrolls the text in the edit control to the right when the user types a character at the end of the line. If this style is not set, only text that fits within the rectangular boundary is allowed.
  • CBS_DROPDOWN   Similar to CBS_SIMPLE, except that the list box is not displayed unless the user selects an icon next to the edit control.
  • CBS_DROPDOWNLIST   Similar to CBS_DROPDOWN, except that the edit control is replaced by a static-text item that displays the current selection in the list box.
  • CBS_HASSTRINGS   An owner-draw combo box contains items consisting of strings. The combo box maintains the memory and pointers for the strings so the application can use the GetText member function to retrieve the text for a particular item.
  • CBS_OEMCONVERT   Text entered in the combo-box edit control is converted from the ANSI character set to the OEM character set and then back to ANSI. This ensures proper character conversion when the application calls the AnsiToOem Windows function to convert an ANSI string in the combo box to OEM characters. This style is most useful for combo boxes that contain filenames and applies only to combo boxes created with the CBS_SIMPLE or CBS_DROPDOWN styles.
  • CBS_OWNERDRAWFIXED   The owner of the list box is responsible for drawing its contents; the items in the list box are all the same height.
  • CBS_OWNERDRAWVARIABLE   The owner of the list box is responsible for drawing its contents; the items in the list box are variable in height.
  • CBS_SIMPLE   The list box is displayed at all times. The current selection in the list box is displayed in the edit control.
  • CBS_SORT   Automatically sorts strings entered into the list box.
  • CBS_DISABLENOSCROLL   The list box shows a disabled vertical scroll bar when the list box does not contain enough items to scroll. Without this style, the scroll bar is hidden when the list box does not contain enough items.
  • CBS_NOINTEGRALHEIGHT   Specifies that the size of the combo box is exactly the size specified by the application when it created the combo box. Normally, Windows sizes a combo box so that the combo box does not display partial items.

List Boxes
The CListBox class provides the functionality of a Windows list box. A list box displays a list of items, such as filenames, that the user can view and select.
In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window.
Member Functions
Construction
Constructs a CListBox object.

Initialization
Creates the Windows list box and attaches it to the CListBox object.
Preallocates blocks of memory for list box items and strings.

General Operations
Returns the number of strings in a list box.
Returns the index of the first visible string in a list box.
Sets the zero-based index of the first visible string in a list box.
Returns the bounding rectangle of the list-box item as it is currently displayed.
Sets the height of items in a list box.
Determines the height of items in a list box.
Returns the selection state of a list-box item.
Copies a list-box item into a buffer.
Returns the length in bytes of a list-box item.
Sets the column width of a multicolumn list box.
Sets the tab-stop positions in a list box.

Single-Selection Operations
Returns the zero-based index of the currently selected string in a list box.
Selects a list-box string.

Multiple-Selection Operations
Selects or deselects a list-box item in a multiple-selection list box.
Determines the index of the item that has the focus rectangle in a multiple-selection list box.
Sets the focus rectangle to the item at the specified index in a multiple-selection list box.
Returns the number of strings currently selected in a multiple-selection list box.
Returns the indices of the strings currently selected in a list box.
Selects or deselects a range of strings in a multiple-selection list box.
Sets the anchor in a multiple-selection list box to begin an extended selection.
Retrieves the zero-based index of the current anchor item in a list box.

String Operations
Adds a string to a list box.
Deletes a string from a list box.
Inserts a string at a specific location in a list box.
Clears all the entries from a list box.
Adds filenames from the current directory to a list box.
Searches for a string in a list box.
Finds the first list-box string that matches a specified string.
Searches for and selects a string in a single-selection list box.

Overridables
Called by the framework when a visual aspect of an owner-draw list box changes.
Called by the framework when an owner-draw list box is created to determine list-box dimensions.
Called by the framework to determine the position of a new item in a sorted owner-draw list box.
Called by the framework when the user deletes an item from an owner-draw list box.
Override to provide custom WM_CHAR handling for owner-draw list boxes which don't have strings.
Example :
CListBox* pmyListBox = new CListBox;
 
pmyListBox->Create(WS_CHILD|WS_VISIBLE|LBS_STANDARD|WS_HSCROLL, 
   CRect(10,10,200,200), pParentWnd, 1);

List-Box Styles

  • LBS_EXTENDEDSEL   The user can select multiple items using the SHIFT key and the mouse or special key combinations.
  • LBS_HASSTRINGS   Specifies an owner-draw list box that contains items consisting of strings. The list box maintains the memory and pointers for the strings so the application can use the GetText member function to retrieve the text for a particular item.
  • LBS_MULTICOLUMN   Specifies a multicolumn list box that is scrolled horizontally. The SetColumnWidth member function sets the width of the columns.
  • LBS_MULTIPLESEL   String selection is toggled each time the user clicks or double-clicks the string. Any number of strings can be selected.
  • LBS_NOINTEGRALHEIGHT   The size of the list box is exactly the size specified by the application when it created the list box. Usually, Windows sizes a list box so that the list box does not display partial items.
  • LBS_NOREDRAW   List-box display is not updated when changes are made. This style can be changed at any time by sending a WM_SETREDRAW message.
  • LBS_NOTIFY   Parent window receives an input message whenever the user clicks or double-clicks a string.
  • LBS_OWNERDRAWFIXED   The owner of the list box is responsible for drawing its contents; the items in the list box are the same height.
  • LBS_OWNERDRAWVARIABLE   The owner of the list box is responsible for drawing its contents; the items in the list box are variable in height.
  • LBS_SORT   Strings in the list box are sorted alphabetically.
  • LBS_STANDARD   Strings in the list box are sorted alphabetically, and the parent window receives an input message whenever the user clicks or double-clicks a string. The list box contains borders on all sides.
  • LBS_USETABSTOPS   Allows a list box to recognize and expand tab characters when drawing its strings. The default tab positions are 32 dialog units. (A dialog unit is a horizontal or vertical distance. One horizontal dialog unit is equal to one-fourth of the current dialog base width unit. The dialog base units are computed based on the height and width of the current system font. The GetDialogBaseUnits Windows function returns the current dialog base units in pixels.)
  • LBS_WANTKEYBOARDINPUT   The owner of the list box receives WM_VKEYTOITEM or WM_CHARTOITEM messages whenever the user presses a key while the list box has input focus. This allows an application to perform special processing on the keyboard input.
  • LBS_DISABLENOSCROLL   The list box shows a disabled vertical scroll bar when the list box does not contain enough items to scroll. Without this style, the scroll bar is hidden when the list box does not contain enough items.

Message Handling :
What kinds of messages do you write handlers for? There are three main categories:
  1. Windows messages
This includes primarily those messages beginning with the WM_ prefix, except for WM_COMMAND. Windows messages are handled by windows and views. These messages often have parameters that are used in determining how to handle the message.
  1. Control notifications
This includes WM_COMMAND notification messages from controls and other child windows to their parent windows. For example, an edit control sends its parent a WM_COMMAND message containing the EN_CHANGE control-notification code when the user has taken an action that may have altered text in the edit control. The window’s handler for the message responds to the notification message in some appropriate way, such as retrieving the text in the control.
The framework routes control-notification messages like other WM_ messages. One exception, however, is the BN_CLICKED control-notification message sent by buttons when the user clicks them. This message is treated specially as a command message and routed like other commands.
  1. Command messages
This includes WM_COMMAND notification messages from user-interface objects: menus, toolbar buttons, and accelerator keys. The framework processes commands differently from other messages, and they can be handled by more kinds of objects, as explained in Command Targets.
Message Maps :
DECLARE_MESSAGE_MAP( )
Each CCmdTarget-derived class in your program must provide a message map to handle messages. Use the DECLARE_MESSAGE_MAP macro at the end of your class declaration. Then, in the .CPP file that defines the member functions for the class, use the BEGIN_MESSAGE_MAP macro, macro entries for each of your message-handler functions, and the END_MESSAGE_MAP macro.
Note   If you declare any member after DECLARE_MESSAGE_MAP, you must specify a new access type (public, private, or protected) for them.
class CTmpDlg : public CDialog
{
          // Member Functions

DECLARE_MESSAGE_MAP()
};


BEGIN_MESSAGE_MAP( theClass, baseClass )
Use the BEGIN_MESSAGE_MAP macro to begin the definition of your message map.
In the implementation (.CPP) file that defines the member functions for your class, start the message map with the BEGIN_MESSAGE_MAP macro, then add macro entries for each of your message-handler functions, and complete the message map with the END_MESSAGE_MAP macro.
ON_Notification( id, memberFxn )
Eg.
BEGIN_MESSAGE_MAP(CTmpDlg, CDialog)
          ON_BN_CLICKED(IDC_BUTTON, OnButton)
END_MESSAGE_MAP()
Member Function for Message map :
  • Declaration :
afx_msg void memberFxn( );
e.g.
class CTmpDlg : public CDialog
{
          // Member Functions

                                    afx_msg void OnButton ( );

DECLARE_MESSAGE_MAP()
};
·         Implementation :
E,g,:
void CTmpDlg::OnButton()
{
                        // TODO: Add your control notification handler code here
            }


Buttons Map Entry

ON_BN_CLICKED
The user clicks a button.
ON_BN_DOUBLECLICKED
The user double-clicks a button.
Edit Box Map Entry

ON_EN_CHANGE 
The user has taken an action that may have altered text in an edit control. Unlike the EN_UPDATE notification message, this notification message is sent after Windows updates the display.
ON_EN_KILLFOCUS
The edit control loses the input focus.
Combo Box Map Entry

ON_CBN_SELCHANGE
The selection in the list box of a combo box is about to be changed as a result of the user either clicking in the list box or changing the selection by using the arrow keys. When processing this message, the text in the edit control of the combo box can only be retrieved via GetLBText or another similar function. GetWindowText cannot be used.
List Box Map Entry

ON_LBN_SETFOCUS 
The list box is receiving the input focus.

Mouse and Keyboard Interaction :

Getting Input from the Mouse

Windows uses a number of different messages—more than 20 in all—to report input events involving the mouse. These messages fall into two rather broad categories: client-area mouse messages, which report events that occur in a window's client area, and nonclient-area mouse messages, which pertain to events in a window's nonclient area. An "event" can be any of the following:
  • The press or release of a mouse button
  • The double click of a mouse button
  • The movement of the mouse
You'll typically ignore events in the nonclient area of your window and allow Windows to handle them. If your program processes mouse input, it's client-area mouse messages you'll probably be concerned with.

Client-Area Mouse Messages

Windows reports mouse events in a window's client area using the messages shown in the following table.
Client-Area Mouse Messages
Message
Sent When
WM_LBUTTONDOWN
The left mouse button is pressed.
WM_LBUTTONUP
The left mouse button is released.
WM_LBUTTONDBLCLK
The left mouse button is double-clicked.
WM_MBUTTONDOWN
The middle mouse button is pressed.
WM_MBUTTONUP
The middle mouse button is released.
WM_MBUTTONDBLCLK
The middle mouse button is double-clicked.
WM_RBUTTONDOWN
The right mouse button is pressed.
WM_RBUTTONUP
The right mouse button is released.
WM_RBUTTONDBLCLK
The right mouse button is double-clicked.
WM_MOUSEMOVE
The cursor is moved over the window's client area.
Messages that begin with WM_LBUTTON pertain to the left mouse button, WM_MBUTTON messages to the middle mouse button, and WM_RBUTTON messages to the right mouse button. An application won't receive WM_MBUTTON messages if the mouse has only two buttons. An application won't receive WM_RBUTTON messages if the mouse has just one button. The vast majority of PCs running Windows have two-button mice, so it's reasonably safe to assume that the right mouse button exists. However, if you'd like to be certain (or if you'd like to determine whether there is a third button, too), you can use the Windows ::GetSystemMetrics API function:
Message-Map Macros and Message Handlers for Client-Area Mouse Messages
Message
Message-Map Macro
Handling Function
WM_LBUTTONDOWN
ON_WM_LBUTTONDOWN
OnLButtonDown
WM_LBUTTONUP
ON_WM_LBUTTONUP
OnLButtonUp
WM_LBUTTONDBLCLK
ON_WM_LBUTTONDBLCLK
OnLButtonDblClk
WM_MBUTTONDOWN
ON_WM_MBUTTONDOWN
OnMButtonDown
WM_MBUTTONUP
ON_WM_MBUTTONUP
OnMButtonUp
WM_MBUTTONDBLCLK
ON_WM_MBUTTONDBLCLK
OnMButtonDblClk
WM_RBUTTONDOWN
ON_WM_RBUTTONDOWN
OnRButtonDown
WM_RBUTTONUP
ON_WM_RBUTTONUP
OnRButtonUp
WM_RBUTTONDBLCLK
ON_WM_RBUTTONDBLCLK
OnRButtonDblClk
WM_MOUSEMOVE
ON_WM_MOUSEMOVE
OnMouseMove
OnLButtonDown and other client-area mouse message handlers are prototyped as follows:
afx_msg void On_MsgName (UINT nFlags, CPoint point)
point identifies the location of the cursor( x and y co-ordinates).
The nFlags parameter specifies the state of the mouse buttons and of the Shift and Ctrl keys at the time the message was generated. You can find out from this parameter whether a particular button or key is up or down by testing for the bit flags listed in the following table.
The nFlags Parameter
Mask
Meaning If Set
MK_LBUTTON
The left mouse button is pressed.
MK_MBUTTON
The middle mouse button is pressed.
MK_RBUTTON
The right mouse button is pressed.
MK_CONTROL
The Ctrl key is pressed.
MK_SHIFT
The Shift key is pressed.
The expression
nFlags & MK_LBUTTON
is nonzero if and only if the left mouse button is pressed, while

Nonclient-Area Mouse Messages

When the mouse is clicked inside or moved over a window's nonclient area, Windows sends the window a nonclient-area mouse message. The following table lists the nonclient-area mouse messages.
Nonclient-Area Mouse Messages
Message
Sent When
WM_NCLBUTTONDOWN
The left mouse button is pressed.
WM_NCLBUTTONUP
The left mouse button is released.
WM_NCLBUTTONDBLCLK
The left mouse button is double-clicked.
WM_NCMBUTTONDOWN
The middle mouse button is pressed.
WM_NCMBUTTONUP
The middle mouse button is released.
WM_NCMBUTTONDBLCLK
The middle mouse button is double-clicked.
WM_NCRBUTTONDOWN
The right mouse button is pressed.
WM_NCRBUTTONUP
The right mouse button is released.
WM_NCRBUTTONDBLCLK
The right mouse button is double-clicked.
WM_NCMOUSEMOVE
The cursor is moved over the window's nonclient area.
Notice the parallelism between the client-area mouse messages shown in the table below and the nonclient-area mouse messages; the only difference is the letters NC in the message ID. Unlike double-click messages in a window's client area, WM_NCxBUTTONDBLCLK messages are transmitted regardless of whether the window was registered with the CS_DBLCLKS style.
As with client-area mouse messages, message-map entries route messages to the appropriate class member functions. The following table lists the message-map macros and message handlers for nonclient-area mouse messages.
Message-Map Macros and Message Handlers for Nonclient-Area Mouse Messages
Message
Message-Map Macro
Handling Function
WM_NCLBUTTONDOWN
ON_WM_NCLBUTTONDOWN
OnNcLButtonDown
WM_NCLBUTTONUP
ON_WM_NCLBUTTONUP
OnNcLButtonUp
WM_NCLBUTTONDBLCLK
ON_WM_NCLBUTTONDBLCLK
OnNcLButtonDblClk
WM_NCMBUTTONDOWN
ON_WM_NCMBUTTONDOWN
OnNcMButtonDown
WM_NCMBUTTONUP
ON_WM_NCMBUTTONUP
OnNcMButtonUp
WM_NCMBUTTONDBLCLK
ON_WM_NCMBUTTONDBLCLK
OnNcMButtonDblClk
WM_NCRBUTTONDOWN
ON_WM_NCRBUTTONDOWN
OnNcRButtonDown
WM_NCRBUTTONUP
ON_WM_NCRBUTTONUP
OnNcRButtonUp
WM_NCRBUTTONDBLCLK
ON_WM_NCRBUTTONDBLCLK
OnNcRButtonDblClk
WM_NCMOUSEMOVE
ON_WM_NCMOUSEMOVE
OnNcMouseMove
Message handlers for nonclient-area mouse messages are prototyped this way:
afx_msg void OnMsgName (UINT nHitTest, CPoint point)
Once again, the point parameter specifies the location in the window at which the event occurred. But for nonclient-area mouse messages, point.x and point.y contain screen coordinates rather than client coordinates. In screen coordinates, (0,0) corresponds to the upper left corner of the screen, the positive x and y axes point to the right and down, and one unit in any direction equals one pixel. If you want, you can convert screen coordinates to client coordinates with CWnd::ScreenToClient. The nHitTest parameter contains a hit-test code that identifies where in the window's nonclient area the event occurred. Some of the most interesting hit-test codes are shown in the following table. You'll find a complete list of hit-test codes in the documentation for WM_NCHITTEST or CWnd::OnNcHitTest.
Commonly Used Hit-Test Codes
Value
Corresponding Location
HTCAPTION
The title bar
HTCLOSE
The close button
HTGROWBOX
The restore button (same as HTSIZE)
HTHSCROLL
The window's horizontal scroll bar
HTMENU
The menu bar
HTREDUCE
The minimize button
HTSIZE
The restore button (same as HTGROWBOX)
HTSYSMENU
The system menu box
HTVSCROLL
The window's vertical scroll bar
HTZOOM
The maximize button





Getting Input from the Keyboard

A Windows application learns of keyboard events the same way it learns about mouse events: through messages. A program receives a message whenever a key is pressed or released. If you want to know when the Page Up or Page Down key is pressed so that your application can react accordingly, you process WM_KEYDOWN messages and check for key codes identifying the Page Up or Page Down key. If you'd rather know when a key is released, you process WM_KEYUP messages instead. For keys that produce printable characters, you can ignore key-down and key-up messages and process WM_CHAR messages that denote characters typed at the keyboard. Relying on WM_CHAR messages instead of WM_KEYUP/DOWN messages simplifies character processing by enabling Windows to factor in events and circumstances surrounding the keystroke, such as whether the Shift key is pressed, whether Caps Lock is on or off, and differences in keyboard layouts.
Keystroke message  handlers are prototyped as follows:
afx_msg void OnMsgName (UINT nChar, UINT nRepCnt, UINT nFlags)
nChar is the virtual key code of the key that was pressed or released. nRepCnt is the repeat count—the number of keystrokes encoded in the message. nRepCnt is usually equal to 1 for WM_KEYDOWN or WM_SYSKEYDOWN messages and is always 1 for WM_KEYUP or WM_SYSKEYUP messages. If key-down messages arrive so fast that your application can't keep up, Windows combines two or more WM_KEYDOWN or WM_SYSKEYDOWN messages into one and increases the repeat count accordingly. Most programs ignore the repeat count and treat combinatorial key-down messages (messages in which nRepCnt is greater than 1) as a single keystroke to prevent overruns—situations in which a program continues to scroll or otherwise respond to keystroke messages after the user's finger has released the key. In contrast to the PC's keyboard BIOS, which buffers incoming keystrokes and reports each one individually, the Windows method of reporting consecutive presses of the same key to your application provides a built-in hedge against keyboard overruns.
The nFlags parameter contains the key's scan code and zero or more of the bit flags described here:
Bit(s)
Meaning
Description
0_7
OEM scan code
8-bit OEM scan code
8
Extended key flag
1 if the key is an extended key, 0 if it is not
9_12
Reserved
N/A
13
Context code
1 if the Alt key is pressed, 0 if it is not
14
Previous key state
1 if the key was previously pressed, 0 if it was up
15
Transition state
0 if the key is being pressed, 1 if it is being released

Virtual Key Codes

The most important value by far that gets passed to a keystroke message handler is the nChar value identifying the key that was pressed or released. Windows identifies keys with the virtual key codes shown in the table below so that applications won't have to rely on hardcoded values or OEM scan codes that might differ from keyboard to keyboard.
 Virtual Key Codes
Virtual Key Code(s)
Corresponding Key(s)
VK_F1_VK_F12
Function keys F1_F12
VK_NUMPAD0_VK_NUMPAD9
Numeric keypad 0_9 with Num Lock on
VK_CANCEL
Ctrl-Break
VK_RETURN
Enter
VK_BACK
Backspace
VK_TAB
Tab
VK_CLEAR
Numeric keypad 5 with Num Lock off
VK_SHIFT
Shift
VK_CONTROL
Ctrl
VK_MENU
Alt
VK_PAUSE
Pause
VK_ESCAPE
Esc
VK_SPACE
Spacebar
VK_PRIOR
Page Up and PgUp
VK_NEXT
Page Down and PgDn
VK_END
End
VK_HOME
Home
VK_LEFT
Left arrow
VK_UP
Up arrow
VK_RIGHT
Right arrow
VK_DOWN
Down arrow
VK_SNAPSHOT
Print Screen
VK_INSERT
Insert and Ins
VK_DELETE
Delete and Del
VK_MULTIPLY
Numeric keypad *
VK_ADD
Numeric keypad +
VK_SUBTRACT
Numeric keypad -
VK_DECIMAL
Numeric keypad .
VK_DIVIDE
Numeric keypad /
VK_CAPITAL
Caps Lock
VK_NUMLOCK
Num Lock
VK_SCROLL
Scroll Lock
VK_LWIN
Left Windows key
VK_RWIN
Right Windows key
VK_APPS
Menu key ()








graphics device interface (GDI)
Classes for Windows GDI Objects
Class
Windows handle type
HPEN
HBRUSH
HFONT
HBITMAP
HPALETTE
HRGN

CFileDialog( BOOL bOpenFileDialog, LPCTSTR lpszDefExt = NULL, LPCTSTR lpszFileName = NULL, DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, LPCTSTR lpszFilter = NULL, CWnd* pParentWnd = NULL );
Invalidate(BOOL bErase = TRUE)
The bErase parameter specifies whether the background within the update area is to be erased when the update region is processed. If bErase is TRUE, the background is erased when the BeginPaint member function is called; if bErase is FALSE, the background remains unchanged. If bErase is TRUE for any part of the update region, the background in the entire region, not just in the given part, is erased.
STEPS FOR OPEN BITMAP FILE :
1.      Create a bitmap handle using the name of the file (LoadImage)
HANDLE LoadImage(
  HINSTANCE hinst,   // handle of the instance containing the image
  LPCTSTR lpszName,  // name or identifier of image
  UINT uType,        // type of image
  int cxDesired,     // desired width
  int cyDesired,     // desired height
  UINT fuLoad        // load flags
);
2.      Convert the Win32 bitmap handle into an MFC bitmap object and attach to it
3.      Call the Win32 GetObject() function to get the properties of the bitmap and store them in a BITMAP structure
typedef struct tagBITMAP {  /* bm */
    int     bmType;
    int     bmWidth;
    int     bmHeight;
    int     bmWidthBytes;
    BYTE    bmPlanes;
    BYTE    bmBitsPixel;
    LPVOID  bmBits;
} BITMAP
4.      Create a compatible device context (pDC to userdefined CDC )
5.      Select the bitmap into the device context (handled)
6.      Using the dimensions store in the BITMAP object, display the picture
BOOL BitBlt( int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, DWORD dwRop );
7.      Get the dimensions of the new picture (For ScrollView)
void SetScrollSizes( int nMapMode, SIZE sizeTotal, const SIZE& sizePage = sizeDefault, const SIZE& sizeLine = sizeDefault );
Mapping Mode
Logical Unit
Positive y-axis Extends...
MM_TEXT
1 pixel
Downward
MM_HIMETRIC
0.01 mm
Upward
MM_TWIPS
1/1440 in
Upward
MM_HIENGLISH
0.001 in
Upward
MM_LOMETRIC
0.1 mm
Upward
MM_LOENGLISH
0.01 in
Upward
8.      Restore the bitmap (selected in step 5)
9.      Delete the handled bitmap (Step 1)

GRAPHICS :

LINE :


void CExampleView::OnDraw(CDC* pDC)
{
    pDC->MoveTo(10, 22);
    pDC->LineTo(155, 64);
}

MoveTo() method is used to set the starting position of a line. When using LineTo(), the line would start from the MoveTo() point to the LineTo() end.


POLYLINE :
BOOL Polyline( LPPOINT lpPoints, int nCount );
Draws a set of line segments connecting the points specified by lpPoints. The lines are drawn from the first point through subsequent points using the current pen.

void CExampleView::OnDraw(CDC* pDC)
{
        CPoint Pt[7];
        Pt[0] = CPoint(20, 50);
        Pt[1] = CPoint(180, 50);
        Pt[2] = CPoint(180, 20);
        Pt[3] = CPoint(230, 70);
        Pt[4] = CPoint(180, 120);
        Pt[5] = CPoint(180, 90);
        Pt[6] = CPoint(20, 90);
        pDC->Polyline(Pt, 7);
}

BOOL PolylineTo( const POINT* lpPoints, int nCount );
void CExampleView::OnDraw(CDC* pDC)
{
        CPoint Pt[7];
 
        Pt[0] = CPoint(20, 50);
        Pt[1] = CPoint(180, 50);
        Pt[2] = CPoint(180, 20);
        Pt[3] = CPoint(230, 70);
        Pt[4] = CPoint(180, 120);
        Pt[5] = CPoint(180, 90);
        Pt[6] = CPoint(20, 90);
 
        pDC->PolylineTo(Pt, 7);
}

While the Polyline() method starts the first line at lpPoints[0], the PolylineTo() member function does not control the beginning of the first line. Like the LineTo() method, it simply starts drawing, which would mean it starts at the origin (0, 0). For this reason, if you want to control the starting point of the PolylineTo() drawing, you can use the MoveTo() method


BOOL PolyPolyline( const POINT* lpPoints, const DWORD* lpPolyPoints, int nCount );

void CExampleView::OnDraw(CDC* pDC)
{
        CPoint Pt[15];
        DWORD  lpPts[] = { 4, 4, 7 };
 
        // Left Triangle
        Pt[0] = Pt[3] = CPoint(50, 20);
        Pt[1] = CPoint(20, 60);
        Pt[2] = CPoint(80, 60);
        
        // Second Triangle
        Pt[4] = Pt[7] = CPoint(70, 20);
        Pt[5] = CPoint(100, 60);
        Pt[6] = CPoint(130, 20);
 
        // Hexagon
        Pt[8]  = Pt[14] = CPoint(145, 20);
        Pt[9]  = CPoint(130, 40);
        Pt[10] = CPoint(145, 60);
        Pt[11] = CPoint(165, 60);
        Pt[12] = CPoint(180, 40);
        Pt[13] = CPoint(165, 20);
 
        pDC->PolyPolyline(Pt, lpPts, 3);
}

This means that PolyPolyline() will not access their values at random. It will retrieve the first point, followed by the second, followed by the third, etc. Therefore, your first responsibility is to decide where one polyline starts and where it ends. The good news (of course depending on how you see it) is that a polyline does not start where the previous line ended. Each polyline has its own beginning and its own ending point.



POLYGON :

A polygon is a closed polyline. In other words, it is a polyline defined so that the end point of the last line is connected to the start point of the first line.

BOOL Polygon( LPPOINT lpPoints, int nCount );
void CExampleView::OnDraw(CDC* pDC)
{
        CPoint Pt[7];
        Pt[0] = CPoint(20, 50);
        Pt[1] = CPoint(180, 50);
        Pt[2] = CPoint(180, 20);
        Pt[3] = CPoint(230, 70);
        Pt[4] = CPoint(180, 120);
        Pt[5] = CPoint(180, 90);
        Pt[6] = CPoint(20, 90);
 
        pDC->Polygon(Pt, 7);
}



BOOL PolyPolygon( LPPOINT lpPoints, LPINT lpPolyCounts, int nCount );

Like the Polygon() method, the lpPoints argument is an array of POINT or CPoint values. The PolyPolygon() method needs to know the number of polygons you would be drawing.  Each polygon uses the points of the lpPoints values but when creating the array of points, the values must be incremental. This means that PolyPolygon() will not randomly access the values of lpPoints. Each polygon has its own set of points. 
Unlike Polygon(), the nCount argument of PolyPolygon() is the number of polygons you want to draw and not the number of points.
void CExampleView::OnDraw(CDC* pDC)
{
        CPoint Pt[12];
        int lpPts[] = { 3, 3, 3, 3 };
 
        // Top Triangle
        Pt[0] = CPoint(125,  10);
        Pt[1] = CPoint( 95,  70);
        Pt[2] = CPoint(155,  70);
 
        // Left Triangle
        Pt[3] = CPoint( 80,  80);
        Pt[4] = CPoint( 20, 110);
        Pt[5] = CPoint( 80, 140);
 
        // Bottom Triangle
        Pt[6] = CPoint( 95, 155);
        Pt[7] = CPoint(125, 215);
        Pt[8] = CPoint(155, 155);
        
        // Right Triangle
        Pt[9] = CPoint(170,  80);
        Pt[10] = CPoint(170, 140);
        Pt[11] = CPoint(230, 110);
 
        pDC->PolyPolygon(Pt, lpPts, 4);
}



RECTANGLE :


BOOL Rectangle( int x1, int y1, int x2, int y2 );
The drawing of a rectangle typically starts from a point defined as (X1, Y1) and ends at another point (X2, Y2).
When drawing a rectangle, if the value of x2 is less than that of x1, then the x2 coordinate would mark the left beginning of the figure. This scenario would also apply if the y2 coordinate were lower than y1.
void CExoView::OnDraw(CDC* pDC)
{
        pDC->Rectangle(20, 20, 226, 144);
}
BOOL Rectangle( LPCRECT lpRect );
void CExoView::OnDraw(CDC* pDC)
{
        CRect Recto(48, 25, 328, 125);
        pDC->Rectangle(&Recto);
}

A Rectangle With Edges
BOOL DrawEdge(LPRECT lpRect, UINT nEdge, UINT nFlags);
The lpRect argument is passed as a pointer to a RECT or CRect, which is the rectangle that would be drawn.
The nEdge value specifies how the interior and the exterior of the edges of the rectangle would be drawn. It can be a combination of the following constants:

Value
Description

BDR_RAISEDINNER
The interior edge will be raised

BDR_SUNKENINNER
The interior edge will be sunken

BDR_RAISEDOUTER
The exterior edge will be raised

BDR_SUNKENOUTER
The exterior edge will be sunken
These values can be combined using the bitwise OR operator. On the other hand, you can use the following constants instead:

Value
Used For

EDGE_DUMP
BDR_RAISEDOUTER | BDR_SUNKENINNER

EDGE_ETCHED
BDR_SUNKENOUTER | BDR_RAISEDINNER

EDGE_RAISED
BDR_RAISEDOUTER | BDR_RAISEDINNER

EDGE_SUNKEN
BDR_SUNKENOUTER | BDR_SUNKENINNER
The nFlags value specifies what edge(s) would be drawn. It can have one of the following values:

Value
Description

BF_RECT
The entire rectangle will be drawn

BF_TOP
Only the top side will be drawn

BF_LEFT
Only the left side will be drawn

BF_BOTTOM
Only the bottom side will be drawn

BF_RIGHT
Only the right side will be drawn

BF_TOPLEFT
Both the top and the left sides will be drawn

BF_BOTTOMLEFT
Both the bottom and the left sides will be drawn

BF_TOPRIGHT
Both the top and the right sides will be drawn

BF_BOTTOMRIGHT
Both the bottom and the right sides will be drawn

BF_DIAGONAL_ENDBOTTOMLEFT
A diagonal line will be drawn from the top-right to the bottom-left corners

BF_DIAGONAL_ENDBOTTOMRIGHT
A diagonal line will be drawn from the top-left to the bottom-right corners

BF_DIAGONAL_ENDTOPLEFT
A diagonal line will be drawn from the bottom-right to the top-left corners

BF_DIAGONAL_ENDTOPRIGHT
A diagonal line will be drawn from the bottom-left to the top-right corners
Here is an example:
void CExoView::OnDraw(CDC* pDC)
{
        CRect Recto(20, 20, 225, 115);
        pDC->DrawEdge(&Recto, BDR_RAISEDOUTER | BDR_SUNKENINNER, BF_RECT);
}
Drawing 3-D edges of a rectangle






0 comments:

Post a Comment