Unit-IV

64
Unit 4 – 16 MARK QUESTIONS & ANSWERS UNIT IV CONTROLS Dialog Based Applications, controls – Animate control, image list, CRect tracker – Tree control – CtabControl – Dynamic controls – slider control – progress control – Inheriting CTreeView – CRicheditView – Modal Dialog, – Modeless Dialog – CColorDialog – CfileDialog. Q1. What Is Dialog-Based Application. Write A Program For Dialog-Based Application Fo Calculator Program. The dialog window immediately appears when the user starts the application. The user can minimize the dialog window, and as long as the dialog is not system modal, the user can freely switch to other applications. Calculator dialog. 1.Create a New Application , app type : Dialog Based Application 2. Design the Dialog window like this Open the Properties dialog box and click on the Styles tab. Select the System Menu and Minimize Box options. Control ID Left operand edit control IDC_LEFT Right operand edit control IDC_RIGHT Result edit control IDC_RESULT

description

vp

Transcript of Unit-IV

Page 1: Unit-IV

Unit 4 – 16 MARK QUESTIONS & ANSWERS

UNIT IV CONTROLS Dialog Based Applications, controls – Animate control, image list, CRect tracker – Tree control – CtabControl – Dynamic controls – slider control – progress control – Inheriting CTreeView – CRicheditView – Modal Dialog, – Modeless Dialog – CColorDialog – CfileDialog.

Q1. What Is Dialog-Based Application. Write A Program For Dialog-Based Application Fo Calculator Program.

The dialog window immediately appears when the user starts the application. The user can minimize the dialog window, and as long as the dialog is not system modal, the user can freely switch to other applications.

Calculator dialog.

1. Create a New Application , app type : Dialog Based Application

2. Design the Dialog window like this

Open the Properties dialog box and click on the Styles tab. Select the System Menu and Minimize Box options.

Control ID

Left operand edit control IDC_LEFT

Right operand edit control IDC_RIGHT

Result edit control IDC_RESULT

First radio button (group property set) IDC_OPERATION

Compute pushbutton IDC_COMPUTE

3. Use ClassWizard to add member variables and a command handler.

Control ID Member Variable Type

IDC_LEFT m_dLeft double

Page 2: Unit-IV

IDC_RIGHT m_dRight double

IDC_RESULT m_dResult double

IDC_OPERATION m_nOperation int

4. Add the message handler OnCompute for the IDC_COMPUTE button. 5. Code the OnCompute member function UpdateData(TRUE); switch (m_nOperation) { case 0: // add m_Result = m_dLeft + m_dRight; break; case 1: // subtract m_dResult = m_dLeft - m_dRight; break; case 2: // multiply m_dResult = m_dLeft * m_dRight; break; case 3: // divide if (m_dRight != 0.0) { m_dResult = m_dLeft / m_dRight; } else { AfxMessageBox("Divide by zero"); m_dResult = 0.0; } break; } UpdateData(FALSE);}

6. Build and test application. Notice that the program's icon appears in the Microsoft Windows taskbar. Verify that you can minimize the dialog window.

Q2. Discuss the Animated Control in VC++ with example .

An animation control is a rectangular window that displays a clip in AVI (Audio Video Interleaved) format— the standard Windows video/audio format.

An AVI clip is a series of bitmap frames, like a movie.

◦ Provides the functionality of the Windows common animation control.

class CAnimateCtrl : public CWnd

Page 3: Unit-IV

Base Class Members

◦ CObject Members ◦ CCmdTarget Members ◦ CWnd Members

CAnimateCtrl

Constructs a CAnimateCtrl object.

You construct a CAnimateCtrl in two steps. First, call the constructor, and then call Create, which creates the animation control and attaches it to the CAnimateCtrl object.

CAnimateCtrl::Create

◦ Creates an animation control and attaches it to a CAnimateCtrl object. virtual BOOL

Create

( DWORD dwStyle,

const RECT& rect, CWnd* pParentWnd, UINT nID );

Apply the following window styles to an animation control.

WS_CHILD   Always WS_VISIBLE   Usually WS_DISABLED   Rarely

CAnimateCtrl:: CreateEx

Creates an animation control with the specified Windows extended styles and attaches it to a CAnimateCtrl object.Operations.

virtual BOOL CreateEx( DWORD dwStyleEx,DWORD dwStyle,

const RECT& rect, CWnd* pParentWnd, UINT nID );

CAnimateCtrl::Open

Page 4: Unit-IV

o Opens an AVI clip from a file or resource and displays the first frame. o Call this function to open an AVI clip and display its first frame.

Syntax

BOOL Open( LPCTSTR lpszFileName ); (or)

BOOL Open( UINT nID );

CAnimateCtrl::Play

Plays the AVI clip without sound. Call this function to play an AVI clip in an animation control

BOOL Play( UINT nFrom, UINT nTo, UINT nRep );

◦ nFrom Zero-based index of the frame where playing begins. Value must be less than

65,536. A value of 0 means begin with the first frame in the AVI clip.◦ nTo

Zero-based index of the frame where playing ends. Value must be less than 65,536. A value of – 1 means end with the last frame in the AVI clip.

◦ nRep Number of times to replay the AVI clip. A value of – 1 means replay the file

indefinitely.CAnimateCtrl::Stop

o Call this function to stop playing an AVI clip in an animation control.

BOOL Stop( );

o Nonzero if successful; otherwise zero.

CAnimateCtrl::IsPlaying

o Indicates whether an Audio-Video Interleaved (AVI) clip is playing

BOOL IsPlaying() const;

o true if an AVI clip is playing; otherwise, false.

o This method sends the ACM_ISPLAYING message, which is described in the Windows SDK.

CAnimateCtrl::Close

o Closes the AVI clip that was previously opened in the animation control (if any) and removes it from memory.

Page 5: Unit-IV

BOOL Close( );

o Nonzero if successful; otherwise zero.

CAnimateCtrl::Seek

o Call this function to statically display a single frame of your AVI clip.

BOOL Seek( UINT nTo );

◦ nTo Zero-based index of the frame to display. Value must be less than 65,536. A

value of 0 means display the first frame in the AVI clip. A value of –1 means display the last frame in the AVI clip.

Nonzero if successful; otherwise zero.

Animation Control Styles

ACS_AUTOPLAY - Starts playing the animation as soon as the AVI clip is opened.

ACS_CENTER - Centers the animation in the animation control's window

ACS_TIMER - By default, the control creates a thread to play the AVI clip. If you set this flag, the control plays the clip without creating a thread; internally the control uses a Win32 timer to synchronize playback. ACS_TRANSPARENT - Allows you to match an animation's background color to that of the underlying window, creating a "transparent" background. Use SetBkColor to set the background color for the device context to an appropriate value.

Q3. Discuss Image Lists and Bitmaps feature in vc++

Image lists can be used to store collections of bitmaps, making them useful when several bitmaps are needed, such as in tree view and list view controls.

What Is an Image List?

An image list is similar to an array of bitmaps, just like a roll of film is an array of images, as shown in Figure 17.1. Unlike rolls of film, an image list can grow, if needed, as extra images are added to the list. Each bitmap stored in an image list is associated with an index, which can be used to retrieve a particular image.

Page 6: Unit-IV

figure 17.1

An image list is like a roll of bitmap images.

In addition, image lists offer two features that are difficult to duplicate with regular bitmaps:

Transparent images Overlaid images

A transparent image is an image that allows the background to be seen through part of the image, as if part of the bitmap were transparent.

An overlaid image is created by combining two images to form a single, combined image.

How Is an Image List Used?

o The CImageList class is used to create, display, and otherwise manage image lists in an MFC-based Windows program.

o Image lists often are used to provide item images for the CListCtrl class and the CTreeCtrl class .

Creating an Image List

The first step in creating an image list is to create a series of bitmaps, each of which is the same size. Although the images can be any size, the sample code in this section assumes the bitmaps are 32 pixels on each side. The bitmaps used in the example are shown in Figure 17.2.

Page 7: Unit-IV

figure 17.2

The bitmaps used in the ImageList example are all the same size.

Create the three bitmaps, and name them as shown in Table 17.1.

Table 17.1. Bitmaps used in the ImageList project.

ID DescriptionIDB_CROSS Cross markIDB_CHECK Check markIDB_BANG Exclamation point

Storing a bitmap image in an image list consists of three steps:

1.Load the bitmap.2. Create a new image index in the image list that contains a copy of the bitmap.3. Delete the bitmap object.

The bitmap object is deleted because the image list makes a copy of the bitmap and stores the image internally. As a rule of thumb, any time a Windows GDI object is loaded, it should be deleted to prevent memory leaks. The preceding steps are handled by AddBitmapToImageList, a new function added to the CImageListView class. Add the function provided in Listing 17.1 to the ImageListView.cpp source file.

TYPE: Listing 17.1. The CImageListView::AddBitmapToImageList function.

BOOL CImageListView::AddBitmapToImageList( UINT nResourceID ){ BOOL bReturn; CBitmap bmp;

bReturn = bmp.LoadBitmap( nResourceID ); if( bReturn != FALSE ) { int nReturn = m_imageList.Add( &bmp, RGB(255,255,255) ); bmp.DeleteObject(); } return bReturn;

}

The AddBitmapToImageList function is used because three bitmap resources are added to the image list. Adding the bitmaps using a new member function reduces the amount of code you must write and helps reduce the chance of errors, because every bitmap is loaded using the same function.

The CImageList::Add member function is used to add an image to the image list. The version of Add used in Listing 17.1 takes two parameters:

Page 8: Unit-IV

The address of the CBitmap image to be copied into the image list A COLORREF value that represents the background color of the bitmap

After adding the member function to the ImageListView.cpp file, add the source code from Listing 17.2 to the CImageListView class, found in the file ImageListView.h. Add the source code in the class implementation section, which is marked by the // Implementation comment. After the comment, there is a protected: label inserted by AppWizard for user- supplied variables and functions.

TYPE: Listing 17.2. Source code to be added to the CImageListView class.protected: BOOL AddBitmapToImageList( UINT nResourceID );

CImageList m_imageList;

The actual work of creating the image list is done when the view is constructed. The image list can be built at any time; however, it is costly to create an image list in terms of computing power. Creating the image list in the constructor lets you build it once, rather than each time it is used. Add the source code from Listing 17.3 to the constructor for CImageViewList.

TYPE: Listing 17.3. The CImageListView constructor.

CImageListView::CImageListView(){ m_imageList.Create( 32, 32, TRUE, 3, 1 );

AddBitmapToImageList( IDB_CROSS ); AddBitmapToImageList( IDB_CHECK ); AddBitmapToImageList( IDB_BANG );

}

The image list is created using one of the CImageList::Create functions. This version of Create is useful when an image list is used as a bitmap collection; I use other versions of Create in the following chapters. This version of Create has five parameters:

The height of each bitmap; in this case, 32 pixels The width of each bitmap; in this case, 32 pixels Whether or not the image list is masked for transparency; in this case, TRUE The number of bitmaps stored initially in the image list; in this case, three The "grow-by," or the number of bitmaps added when the image list is expanded; in this case,

one

Displaying an Image List Using the CImageList::Draw Function

Individual items stored in an image list can be drawn using the CImageList::Draw member function, as shown in Listing 17.4.

Page 9: Unit-IV

TYPE: Listing 17.4. Using CImageList::Draw to display a bitmap from an image list.

void CImageListView::OnDraw(CDC* pDC){

CPoint ptImage( 0, 0 ); for( int nImage = 0; nImage < 3; nImage++ ) { m_imageList.Draw( pDC, nImage, ptImage, ILD_NORMAL ); ptImage.x += 50; }}

The Draw member function has four parameters:

The device context that represents the drawing surface The image list index of the image to be drawn The location of the image, represented by a CPoint object The type of drawing operation to be performed

Compile and run the ImageList project. Figure 17.3 shows the current version of the ImageList application running.

figure 17.3Using ILD_NORMAL to display the contents of the image list.

There are eight different types of drawing operations:

ILD_NORMAL draws the image directly onto the drawing surface. If the image is masked, the image will be drawn transparently if the background color for the image list is the default value of CLR_NONE.

ILD_TRANSPARENT draws the image transparently. If the image is not masked, the image is drawn normally.

ILD_MASK draws the image mask. If the image list doesn't have a mask, the image is drawn normally.

ILD_BLEND25 draws the image and blends it 25 percent with the system highlight color. If the image list doesn't have a mask, the image is drawn normally.

ILD_FOCUS is identical to ILD_BLEND25.

Page 10: Unit-IV

ILD_BLEND50 draws the image and blends it 50 percent with the system highlight color. If the image list doesn't have a mask, the image is drawn normally.

ILD_BLEND is identical to ILD_BLEND50. ILD_SELECTED is identical to ILD_BLEND50.

Figure 17.4 shows the image list items drawn using the ILD_MASK style. This allows you to see the image mask generated by the image list.

figure 17.4Image list items mask drawn using ILD_MASK.

The individual image bitmaps stored in an image list can also be extracted as icons using the ExtractIcon member function:

HICON hicon = m_imageList.ExtractIcon( nImage );

The only parameter needed for ExtractIcon is the image index. You can then use the icon extracted just like any icon handle. Icons were discussed in Section 14, "Icons and Cursors."

Q4 . What is MFC CRECT TRACKER Class with example.

CRECT TRACKER

o Allows an item to be displayed, moved, and resized in different fashions.

class CRect : public tagRECT

o CRectTracker does not have a base class.

o Although the CRectTracker class is designed to allow the user to interact with OLE items by using a graphical interface, its use is not restricted to OLE- enabled applications.

o It can be used anywhere such a user interface is required.

o CRectTracker borders can be solid or dotted lines. There are two important data membes

Page 11: Unit-IV

o m_rect member holds the device coordinates for the rectangle.o m-nStyle member determine the border, resize handle

Creates and initializes a CRectTracker object.

CRectTracker( ); (Or)CRectTracker

( LPCRECT lpSrcRect,UINT nStyle );

lpSrcRect

o The coordinates of the rectangle objecto The RECT structure defines the coordinates of the upper-left and lower-right corners of

a rectangle.

typedef struct tagRECT{  LONG left; LONG top;LONG right; LONG bottom; } RECT;

nStyle

Specifies the style of the CRectTracker object. The following styles are supported:

CRectTracker::solidLine   Use a solid line for the rectangle border.

CRectTracker::dottedLine   Use a dotted line for the rectangle border.

CRectTracker::hatchedBorder   Use a hatched pattern for the rectangle border.

CRectTracker::resizeInside   Resize handles located inside the rectangle.

CRectTracker::resizeOutside   Resize handles located outside the rectangle.

CRectTracker::hatchInside   Hatched pattern covers the entire rectangle.

Construction

CRectTracker Constructs a CRectTracker object.

Operations

DrawDraw the tracker, including border and resize handles, but does not draw anything inside the rectangle.

Page 12: Unit-IV

Void Draw(CDC* PDC) const;

HitTestReturn hit status( mouse button hits inside or on the tracker rectanle.

NormalizeHit Normalizes a hit-test code.

SetCursorSets the cursor, depending on its position over the rectangle. (WM_SETCURSOR handler)

Track Allows the user to manipulate the rectangle.

TrackRubber Band Allows the user to "rubber-band" the selection.

Alternate ways to intialize a RECT structure

RECT rctA; rctA.left = 20; rctA.top = 30; rctA.right = 180; rctA.bottom = 230;

RECT rctB = {20,30,180,230}

//Alternate ways to call a RECT structure

1. CRect( ) throw( ); 

2. CRect(  int l,  int t,  int r,  int b   ) throw( );

3. CRect(  const RECT& srcRect   ) throw( );

4. CRect(  LPCRECT lpSrcRect   ) throw( );

5. CRect(  POINT point,  SIZE size   ) throw( );

6. CRect(  POINT topLeft,  POINT bottomRight   ) throw( );

Q5. Discuss CTreeView Class feature in VC++

Simplifies use of the tree control and of CTreeCtrl, the class that encapsulates tree-control functionality, with MFC's document-view architecture.

A "tree view control" is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk.

Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it.

By clicking an item, the user can expand and collapse the associated list of subitems.

Page 13: Unit-IV

class CTreeView : public CCtrlView

Base Class Members

CObject Members CCmdTarget Members CWnd Members Construction

CTreeView Constructs a CTreeView object.Attributes

GetTreeCtrl Returns the tree control associated with the view.

Constructs a CTreeView object.

CTreeView( );

Construction

◦ Create Creates a tree view control and attaches it to a CTreeCtrl object.

◦ // Assuming your window has a CTreeCtrl member named m_TreeCtrl, ◦ // you can create the tree control window with a child ID of 0x1005 ◦ // using a call like this:

m_TreeCtrl->Create(WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_BORDER | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_HASLINES | TVS_DISABLEDRAGDROP, CRect(10, 10, 300, 100), this, 0x1005);

CreateEx Creates a tree control with the specified Windows extended styles and attaches it to a CTreeCtrl object.

CTreeCtrl Constructs a CTreeCtrl object.◦ GetBkColor Retrieves the current background color of the control.

◦ GetChildItem Retrieves the child of a specified tree view item.

◦ GetCount Retrieves the number of tree items associated with a tree view control.

◦ GetEditControl Retrieves the handle of the edit control used to edit the specified tree view item.

◦ GetFirstVisibleItem Retrieves the first visible item of the specified tree view item.

◦ GetImageList Retrieves the handle of the image list associated with a tree view control.

◦ GetIndent Retrieves the offset (in pixels) of a tree view item from its parent.

Page 14: Unit-IV

◦ GetInsertMarkColor Retrieves the color used to draw the insertion mark for the tree view.

◦ GetItem Retrieves the attributes of a specified tree view item.

◦ GetItemData Returns the 32-bit application-specific value associated with an item.◦ GetItemHeight Retrieves the current height of the tree view items.

◦ GetItemImage Retrieves the images associated with an item.

◦ GetItemRect Retrieves the bounding rectangle of a tree view item.

◦ GetItemState Returns the state of an item.

◦ GetItemText Returns the text of an item.

◦ GetLineColor Retrieves the current line color for the tree view control.

◦ GetNextItem Retrieves the next tree view item that matches a specified relationship.

◦ GetNextSiblingItem Retrieves the next sibling of the specified tree view ◦ item.

◦ GetNextVisibleItem Retrieves the next visible item of the specified tree view item.◦ GetParentItem Retrieves the parent of the specified tree view item.

◦ GetPrevSiblingItem Retrieves the previous sibling of the specified tree view item.

◦ GetPrevVisibleItem Retrieves the previous visible item of the specified tree view item.

◦ GetRootItem Retrieves the root of the specified tree view item.

◦ GetScrollTime Retrieves the maximum scroll time for the tree view control.

◦ GetSelectedItem Retrieves the currently selected tree view item.

◦ GetTextColor Retrieves the current text color of the control.

◦ GetToolTips Retrieves the handle to the child ToolTip control used by a tree view control.

◦ GetVisibleCount Retrieves the number of visible tree items associated with a tree view control.

◦ ItemHasChildren Returns nonzero if the specified item has child items.

◦ SetBkColor Sets the background color of the control.

◦ SetCheck Sets the check state of a tree control item.

Page 15: Unit-IV

◦ SetImageList Sets the handle of the image list associated with a tree view control.◦ SetItem Sets the attributes of a specified tree view item.

◦ SetItemData Sets the 32-bit application-specific value associated with an item.

◦ SetItemHeight Sets the height of the tree view items.

◦ SetItemImage Associates images with an item.

◦ SetItemState Sets the state of an item.

◦ SetItemText Sets the text of an item.

◦ SetLineColor Sets the current line color for the tree view control.

◦ SetScrollTime Sets the maximum scroll time for the tree view control.

◦ SetTextColor Sets the text color of the control.

◦ SetToolTips Sets a tree view control's child ToolTip control. Operations

◦ CreateDragImage Creates a dragging bitmap for the specified tree view item.

◦ DeleteAllItems Deletes all items in a tree view control.

◦ DeleteItem Deletes a new item in a tree view control.

Q6. Disucuss the Tab Control Feature in VC++

CTabCtrl Class  

Provides the functionality of the Windows common tab control.

class CTabCtrl : public CWnd

A "tab control" is analogous to the dividers in a notebook or the labels in a file cabinet.

By using a tab control, an application can define multiple pages for the same area of a window or dialog box.

Each page consists of a set of information or a group of controls that the application displays when the user selects the corresponding tab.

A special type of tab control displays tabs that look like buttons.

Page 16: Unit-IV

Creating the Tab Control 

How the tab control is created depends on whether the control is placed in a 1. dialog box or

creating it in a 2. nondialog window.

1. To use CTabCtrl directly in a dialog box

In the dialog editor, add a Tab Control to the dialog template resource. Specify its control ID.

Use the Add Member Variable Wizard to add a member variable of type CTabCtrl with the Control

property. Use this member to call CTabCtrl member functions.

Map handler functions in the dialog class for any tab control notification messages that needs to be

handled.

In OnInitDialog, set the styles for the CTabCtrl.

2. To use CTabCtrl in a nondialog window

1. Define the control in the view or window class.

2. Call the control's Create member function,

possibly in OnInitialUpdate, possibly as early as the parent window's OnCreate handler

function.

Set the styles for the control.

After the CTabCtrl object has been created, set or clear the following extended styles:

TCS_EX_FLATSEPARATORS  

 The tab control will draw separators between the tab items.

This extended style only affects tab controls that have the TCS_BUTTONS and

TCS_FLATBUTTONS styles.

By default, creating the tab control with the TCS_FLATBUTTONS style sets this

extended style.

TCS_EX_REGISTERDROP   The tab control generates TCN_GETOBJECT

notification messages to request a drop target object when an object is dragged over the

tab items in the control.

Note: To receive the TCN_GETOBJECT notification, it must initialize the OLE libraries with a call

to AfxOleInit

These styles can be retrieved and set, after the control has been created, with respective calls to the

GetExtendedStyle and SetExtendedStyle member functions.

For instance, set the TCS_EX_FLATSEPARATORS style with the following lines of code:

DWORD dwExStyle= m_tabCtrl.GetExtendedStyle();

Page 17: Unit-IV

m_tabCtrl.SetExtendedStyle(dwExStyle | TCS_EX_FLATSEPARATORS);

Clear the TCS_EX_FLATSEPARATORS style from a CTabCtrl object with the following lines

of code:

DWORD dwExStyle= m_tabCtrl.GetExtendedStyle();

m_tabCtrl.SetExtendedStyle(dwExStyle & ~TCS_EX_FLATSEPARATORS);

Base Class Members

Construction

Create Creates a tab control and attaches it to an instance of a CTabCtrl object.

CreateEx Creates a tab control with the specified Windows extended styles and attaches it to an

instance of a CTabCtrl object.

CTabCtrl Constructs a CTabCtrl object.

Attributes

GetCurFocus Retrieves the tab with the current focus of a tab control.

GetCurSel Determines the currently selected tab in a tab control.

GetExtendedStyle Retrieves the extended styles that are currently in use for the

tab control.

GetImageList Retrieves the image list associated with a tab control.

GetItem Retrieves information about a tab in a tab control.

GetItemCount Retrieves the number of tabs in the tab control.

GetItemRect Retrieves the bounding rectangle for a tab in a tab control.

GetItemState Retrieves the state of the indicated tab control item.

GetRowCount Retrieves the current number of rows of tabs in a tab control.

GetToolTips Retrieves the handle of the tool tip control associated with a tab

control.

SetCurFocus Sets the focus to a specified tab in a tab control.

SetCurSel Selects a tab in a tab control.

SetExtendedStyle Sets the extended styles for a tab control.

SetImageList Assigns an image list to a tab control.

SetItem Sets some or all of a tab's attributes.

SetItemExtra Sets the number of bytes per tab reserved for application-

defined data in a tab control.

SetItemSize Sets the width and height of an item.

Page 18: Unit-IV

SetItemState Sets the state of the indicated tab control item.

SetMinTabWidth Sets the minimum width of items in a tab control.

SetPadding Sets the amount of space (padding) around each tab's icon and

label in a tab control.

SetToolTips Assigns a tool tip control to a tab control.

Operations

AdjustRect Calculates a tab control's display area given a window rectangle, or calculates the

window rectangle that would correspond to a given display area.

DeleteAllItems Removes all items from a tab control.

DeleteItem Removes an item from a tab control.

DeselectAll Resets items in a tab control, clearing any that were pressed.

HighlightItem Sets the highlight state of a tab item.

HitTest Determines which tab, if any, is at a specified screen position.

InsertItem Inserts a new tab in a tab control.

RemoveImage Removes an image from a tab control's image list.

Overridables

DrawItem Draws a specified item of a tab control.

CREATING THE DERIVED CLASS FOR CTABCTRL:

Open the class wizard by pressing the key combination Ctrl + W.

Click on the Add Class --> New button.

Enter the name of the derived class (of CTabCtrl ) in the empty text box let it be

MyTabCtrl

Select the CTabCtrl as the Base Class.

o Two Files will be created as MyTabCtrl.h and MyTabCtrl.cpp.

Add the following data and function members to the MyTabCtrl class, in the MyTabCtrl.h file.

//Array to hold the list of dialog boxes/tab pages for CTabCtrl

int m_DialogID[2];

//CDialog Array Variable to hold the dialogs 

CDialog *m_Dialog[2];

//Function to Create the dialog boxes during startup

Page 19: Unit-IV

void InitDialogs();

//Function to activate the tab dialog boxes

void ActivateTabDialogs();

Open the class wizard for MyTabCtrl and add a handler for TCN_SELCHANGE event (of CTabCtrl).

This can be done through the Class Wizard --> Message Maps tab.

Open the MyTabCtrl.cpp file and paste the following functions except ActivateTabDialogs() and InitDialogs()

include the Child dialog header files in this MyTabCtrl.cpp.

//Constructor for the class derived from CTabCtrlMyTabCtrl::MyTabCtrl(){   m_DialogID[0] =IDD_DIALOG1;   m_DialogID[1] =IDD_DIALOG2;

   m_Dialog[0] = new MyDlg1();   m_Dialog[1] = new MyDlg2();

   m_nPageCount = 2;

}//This function creates the Dialog boxes oncevoid MyTabCtrl::InitDialogs(){m_Dialog[0]->Create(m_DialogID[0],GetParent());m_Dialog[1]->Create(m_DialogID[1],GetParent());}

//Selection change event for the class derived from CTabCtrlvoid MyTabCtrl::OnSelchange(NMHDR* pNMHDR, LRESULT* pResult) {   // TODO: Add your control notification handler code here   ActivateTabDialogs();   *pResult = 0;}

void MyTabCtrl::ActivateTabDialogs(){  int nSel = GetCurSel();  if(m_Dialog[nSel]->m_hWnd)     m_Dialog[nSel]->ShowWindow(SW_HIDE);

  CRect l_rectClient;  CRect l_rectWnd;

  GetClientRect(l_rectClient);  AdjustRect(FALSE,l_rectClient);  GetWindowRect(l_rectWnd);

Page 20: Unit-IV

  GetParent()->ScreenToClient(l_rectWnd);  l_rectClient.OffsetRect(l_rectWnd.left,l_rectWnd.top); for(int nCount=0; nCount < m_nPageCount; nCount++){m_Dialog[nCount]->SetWindowPos(&wndTop, l_rectClient.left, l_rectClient.top, l_rectClient.Width(), l_rectClient.Height(), SWP_HIDEWINDOW);} m_Dialog[nSel]->SetWindowPos(&wndTop, l_rectClient.left, l_rectClient.top, l_rectClient.Width(), l_rectClient.Height(), SWP_SHOWWINDOW);

  m_Dialog[nSel]->ShowWindow(SW_SHOW);

}Now the above can be enough for a basic tab control with CTabCtrl, which can be made to hold 2

dialog boxes or tab sheets.

The next step will be to create two dialog boxes which will be used as the Tab sheets.

Creating the Tab Sheets for CTabCtrl:

Create two Dialog boxes by using the Visual Studio --> Menu --> Insert Resource --> Dialog.

Ensure that their ids are IDD_DIALOG1, IDD_DIALOG2.

Put some controls or some sample text on the dialog boxes for differentiating both of them from

each other.

For both the dialogs, set the Properties Dialog --> Styles --> Style equal to Child.

Also Un-check the Properties Dialog --> Styles --> Title bar and System Menu. They should be set

to false. Because the tab sheets cannot have a title bar.

Set the Properties Dialog --> More Styles --> Visible style to True.

For both the dialogs create two dialog classes by using the class wizard.

Initializing and Activating the Tab Sheets in CTabCtrl:

Open the Parent dialog which holds the Tab Control.

Open the class wizard.

In the Class wizard --> Member Variables tab, add a variable for the Tab control. Use the

MyTabCtrl as the class representing the Tab Control, instead of CTabCtrl.

This sample uses the variable name as m_tbCtrl.

After this, in the OnInitDialog of the MyTabCtrl class, add the following lines of code.

      m_tbCtrl.InitDialogs();

m_tbCtrl.InsertItem(0,"Sample Tab 1");

m_tbCtrl.InsertItem(1,"Sample Tab 2");

m_tbCtrl.ActivateTabDialogs();

Now the application is ready to be launched.

Page 21: Unit-IV

Build the application and execute it.

The application will have 2 tab sheets and upon clicking the tab buttons, the dialogs get activated

correspondingly.

Q7. Discuss Progress Control Class and its member functions with details.

o Provides the functionality of the Windows common progress bar control

o A progress bar control is a window that an application can use to indicate the progress of a lengthy operation.

o It consists of a rectangle that is gradually filled, from left to right, with the system highlight color as an operation progresses

◦ A progress bar control has a range and a current position.

◦ Range represents the total duration of the operation, and

◦ Current Position represents the progress the application has made toward completing the operation.

Using CProgressCtrl

◦ The progress control is represented in MFC by class CProgressCtrl.◦ When the progress control is created (CProgressCtrl::Create), specify its size and

position, ◦ Constructs a CProgressCtrl object.

CProgressCtrl( );

◦ After constructing the CProgressCtrl object, call ProgressCtrl::Create to create the progress bar control.

◦1. // Create a progress control object on the stack.

CProgressCtrl myCtrl; // Create a progress control object on the heap. CProgressCtrl* pmyCtrl = new CProgressCtrl;

2.CProgressCtrl myCtrl; // Create a smooth child progress control. myCtrl.Create(WS_CHILD|WS_VISIBLE|PBS_SMOOTH, CRect(10,10,200,30), pParentWnd, 1)

Construction◦ CProgressCtrl Constructs a CProgressCtrl object.

Page 22: Unit-IV

◦ Create Creates a progress bar control and attaches it to a CProgressCtrl object.◦ CreateEx Creates a progress control with the specified Windows extended styles and

attaches it to a CProgressCtrl object.Attributes

◦ GetPos Gets the current position of the progress bar.◦ GetRange Gets the lower and upper limits of the range of the progress bar control.◦ OffsetPos Advances the current position of a progress bar control by a specified

increment and redraws the bar to reflect the new position.◦ SetBkColor Sets the background color for the progress bar.◦ SetPos Sets the current position for a progress bar control and redraws the bar to reflect

the new position.◦ SetRange Sets the minimum and maximum ranges for a progress bar control and

redraws the bar to reflect the new ranges.

◦ SetRange32 Sets the minimum and maximum ranges for a progress bar control and redraws the bar to reflect the new ranges.

◦ SetStep Specifies the step increment for a progress bar control.

Operations

◦ StepIt Advances the current position for a progress bar control by the step increment (see SetStep) and redraws the bar to reflect the new position

CProgressCtrl::Create

Creates a progress bar control and attaches it to a CProgressCtrl object

virtual BOOL Create( DWORD dwStyle, const RECT& rect,CWnd* pParentWnd, UINT nID );

◦ PBS_VERTICAL   Displays progress information vertically, top to bottom. Without this flag, the progress bar control displays horizontally, left to right.

◦ PBS_SMOOTH   Displays gradual, smooth filling in the progress bar control. Without this flag, the control will fill with blocks.

CProgressCtrl::CreateEx  

dwExStyle Specifies the extended style of the control being created.

Retrieves the current position of the progress bar. int GetPos( );

Example

Page 23: Unit-IV

CProgressCtrl myCtrl; // Create a child progress control. myCtrl.Create(WS_CHILD|WS_VISIBLE, CRect(10,10,200,30), pParentWnd, 1); // Set the new position to half of the current position.

myCtrl.SetPos( myCtrl.GetPos()/2 );

CProgressCtrl::GetRange

Gets the current lower and upper limits, or range, of the progress bar control.

void GetRange(  int& nLower,   int& nUpper   );

CProgressCtrl::OffsetPos 

int OffsetPos( int nPos );

◦ nPos Amount to advance the position.

CProgressCtrl::SetBkColor

Sets the background color for the progress bar.

COLORREF SetBkColor( COLORREF clrNew );

◦ clrNew

A COLORREF value that specifies the new background color. Specify the CLR_DEFAULT value to use the default background color for the progress bar.

CProgressCtrl::SetPos 

Sets the progress bar control's current position as specified by nPos and redraws the bar to reflect the new position.

int SetPos( int nPos );

◦ nPos New position of the progress bar control.

CProgressCtrl::SetRange

Sets the upper and lower limits of the progress bar control's range and redraws the bar to reflect the new ranges.

void SetRange( short nLower, short nUpper ); void SetRange32( int nLower, int nUpper );◦ nLower

Specifies the lower limit of the range (default is zero).◦ nUpper

Page 24: Unit-IV

Specifies the upper limit of the range (default is 100).

CProgressCtrl::SetStep

Specifies the step increment for a progress bar control.

int SetStep( int nStep ); ◦ nStep

New step increment

Operations

CProgressCtrl::StepIt

Advances the current position for a progress bar control by the step increment and redraws the bar to reflect the new position.

int StepIt( );

The previous position of the progress bar control.

CProgressCtrl - Code Example

BOOL CDlgProgress1Dlg::OnInitDialog() { CDialog::OnInitDialog(); SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE);

// Set small icon // TODO: Add extra initialization here CProgressCtrl *Progress = new CProgressCtrl; Progress->Create(WS_CHILD | WS_VISIBLE, CRect(10, 10, 288, 35), this,0x16); Progress->SetRange(1, 100); Progress->SetPos(38); return TRUE; // return TRUE unless you set the focus to a control }

Q8. Discuss CSliderCtrl control classes and its member functions with example

A slider is Window control equipped with a small bar, also called a thumb, that slides along a visible line.

There are two types of Sliders:

1. Horizontal2. Vertical

Page 25: Unit-IV

◦ The CSliderCtrl class represents a slider control, which is also called a trackbar.

◦ A "slider control" is a window that contains a slider and optional tick marks.

◦ When the user moves the slider, using either the mouse or the arrow keys, the slider control sends notification messages to indicate the change.

◦ Slider controls are useful when you want the user

◦ To provide a slider to an application, from the Controls toolbox, click the Slider button and click the desired area on the dialog box or the form.

◦ To programmatically create a slider, declare a pointer to CSliderCtrl using the new operator. To initialize the control, call its Create() method. Here is an example:

BOOL CDlgSlide::OnInitDialog() 

{

CDialog::OnInitDialog();

CSliderCtrl *TrackBar = new CSliderCtrl;

TrackBar->Create(WS_CHILD | WS_VISIBLE, CRect(15, 20, 222, 50), this, 0x14);

return TRUE; // return TRUE unless you set the focus to a control

Page 26: Unit-IV

}

◦ As the user interacts with the control, it will send various notification messages. You can extract the slider value from the control by calling the GetPos member function.

◦ When you're done with the control, you need to make sure it's properly destroyed. If the slider control is in a dialog box, it and the CSliderCtrl object will be destroyed automatically. If not, you need to ensure that both the control and the CSliderCtrl object are properly destroyed.

CSliderCtrl - Styles

◦ The TBS_HORZ and TBS_VERT styles determine the orientation of the slider control. If you do not specify an orientation, the slider control is oriented horizontally.

◦ The TBS_AUTOTICKS style creates a slider control that has a tick mark for each increment in its range of values.

◦ . To create a slider control that does not display tick marks, you can use the TBS_NOTICKS style.

◦ For horizontal slider controls, you can specify the TBS_BOTTOM or TBS_TOP style. For vertical slider controls, you can specify the TBS_RIGHT or TBS_LEFT style. (TBS_BOTTOM and TBS_RIGHT are the default settings.) For tick marks on both sides of the slider control in any orientation, specify the TBS_BOTH style

◦ A slider control can display a selection range only if you specify the TBS_ENABLESELRANGE style when you create it. When a slider control has this style, the tick marks at the starting and ending positions of a selection range are displayed as triangles (instead of vertical dashes) and the selection range is highlighted

. ◦ By default, the length of a slider control's slider varies as the selection range changes. If the

slider control has the TBS_FIXEDLENGTH style, the length of the slider remains the same even if the selection range changes.

◦ A slider control that has the TBS_NOTHUMB style does not include a slider.

Q9. Creating and Inheriting CTreeView using Tree Control in VC++.

Tree view controls can also be used in a view. The CTreeView class is a specialized view that consists of a single tree control. The CTreeView class is derived from CCtrlView, which is itself derived from CView.

Using a Tree View Control as a View

Page 27: Unit-IV

For this example, create an SDI project named TreeEx using AppWizard. In AppWizard step six, a checkered flag is displayed along with a list box containing classes that are generated for the application. Follow these steps to use a tree view as the application's main view:

1. Select the view class in the class list box, in this case CTreeExView.

2. Select CTreeView from the Base Class combo box.

3. Click the Finish button to end the AppWizard process and display the New Project Information dialog box.

4. Click OK to generate the code for the TreeEx project.

You can compile and run the TreeEx application; however, no items have been added to the tree control yet. In the next section, you see how items are added to a tree view.

Adding Items to a CTreeView

As discussed earlier, the CTreeView class is derived from CView and contains a tree view control that covers the entire view surface. To get access to the tree view control, you use the GetTreeControl function.

CTreeCtrl& tree = GetTreeCtrl();

Note that the return value from GetTreeCtrl is a reference to a CTreeCtrl object. This means that the return value must be assigned, or bound, to a CTreeCtrl reference variable.

After you have access to the tree view control, items can be added to the control in several different ways. The simplest methods are used when adding simple text items without bitmap images to the tree view control. When adding simple items to a tree control, only the label for the item must be provided:

HTREEITEM hItem = tree.InsertItem( "Foo" );

This line adds an item to the tree control at the first, or root, level. The return value from InsertItem is a handle to the new item if it was inserted successfully or NULL if the item could not be inserted.

To add an item as a child, pass the parent's handle as a parameter when inserting the item.

tree.InsertItem( "Bar", hItem );

The source code provided in Listing 1uses the functions discussed previously to add eight items in the CTreeExView::OnInitialUpdate function.

TYPE: Listing 1. Adding items to a CTreeView.

void CTreeExView::OnInitialUpdate(){ CTreeView::OnInitialUpdate();

Page 28: Unit-IV

CTreeCtrl& tree = GetTreeCtrl();

HTREEITEM hChapter = tree.InsertItem( "Chapter 1" ); tree.InsertItem( "What", hChapter); tree.InsertItem( "Why", hChapter ); tree.InsertItem( "How", hChapter ); hChapter = tree.InsertItem( "Chapter 2" ); tree.InsertItem( "What", hChapter ); tree.InsertItem( "Why", hChapter ); tree.InsertItem( "How", hChapter );

}

This version of the tree view control is a minimal tree control, as shown in Figure 1. There are no connecting lines, no bitmaps, and no pushbuttons; in short, it's fairly simple.

figure 19.1

The main view of the TreeEx example.

Applying Styles to a Tree View Control

In addition to other available view and window styles, you can apply four style options specifically to a tree view control:

TVS_HASLINES adds connecting lines between parent and child items. TVS_LINESATROOT adds lines for the root items in the tree control. This attribute is ignored

if TVS_HASLINES is not selected. TVS_HASBUTTONS adds the plus and minus buttons for items that can be expanded.

TVS_EDITLABELS enables the user to edit a tree view item label.

The source code in Listing 2 applies all the optional attributes except for TVS_EDITLABELS.

Page 29: Unit-IV

TYPE: Listing 2. Modifying the tree view style in PreCreateWindow..

BOOL CTreeExView::PreCreateWindow(CREATESTRUCT& cs){

cs.style |= ( TVS_HASLINES|TVS_LINESATROOT|TVS_HASBUTTONS ); return CTreeView::PreCreateWindow(cs);

}

Compile and run the TreeEx example, and you'll see that the example now has lines and buttons, as shown in Figure 2. It might sound like a small addition, but it makes the control much easier to use, especially if the tree must be expanded and collapsed frequently.

Figure 2

The TreeEx application after modifying the Tree View styles

Q10. Discuss the feature o RichEditView Class.

Provides the functionality of the rich edit control.

class CRichEditCtrl : public CWnd

A "rich edit control" is a window in which the user can enter and edit text.

Page 30: Unit-IV

The text can be assigned character and paragraph formatting, and can include embedded OLE

objects.

Rich edit controls provide a programming interface for formatting text.

However, an application must implement any user interface components necessary to make

formatting operations available to the user.

Using CRichEditCtrl

A rich edit control is a window in which the user can enter and edit text.

The text can be assigned character and paragraph formatting, and can include embedded OLE

objects.

The rich edit control is represented in MFC by the CRichEditCtrl class.

Overview of the Rich Edit Control

Rich edit controls (CRichEditCtrl) provide a programming interface for formatting text.

However, an application must implement any user interface components necessary to make

formatting operations available to the user.

That is, the rich edit control supports changing the character or paragraph attributes of the selected

text.

Some examples of character attributes are bold, italics, font family, and point size.

Examples of paragraph attributes include alignment, margins, and tab stops. However, it is up to

you to provide the user interface, whether that is toolbar buttons, menu items, or a format

character dialog box.

There are also functions to query the rich edit control for the attributes of the current selection.

Use these functions to display the current settings for the attributes, for example, setting a check

mark on the command UI if the selection has the bold character formatting attribute.

Rich edit controls support almost all of the operations and notification messages used with

multiline edit controls.

Thus, applications that already use edit controls can be easily changed to use rich edit controls.

Additional messages and notifications enable applications to access the functionality unique to rich

edit controls.

Classes Related to Rich Edit Controls

The CRichEditView, CRichEditDoc, and CRichEditCntrItem classes provide the

functionality of the rich edit control (CRichEditCtrl) within the context of MFC's

document/view architecture.

CRichEditView maintains the text and formatting characteristic of text.

Page 31: Unit-IV

CRichEditDoc maintains the list of OLE client items that are in the view.

CRichEditCntrItem provides container-side access to the OLE client item.

To modify the contents of a CRichEditView, use CRichEditView::GetRichEditCtrl to access

the underlying rich edit control.

Rich Edit Control Examples

The MFC OLE sample WORDPAD uses the CRichEditView, CRichEditDoc, and

CRichEditCntrItem classes.

By extension, it uses the CRichEditCtrl.

Character Formatting in Rich Edit Controls

You can use member functions of the rich edit control (CRichEditCtrl) to format characters and to

retrieve formatting information.

For characters, you can specify typeface, size, color, and effects such as bold, italic, and protected.

You can apply character formatting by using the SetSelectionCharFormat and

SetWordCharFormat member functions.

To determine the current character formatting for the selected text, use the

GetSelectionCharFormat member function.

The CHARFORMAT structure is used with these member functions to specify character attributes.

One of the important members of CHARFORMAT is dwMask.

In SetSelectionCharFormat and SetWordCharFormat, dwMask specifies which character

attributes will be set by this function call.

GetSelectionCharFormat reports the attributes of the first character in the selection;

dwMask specifies the attributes that are consistent throughout the selection.

You can also get and set the "default character formatting," which is the formatting applied to any

subsequently inserted characters.

For example, if an application sets the default character formatting to bold and the user then types a

character, that character is bold.

To get and set default character formatting, use the GetDefaultCharFormat and

SetDefaultCharFormat member functions.

The "protected" character attribute does not change the appearance of text.

If the user attempts to modify protected text, a rich edit control sends its parent window an

EN_PROTECTED notification message, allowing the parent window to allow or prevent the

change.

Page 32: Unit-IV

To receive this notification message, you must enable it by using the SetEventMask member

function.

Foreground color is a character attribute, but background color is a property of the rich edit

control. To set the background color, use the SetBackgroundColor member function.

Paragraph Formatting in Rich Edit Controls

You can use member functions of the rich edit control (CRichEditCtrl) to format paragraphs

and to retrieve formatting information.

Paragraph formatting attributes include alignment, tabs, indents, and numbering.

you can apply paragraph formatting by using the SetParaFormat member function.

To determine the current paragraph formatting for the selected text, use the GetParaFormat

member function.

The PARAFORMAT structure is used with these member functions to specify paragraph

attributes.

One of the important members of PARAFORMAT is dwMask. In SetParaFormat, dwMask

specifies which paragraph attributes will be set by this function call.

GetParaFormat reports the attributes of the first paragraph in the selection; dwMask

specifies the attributes that are consistent throughout the selection.

Current Selection in a Rich Edit Control

o The user can select text in a rich edit control (CRichEditCtrl) by using the mouse or the

keyboard.

o The current selection is the range of selected characters, or the position of the insertion

point if no characters are selected.

o An application can get information about the current selection, set the current selection,

determine when the current selection changes, and show or hide the selection highlight.

o To determine the current selection in a rich edit control, use the GetSel member

function.

o To set the current selection, use the SetSel member function.

o The CHARRANGE structure is used with these functions to specify a range of

characters.

o To retrieve information about the contents of the current selection, you can use the

GetSelectionType member function.

o By default, a rich edit control shows and hides the selection highlight when it gains and

loses the focus.

Page 33: Unit-IV

o You can show or hide the selection highlight at any time by using the HideSelection

member function.

o For example, an application might provide a Search dialog box to find text in a rich edit

control.

o The application might select matching text without closing the dialog box, in which

case it must use HideSelection to highlight the selection.

o To get the selected text in a rich edit control, use the GetSelText member function.

o The text is copied to the specified character array. You must ensure that the array is

large enough to hold the selected text plus a terminating null character.

o You can search for a string in a rich edit control by using the FindText member function

The FINDTEXTEX structure used with this function specifies the text range to search

and the string to search for.

o You can also specify such options as whether the search is case-sensitive.

Word Breaks in Rich Edit Controls

o A rich edit control (CRichEditCtrl) calls a function called a "word break procedure" to find

breaks between words and to determine where it can break lines.

o The control uses this information when performing word-wrap operations and when processing

the CTRL+LEFT and CTRL+RIGHT key combinations.

o An application can send messages to a rich edit control to replace the default word-break

procedure, to retrieve word-break information, and to determine what line a given character

falls on.

Clipboard Operations in Rich Edit Controls

o Your application can paste the contents of the Clipboard into a rich edit control (CRichEditCtrl)

using either the best available Clipboard format or a specific Clipboard format.

o You can also determine whether a rich edit control is capable of pasting a Clipboard format.

o You can copy or cut the contents of the current selection by using the Copy or Cut member

function.

o Similarly, you can paste the contents of the Clipboard into a rich edit control by using the Paste

member function.

o The control pastes the first available format that it recognizes, which presumably is the most

descriptive format.

Page 34: Unit-IV

o To paste a specific Clipboard format, you can use the PasteSpecial member function. This

function is useful for applications with a Paste Special command that enables the user to select

the Clipboard format.

o You can use the CanPaste member function to determine whether a given format is recognized

by the control.

o You can also use CanPaste to determine whether any available Clipboard format is recognized

by a rich edit control.

o This function is useful in the OnInitMenuPopup handler. An application might enable or gray

its Paste command depending on whether the control can paste any available format.

o Rich edit controls register two Clipboard formats: rich-text format and a format called RichEdit

Text and Objects.

o An application can register these formats by using the RegisterClipboardFormat function,

specifying the CF_RTF and CF_RETEXTOBJ values.

Stream Operations in Rich Edit Controls

o You can use streams to transfer data into or out of a rich edit control (CRichEditCtrl).

o A stream is defined by an EDITSTREAM structure, which specifies a buffer and an

application-defined callback function.

o To read data into a rich edit control (that is, stream the data in), use the StreamIn member

function.

o The control repeatedly calls the application-defined callback function, which transfers a portion

of the data into the buffer each time.

o To save the contents of a rich edit control (that is, stream the data out), you can use the

StreamOut member function.

o The control repeatedly writes to the buffer and then calls the application-defined callback

function. For each call, the callback function saves the contents of the buffer.

Printing in Rich Edit Controls

o You can tell a rich edit control (CRichEditCtrl) to render its output for a specified device, such

as a printer.

o You can also specify the output device for which a rich edit control formats its text.

o To format part of the contents of a rich edit control for a specific device, you can use the

FormatRange member function.

o The FORMATRANGE structure used with this function specifies the range of text to format as

well as the device context (DC) for the target device.

Page 35: Unit-IV

o After formatting text for an output device, you can send the output to the device by using the

DisplayBand member function.

o By repeatedly using FormatRange and DisplayBand, an application that prints the contents of

a rich edit control can implement banding. (Banding is division of output into smaller parts for

printing purposes.)

o You can use the SetTargetDevice member function to specify the target device for which a rich

edit control formats its text.

o This function is useful for WYSIWYG (what you see is what you get) formatting, in which an

application positions text using the default printer's font metrics instead of the screen's.

Bottomless Rich Edit Controls

o Your application can resize a rich edit control (CRichEditCtrl) as needed so that it is always the

same size as its contents. A rich edit control supports this so-called "bottomless" functionality

by sending its parent window an EN_REQUESTRESIZE notification message whenever the

size of its contents changes.

o When processing the EN_REQUESTRESIZE notification message, an application should

resize the control to the dimensions in the specified REQRESIZE structure.

o An application might also move any information near the control to accommodate the control's

change in height.

o To resize the control, you can use the CWnd function SetWindowPos.

o You can force a bottomless rich edit control to send an EN_REQUESTRESIZE notification

message by using the RequestResize member function.

o This message can be useful in the OnSize handler.

o To receive EN_REQUESTRESIZE notification messages, you must enable the notification

by using the SetEventMask member function.

Notifications from a Rich Edit Control

o Notification messages report events affecting a rich edit control (CRichEditCtrl). They can be

processed by the parent window or, using message reflection, by the rich edit control itself.

o Rich edit controls support all of the notification messages used with edit controls as well as

several additional ones.

o You can determine which notification messages a rich edit control sends its parent window by

setting its "event mask."

To set the event mask for a rich edit control, use the SetEventMask member function. You can retrieve

the current event mask for a rich edit control by using the GetEventMask member function.

Page 36: Unit-IV

The following paragraphs list several specific notifications and their uses:

EN_MSGFILTER   Handling the EN_MSGFILTER notification lets a class, either the rich edit

control or its parent window, filter all keyboard and mouse input to the control. The handler can

prevent the keyboard or mouse message from being processed or can change the message by

modifying the specified MSGFILTER structure.

EN_PROTECTED   Handle the EN_PROTECTED notification message to detect when the user

attempts to modify protected text. To mark a range of text as protected, you can set the

protected character effect. For more information, see Character Formatting in Rich Edit

Controls.

EN_DROPFILES   You can enable the user to drop files in a rich edit control by processing the

EN_DROPFILES notification message. The specified ENDROPFILES structure contains

information about the files being dropped.

EN_SELCHANGE   An application can detect when the current selection changes by processing

the EN_SELCHANGE notification message. The notification message specifies a

SELCHANGE structure containing information about the new selection.

Q11. What is Dialog? Explain Modal and Modaless Dialogs with example.

Dialog: A window which receives messages can be moved, closed, can even accept drawing instructions in its client area. It is always a windows resource. Class wizard generates a class derived from CDialog.Modal Dialog:

The user cannot work elsewhere in the same application (more correctly, in the same user interface thread) until the dialog is closed. Example: Open File dialogModeless Dialog:

The user can work in another window in the application while the dialog remains on the screen

Example: Microsoft Word's Find and Replace dialog is a good example of a modeless dialog; you can edit your document while the dialog is open. Controls:

A dialog contains a number of elements called controls. Dialog controls include edit controls, buttons, list boxes, combo boxes, static text, tree views, progress indicators, sliders, and so forth.

MFC provides 2 mechanisms for programming controls and Dialog box:

1) Data Validation - Validating the data inputted by the user2) Data Exchange – Transfer data between the ctrl in the dialog box & data

member of the dialog.

Page 37: Unit-IV

Modal Dialog

Modal dialogs are the most frequently used dialogs. A user action (a menu choice, for example) brings up a dialog on the screen, the user enters data in the dialog, and then the user closes the dialog.

1. Use the dialog editor to create a dialog resource that contains various controls. The dialog editor updates the project's resource script (RC) file to include your new dialog resource, and it updates the project's resource.h file with corresponding #define constants.

2. Use ClassWizard to create a dialog class (Dialog Class Name is MyDialog) that is derived from CDialog and attached to the resource created in step 1. ClassWizard adds the associated code and header file to the Microsoft Visual C++ project.

When ClassWizard generates your derived dialog class, it generates a constructor that invokes a CDialog modal constructor, which takes a resource ID as a parameter.

In the CPP file, the constructor implementation looks like this: CMyDialog::CMyDialog(CWnd* pParent /*=NULL*/) : CDialog(CMyDialog::IDD, pParent){ // initialization code here }

3. Use Class Wizard to add data members, exchange functions, and validation functions to the dialog class.

4. Use Class Wizard to add message handlers for the dialog's buttons and other event-generating controls.

5. Write the code for special control initialization (in OnInitDialog) and for the message handlers. Be sure the CDialog virtual member function OnOK is called when the user closes the dialog (unless the user cancels the dialog). (Note: OnOK is called by default.)

6. Write the code in your view class to activate the dialog. This code consists of a call to your dialog class's constructor followed by a call to the DoModal dialog class member function. DoModal returns only when the user exits the dialog window.

CMydialog d; d.DoModal(); // creates modal dialog box

Example Program for Modal Dialog (to calculate x power y ):

Steps1) Create a new VC++ application using AppWizard where the project

type : MFC AppWizard(exe) ProjectName: Sample In Wizard Step1 : SDI application , select finish button

Page 38: Unit-IV

2) Insert dialog resource by selecting Insert menu -> Resource option select the dialog resource & design Your dialog box with a required controls

3) Create dialog class by using class wizard (dialog class name: mydialog)

4) Define member variables (for 2 textboxes) & message handlers for Compute and clear by using class wizard

Control id Member variable Data typeIDC_EDIT1 m_x doubleIDC_EDIT2 m_y DoubleIDC_EDIT 3 m_res Double

5) Add the Message handler for compute and clear, include math.h in mydialog.h

void mydialog::OnCompute() { UpdateData(TRUE); // transfer data from control to variable

m_res=pow(m_x,m_y);UpdateData(FALSE); // transfer data from variable to control

Page 39: Unit-IV

}void mydialog::OnClear() { m_res=m_x =m_y =0;

UpdateData(FALSE); }6) Dialog box activation code - activate dialog box for WM_LButtonDown

of View class mydialog d;

d.DoModal();include “mydialog.h” in view.cpp file

7) Test your application

Modeless Dialogs

In the Microsoft Foundation Class (MFC) Library version 6.0, modal and modeless dialogs share the same base class, CDialog, and they both use a dialog resource that you can build with the dialog editor. Programmer should take care of

When to construct the modeless dialog

When to destroy the modeless dialog

When to activate the modeless dialog

Construct a modeless dialog object using a CDialog class. You start by invoking the CDialog default constructor to construct the dialog object, but then to create the dialog window you need to call the CDialog::Create member function instead of DoModal. Create takes the resource ID as a parameter and returns immediately with the dialog window still on the screen.

Difference between modal and modeless dialog window

  Modal Dialog Modeless Dialog

Constructor used Constructor with resource ID param

Default constructor (no params)

Function used to create window

DoModal Create with resource ID param

Example: Create a modeless dialog for first left mouse click, destroy it for right mouse click, no duplicates for other next left clicks

Page 40: Unit-IV

Construct the modeless dialog – when view is created

Display the modeless dialog - WM_LBUTTONDOWN

When to destroy the modeless dialog - WM_RBUTTONDOWN

When to activate the modeless dialog - WM_LBUTTONDOWN1. Start VC++.

2. Create a new application by selecting file-new menu, Project type: MFCAppWizard(exe) Project name: modeless1Press OK button.

3. In AppWizard Step1 Application type: Single Document Select Finish button.4. Design of Dialog Box 4. a) Select Insert Menu->Resource->select Dialog (new Dialog is added to the project workspace) 4. b) Place the following Controls and set their properties.

Control Type Object ID Property ValueEdit Box IDC_EDIT1 -- Enable

5. Coding in Dialog Box Select ClassWizard->Select the option “Create a new class”->Give Class name to New Dialog window as “mldia”. 5.a) Add the following member variables. IDC_EDIT1 CString m_str 5.b) Include the following message maps. Class name Object ID Member Function CModeless1View IDOK OnOk() CModeless1View IDCANCEL OnCancel() CModeless1View modelessView OnLButtonDown (WM_LBUTTONDOWN Message)

In CMldia(class name) mldia.h(file name) Add the following #define WM_GOODBYE WM_USER+5private: CView *m_pv;public: mldia(CView *pv);BOOL Create();

Page 41: Unit-IV

In CMldia(class name) mldia.cpp(file name) Add the following mldia::mldia(CView *pv){

m_pv=pv;}BOOL mldia::Create(){

return CDialog::Create(mldia::IDD);}void mldia::OnOK() {

if(m_pv!=NULL){

UpdateData(TRUE);m_pv->PostMessage(WM_GOODBYE,IDOK);

}else

CDialog::OnOK();}

void mldia::OnCancel() {

if(m_pv!=NULL){

m_pv->PostMessage(WM_GOODBYE,IDCANCEL);}else

CDialog::OnCancel();}

In CModeless1View(class name) modeless1View.h(file name) add pointer for dialog class

public:mldia* m_d;

In CModeless1View(class name) modeless1View.cpp(file name) create the object for dialog class

CModeless1View::CModeless1View(){

Page 42: Unit-IV

m_d=new mldia(this);}

6. View->Class Wizard->Message Maps tab-> CModeless1View(class name) WM_LBUTTONDOWN(member function) (OnLButtonDown)

Type the following code void CModeless1View::OnLButtonDown(UINT nFlags, CPoint point) {

if(m_d->GetSafeHwnd()==NULL){

m_d->Create();m_d->ShowWindow(SW_SHOWNORMAL);

}

} 7. Manual message handling. In CModeless1View(class name) modeless1View.h(file name) protected:

//{{AFX_MSG(CModeless1View)afx_msg void OnLButtonDown(UINT nFlags, CPoint point);afx_msg void OnGoodBye();//}}AFX_MSGDECLARE_MESSAGE_MAP()

In CModeless1View(class name) modeless1View.cpp(file name)

BEGIN_MESSAGE_MAP(CModeless1View, CView)//{{AFX_MSG_MAP(CModeless1View)ON_WM_LBUTTONDOWN()//}}AFX_MSG_MAP// Standard printing commandsON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)ON_MESSAGE(WM_GOODBYE,OnGoodBye)

END_MESSAGE_MAP()

void CModeless1View::OnGoodBye(){

CDC *dc=GetDC();dc->TextOut(100,100,m_d->m_str);

}

Page 43: Unit-IV

8. Include the following header file as follows, #include “mldia.h” in modeless1View.h and modeless1View.cpp files. #include "modeless1.h" in mldia.cpp file.

9. Save, Build and Run the application.

WINDOWS COMMON DIALOGS Windows provides a group of standard user interface dialogs, and

these are supported by the MFC library classes. All the common dialog classes are derived from a common base class,

CCommonDialog.

Class PurposeCColorDialog Allows the user to select or create a

colorCFileDialog Allows the user to open or save a fileCFindReplaceDialog Allows the user to substitute one

string for anotherCPageSetupDialog Allows the user to input page

measurement parametersCFontDialog Allows the user to select a font from

a list of available fontsCPrintDialog Allows the user to set up the printer

and print a document Using the CFileDialog Class DirectlyThe following code opens a file that the user has selected through the dialog: CFileDialog dlg(TRUE, "bmp", "*.bmp");if (dlg.DoModal() == IDOK) { CFile file; file.Open(dlg.GetPathName(), CFile::modeRead);} The first constructor parameter (TRUE) specifies that this object is a

"File Open" dialog instead of a "File Save" dialog. The default file extension is bmp, and *.bmp appears first in the

filename edit box. The CFileDialog::GetPathName function returns a CString object that contains the full pathname of the selected file.

Q12. Discuss the feature of CColorDialog Class in VC++.

Page 44: Unit-IV

o Allows you to incorporate a color-selection dialog box into your application.

class CColorDialog : public CCommonDialog

o To construct a CColorDialog object, use the provided constructor or derive a new class and use your own custom constructor.

Base Class Members

1. CObject Members 2. CCmdTarget Members 3. CWnd Members 4. CDialog Members 5. CCommonDialog Members

Data Members

o m_ccA structure used to customize the settings of the dialog box.

o A structure of type CHOOSECOLOR, whose members store the characteristics and values of the dialog box.

CHOOSECOLOR m_cc;

o ChooseColor function uses to initialize the Color dialog box.

typedef struct { DWORD lStructSize; HWND hwndOwner; HWND hInstance;COLORREF rgbResult; COLORREF *lpCustColors; DWORD Flags; LPARAM lCustData; LPCCHOOKPROC lpfnHook; LPCTSTR lpTemplateName; } CHOOSECOLOR, *LPCHOOSECOLOR;

Construction

Constructs a CColorDialog object

CColorDialog :: CColorDialog CColorDialog

( COLORREF clrInit = 0, DWORD dwFlags = 0, CWnd* pParentWnd = NULL );

Page 45: Unit-IV

Operations

DoModal Displays a color dialog box and allows the user to make a selection.

GetColor Returns a COLORREF structure containing the values of the selected color.

COLORREF GetColor( ) const;

GetSavedCustomColors Retrieves custom colors created by the user.

SetCurrentColor Forces the current color selection to the specified color.

void SetCurrentColor( COLORREF clr );

Q13. Discuss CFileDialog Class in VC++

The CFileDialog class encapsulates the Windows common file dialog box. Common file dialog boxes provide an easy way to implement File Open and File Save As

dialog boxes Hierarchy in MFC

class CFileDialog : public CCommonDialog

CFileDialog::CFileDialog

Call this function to construct a standard Windows file dialog box-object.

explicit CFileDialog(BOOL bOpenFileDialog, LPCTSTR lpszDefExt = NULL, LPCTSTR lpszFileName = NULL, DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, LPCTSTR lpszFilter = NULL, CWnd* pParentWnd = NULL, DWORD dwSize = 0 );

Data Members

o m_ofn The Windows OPENFILENAME structure. Provides access to basic file dialog box parameters.Construction

Page 46: Unit-IV

o CFileDialog Constructs a CFileDialog object

Operations

DoModal

◦ Displays the dialog box and allows the user to make a selection.GetFileExt

o Returns the file extension of the selected file.

GetFileName

o Returns the filename of the selected file.

GetFileTitle

o Returns the title of the selected file.

GetFolderPath

o Retrieves the path of the currently open folder or directory for an Explorer-style Open or Save As common dialog box.

GetNextPathName

o Returns the full path of the next selected file.

GetOFN

Retrieves the OPENFILENAME structure of the CFileDialog object.

GetPathName

Returns the full path of the selected file.

GetReadOnlyPref

Returns the read-only status of the selected file.

GetStartPosition

Returns the position of the first element of the filename list.

HideControl

Hides the specified control in an Explorer-style Open or Save As common dialog box.

SetControlText

Page 47: Unit-IV

Sets the text for the specified control in an Explorer-style Open or Save As common dialog box.

SetDefExt

Sets the default file name extension for an Explorer-style Open or Save As common dialog box.

SetTemplate

Sample Code

void CChildFrame::OnFileOpen() { // szFilters is a text string that includes two file name filters:

// "*.my" for "MyType Files" and "*.*' for "All Files."

char CChildFrame::szFilters[]= "MyType Files (*.my)|*.my|All Files (*.*)|*.*||";

// Create an Open dialog; the default file name extension is ".my".

CFileDialog fileDlg (TRUE, "my", "*.my", OFN_FILEMUSTEXIST| OFN_HIDEREADONLY, szFilters, this);

// Display the file dialog. When user clicks OK, fileDlg.DoModal() // returns IDOK. if( fileDlg.DoModal ()==IDOK )

{ CString pathName = fileDlg.GetPathName();

// Implement opening and reading file in here. ... //Change the window's title to the opened file's title. CString fileName = fileDlg.GetFileTitle (); SetWindowText(fileName); }

}