Hacking the CPropertySheet

Environment: VC6 SP4, Windows 2000, WindowsXP -->

Introduction

In my applications, I usually need to change the default look and feel and the behavior of property sheets. Working with property sheets and pages is really a pain and you must do most of the work yourself for non-standard operations (such as changing the coordinates of the buttons, adding new controls to the property sheet, and so forth). In this article, I tried to give as many tips and tricks as I can do.

Before going in to the details, you should first create a CPropertySheet derived class—say CMyPropSheet.

Let's begin with some simple things:

Hiding Standards Buttons

When our property sheet shows up, by default it has all the buttons visible and the Apply button is disabled. In general, we don't need to use an Apply button. To hide the Apply button, you can simply use the following code:

propsheet.m_psh.dwFlags |= PSH_NOAPPLYNOW;

However, this does not work for all buttons. A better approach is to get a handle to the specified button and then treat the button as a normal window. Here is sample code that hides the Cancel button:

CWnd *pWnd = GetDlgItem( IDCANCEL );
pWnd->ShowWindow( FALSE );

When we hide the controls using the ShowWindow function, all the other controls remain wherever they were. This may gives the property sheet an unappealing look. To avoid this, we should reposition the controls manually. The following subsections show how to move the controls.

Moving the Standard Buttons

As I mentioned before, once we get the handle to the standard buttons, we can treat them like any other window. The code below first hides Apply and Help buttons, then moves OK the and Cancel buttons right.

BOOL CMyPropSheet::OnInitDialog ()
{
    BOOL bResult = CPropertySheet::OnInitDialog();

    int ids [] = {IDOK, IDCANCEL};    //, ID_APPLY_NOW, IDHELP };

    // Hide Apply and Help buttons
    CWnd *pWnd = GetDlgItem (ID_APPLY_NOW);
    pWnd->ShowWindow (FALSE);
    pWnd = GetDlgItem (IDHELP);
    pWnd->ShowWindow (FALSE);
    
    CRect rectBtn;
    int nSpacing = 6;        // space between two buttons...

    for( int i =0; i < sizeof(ids)/sizeof(int); i++)
    {
        GetDlgItem (ids [i])->GetWindowRect (rectBtn);
        
        ScreenToClient (&rectBtn);
        int btnWidth = rectBtn.Width();
        rectBtn.left = rectBtn.left + (btnWidth + nSpacing)* 2;
        rectBtn.right = rectBtn.right + (btnWidth + nSpacing)* 2;

        GetDlgItem (ids [i])->MoveWindow(rectBtn);
    }

    
    return bResult;
}

The following code moves all standard buttons to the right and resizes the property sheet appropriately.

BOOL CMyPropSheet::OnInitDialog () 
{
    BOOL bResult = CPropertySheet::OnInitDialog();

    
    int ids[] = { IDOK, IDCANCEL, ID_APPLY_NOW };
    
    CRect rectWnd;
    CRect rectBtn;
    
    GetWindowRect (rectWnd);
    GetDlgItem (IDOK)->GetWindowRect (rectBtn);
    
    int btnWidth   = rectBtn.Width();
    int btnHeight  = rectBtn.Height();
    int btnOffset  = rectWnd.bottom - rectBtn.bottom;
    int btnLeft    = rectWnd.right - rectWnd.left;

    rectWnd.bottom = rectBtn.top;
    rectWnd.right  = rectWnd.right + btnWidth + btnOffset;
    MoveWindow(rectWnd);
    
    rectBtn.left   = btnLeft;
    rectBtn.right  = btnLeft + btnWidth;

    for (int i = 0; i < sizeof (ids) / sizeof (int); i++)
    {
        rectBtn.top = (i + 1) * btnOffset + btnHeight * i;
        rectBtn.bottom = rectBtn.top + btnHeight;
        GetDlgItem (ids [i])->MoveWindow (rectBtn);
    }
    
    return bResult;
}

Changing the Tab Label

To change the labels at runtime, we just need to get a pointer to the tab control and then use the SetItem functions of the tab control. Here is an example:

TC_ITEM item;
item.mask = TCIF_TEXT;
item.pszText = "New Label";

//Change the label of the first tab (0 is the index of the
//first tab)...
GetTabControl ()->SetItem (0, &item);

Changing the Tab Label Font

This is also similar to changing the label of the tab. Here is an example code:

    m_NewFont.CreateFont (14, 0, 0, 0, 800, TRUE, 0, 0, 1, 0, 0,
                          0, 0, _T("Arial") );
    GetTabControl()->SetFont (&m_NewFont);

Using Images with Tab Labels

To use images with the tab labels, first you have to create a CImageList class with the images you want to use in the tab control. For the using SetItem method of the CTabCtrl class, you should set the images of the items. Here is an example:

BOOL CMyPropSheet::OnInitDialog ()
{
    BOOL bResult = CPropertySheet::OnInitDialog();

    m_imageList.Create (IDB_MYIMAGES, 13, 1, RGB(255,255,255));
    CTabCtrl *pTabCtrl = GetTabControl ();
    pTabCtrl->SetImageList (&m_imageList);
    
    TC_ITEM item;
    item.mask = TCIF_IMAGE;
    for (int i = 0; i < NUMBER_OF_TABS; i++)
    {
        item.iImage = i;
        pTabCtrl->SetItem (i, &item );
    }

    return bResult;
}

Placing a Bitmap in the Property Sheet

The following code places a bitmap in the left-bottom corner of the property sheet.

void CMyPropSheet::OnPaint ()
{
    CPaintDC dc(this);    // device context for painting

    int nOffset = 6;
    // load IDB_BITMAP1 from our resources
    CBitmap bmp;
    if (bmp.LoadBitmap (IDB_BITMAP1))
    {
        // Get the size of the bitmap
        BITMAP bmpInfo;
        bmp.GetBitmap (&bmpInfo);

        // Create an in-memory DC compatible with the
        // display DC we're using to paint
        CDC dcMemory;
        dcMemory.CreateCompatibleDC (&dc);

        // Select the bitmap into the in-memory DC
        CBitmap* pOldBitmap = dcMemory.SelectObject (&bmp);

        // Find a bottom-left point for the bitmap in the
        // client area
        CRect rect;
        GetClientRect (&rect);
        int nX = rect.left + nOffset;
        int nY = rect.top + (rect.Height () - bmpInfo.bmHeight)
                          - nOffset;
        
        // Copy the bits from the in-memory DC into the on-
        // screen DC to actually do the painting. Use the
        // centerpoint we computed for the target offset.
        dc.BitBlt (nX, nY, bmpInfo.bmWidth, bmpInfo.bmHeight,
                   &dcMemory,
            0, 0, SRCCOPY);
        
        dcMemory.SelectObject (pOldBitmap);
    }

    // Do not call CPropertySheet::OnPaint() for painting messages
}

Adding a Control to the Property Sheet

To add your own control to the property sheet, first add a member variable to your header class. The following steps show you how to add an Edit conrol to your property sheet (to the bottom-left corner):

In MyPropSheet.h:

public:
    CEdit m_edit;

In MyPropSheet.cpp:

BOOL CMyPropSheet::OnInitDialog ()
{
    BOOL bResult = CPropertySheet::OnInitDialog ();


    CRect rect;

    int nHeight = 24;
    int nWidth = 120;
    int nOffset = 6;

    GetClientRect (&rect);

    // Find a bottom-left point for the edit control in the
    // client area
    int nX = rect.left + nOffset;
    int nY = rect.top + (rect.Height() - nHeight) - nOffset;
    
    // finally, create the edit control
    m_Edit.CreateEx (WS_EX_CLIENTEDGE, _T("EDIT"), NULL,
                     WS_CHILD | WS_VISIBLE | WS_TABSTOP |
                     WS_BORDER, nX, nY, nWidth, nHeight,
                     m_hWnd, 0, 0 );

    return bResult;
}

A More Complex Scenario

Now we are ready for a more complex operation on these stupid property sheets. Suppose you want to add a header on top of your property sheet. At first, this seems to be an easy task, but when you implement the first thing in your mind, you would mostly be disappointed.

You need a free space on top of the property sheet. Thus, you need to increase the size of the property sheet, then move all the buttons and tab control. However, this is not enough. The problem is that when you move your Tab Control, your property pages in the Tab control will not be moved appropriately. They will remain on the same coordinates (even though the tab control is moved). So, you also have to move the first property page on your tab control. You don't have to move the other property pages because when you change the active tab, the tab control will get the new coordinates automatically and place the property pages correctly. The problem occurs only when the property sheet is created and first shown. The following code creates an area on top of the property sheet and moves all the controls and property pages accordingly. You just need to add your header control.

BOOL CMyPropSheet::OnInitDialog ()
{
    BOOL bResult = CPropertySheet::OnInitDialog ();

    
    int _PropSheetButtons[] = {IDOK, IDCANCEL, ID_APPLY_NOW,
                               IDHEL };
    int m_nHeaderHeight = 70;    //The height of the header control

    CRect rectWnd;
    GetWindowRect (rectWnd);
    ScreenToClient (rectWnd);
    SetWindowPos (NULL, 0, 0, rectWnd.Width(), rectWnd.Height()
                  + m_nHeaderHeight, SWP_NOMOVE | SWP_NOZORDER |
                  SWP_NOACTIVATE);
    
    // create your header control here
    //m_HeaderCtrl.CreateEx (NULL, NULL, NULL,
    //    WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER,
    //    -1, -1, rectWnd.Width (), m_nHeaderHeight
    //    -5, m_hWnd, 0, 0);
    //m_HeaderCtrl.SetTitle (m_sTitle);
    //m_HeaderCtrl.SetIcon (m_nIcon);
    //m_HeaderCtrl.SetDesc (m_sDesc);*/
    
    
    HWND hWnd = (HWND)GetTabControl ()->m_hWnd;
    ASSERT (hWnd != NULL);
    CRect rectOld;
    ::GetWindowRect (hWnd, &rectOld);
    ScreenToClient (&rectOld);
    ::SetWindowPos (hWnd, NULL, rectOld.left, 
                    rectOld.top + m_nHeaderHeight,
                    rectOld.Width (), rectOld.Height (),
                    SWP_NOZORDER | SWP_NOACTIVATE);
    
    hWnd = (HWND)m_Page1.m_hWnd;    // m_Page1 is assumed to be
                                    // the first page in your
                                    // property sheet. Do 
                                    //corrections accordingly

    ASSERT (hWnd != NULL);
    ::GetWindowRect (hWnd, &rectOld);
    ScreenToClient (&rectOld);
    ::SetWindowPos (hWnd, NULL, rectOld.left, 
                    rectOld.top + m_nHeaderHeight, 
                    rectOld.Width (), rectOld.Height (),
                    SWP_NOZORDER | SWP_NOACTIVATE);
    
    // move buttons by a similar amount
    for (int i = 0; i < sizeof (_PropSheetButtons)
                                   / sizeof (int); i++)
    {
        hWnd = ::GetDlgItem (m_hWnd, _PropSheetButtons [i]);
        if (hWnd != NULL)
        {
            ::GetWindowRect (hWnd, &rectOld);
            ScreenToClient (&rectOld);
            ::SetWindowPos (hWnd, NULL, rectOld.left, 
                            rectOld.top + m_nHeaderHeight, 
                            rectOld.Width (), rectOld.Height (),
                            SWP_NOZORDER | SWP_NOACTIVATE);
        }
    }
    
    // Enable the Apply Now button
    hWnd = ::GetDlgItem(m_hWnd, ID_APPLY_NOW);
    if (hWnd != NULL)
    {
        ::ShowWindow (hWnd, SW_SHOW);
        ::EnableWindow (hWnd, TRUE);
    }
    
    CenterWindow ();
    
    return bResult;
}

So far, so good. Now, I want to change the behavior for the OK, Cancel, and Apply buttons. For example, when the user clicks on OK or Cancel button, you may want to do something different rather than closing the property sheet. Here is a general template that can be used to do this kind of stuff:

BOOL CMyPropSheet::OnCommand (WPARAM wParam, LPARAM lParam)
{
    // allow message map override
    if (CWnd::OnCommand (wParam, lParam))
        return TRUE;
    
    // crack message parameters
    UINT nID = LOWORD(wParam);
    HWND hWndCtrl = (HWND)lParam;
    int nCode = HIWORD(wParam);
    
    // set m_nModalResult to ID of button, whenever button
    // is clicked
    if (hWndCtrl != NULL && nCode == BN_CLICKED)
    {
        if (::SendMessage(hWndCtrl, WM_GETDLGCODE, 0, 0) &
            (DLGC_BUTTON|DLGC_DEFPUSHBUTTON))
        {
            LONG lStyle = ::GetWindowLong(hWndCtrl, GWL_STYLE)
                                          & 0x0F;
            if (lStyle == BS_PUSHBUTTON || lStyle
                       == BS_DEFPUSHBUTTON ||
                lStyle == BS_USERBUTTON || lStyle == BS_OWNERDRAW)
            {
                if (nID == IDOK)
                {
                    if (YOU_WANT_TO_CLOSE_THE_PROPERTY_SHEET)
                    {
                        // do whatever you want before closing
                        // the property page

                        // You dont have to assign nID to
                        // m_nModalResult. If you want to return
                        // IDOK or IDCANCEL instead of the default
                        // return value, you can do it by
                        // assigning IDOK or IDCANCEL to
                        // m_nModalResult
                        m_nModalResult = nID;
                    }
                    else
                    {
                        // do whatever you want.
                        return TRUE;
                    }
                }
                else if (nID == ID_APPLY_NOW)
                {
                    if (YOU_WANT_TO_CLOSE_THE_PROPERTY_SHEET)
                    {
                        // do whatever you want before closing
                        // the property page

                        // You dont have to assign nID to
                        // m_nModalResult. If you want to return
                        // IDOK or IDCANCEL instead of the
                        // default return value, you can do it
                        // by assigning IDOK or IDCANCEL to
                        // m_nModalResult
                        m_nModalResult = nID;
                    }
                    else
                    {
                        // do whatever you want.
                        return TRUE;
                    }
                }
                else if (nID == IDCANCEL)
                {
                    if (YOU_WANT_TO_CLOSE_THE_PROPERTY_SHEET)
                    {
                        // do whatever you want before closing
                        // the property page

                        // You dont have to assign nID to
                        // m_nModalResult. If you want to return
                        // IDOK or IDCANCEL instead of the
                        // default return value, you can do it
                        // by assigning IDOK or IDCANCEL to
                        // m_nModalResult
                        m_nModalResult = nID;
                    }
                    else
                    {
                        // do whatever you want.
                        return TRUE;
                    }
                }
            }
        }
    }
    return FALSE;
}

Thanks...

...To Zafir Anjum for his very useful articles about property sheets on CodeGuru.com.

Some Points that You Should Keep in Mind

  • I am not an expert in GUI programming. These tips and tricks are all from my own experience. Thus, they may contain some bugs. But until now, they've worked fine for me.
  • If you need resizable property sheets, I strongly recommend you to have a look at ResizableLib.
  • If you have any comments, suggestions, or corrections, please mail me at emindemirhan@yahoo.com.


Comments

  • The Fools Tips For mulberry bags Simplified

    Posted by hekvvddtest on 05/20/2013 04:43am

    The quality of these shoes is excellent can can't be compares with its price. [url=http://www.huanchristianlouboutinsale.co.uk/]christian louboutin sale[/url] [url=http://www.yhthomassabouk.co.uk/]thomas sabo charms uk[/url] Aldo shoes are designed by experienced craftsmen therefore they are of high quality..

    Reply
  • how to know why OnKillActive got called???

    Posted by error_hari on 12/02/2004 09:48am

    Hi all! 
    I have a property sheet with 7 property pages. 
    
    i have a requirement to find out the reason behind OnKillActive Function getting called for a property page. 
    
    That is, suppose a property page is active. If u click on the tab control and choose another page, OnKillActive of this page gets called. 
    similarly, even if OK/Apply button is clicked OnKillActive of this page gets called. 
    
    Basically, i want to differentiate between these 2 cases in my OnKillActive Function. 
    I want to do some processing only when the reason for OnKillActive of this page (i.e., PSN_KILLACTIVE is notified to this property page) is clicking OK/Apply button and not shifting to some other property page. 
    
    Though, OnApply/OnOK is the right place for this, it doesn't suit my case coz i want to do this processing before OnApply gets called (very odd case, but really in bad need of it!).... 
    
    PLZZZZ.. if any of u know a solution to this problem, let me know! 
    Thanking you all. 
    Srihari. 
    snarasim@informatica.com

    Reply
  • Hello, The apply property page button !

    Posted by Legacy on 09/16/2003 12:00am

    Originally posted by: Hajer

    Hello,

    I added the virtual function OnCommand to my activeX Property page code, The problem i met that when i added this to the code, once i change one of the controls in my property page, the apply button didn't become enabled. When i comment all the added code, everything goes right. I want to let the apply button changed when i modified some properties. So what is the problem, and can i write my own apply and cancel buttons codes and in the same time, when my properties chenged, the apply button is enabled.

    Thanks.
    Hajer.

    Reply
  • How to change PropertySheet's color?

    Posted by Legacy on 09/08/2003 12:00am

    Originally posted by: XuFeng

    I derived OnCtrColor(),but it can only change the main client rect's color.The Tab's color can't be changed?How to do it?

    • How to change the font of each page.

      Posted by emp on 08/31/2004 11:05pm

      How to change the font of each page.

      Reply
    Reply
  • How to change the button style to BS_OWNERDRAW

    Posted by Legacy on 07/22/2003 12:00am

    Originally posted by: Sylvain MARECHAL

    Hello,
    
    

    I currently workin with propertysheet in win32 (not MFC).
    I try to set the button style to BS_OWNERDRAW in order to redraw it with another color.

    I put the following code in the first Property Sheet winproc:

    static BOOL WINAPI FirstPageProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam )
    {
    switch (nMsg)
    {
    case WM_INITDIALOG :
    {
    HWND hWndButton = GetDlgItem(GetParent(hDlg), IDCANCE);
    if( hWndButton )
    {
    LONG dwStyle = GetWindowLong( hWndButton, GWL_STYLE );
    dwStyle = dwStyle | BS_OWNERDRAW;
    SetWindowLong( hWndButton, GWL_STYLE, dwStyle );
    LONG dwStyle2 = GetWindowLong( hWndButton, GWL_STYLE );
    assert( dwStyle == dwStyle2 );
    }

    // next, SetWindowLong( GetParent(hDlg),
    // GWL_WNDPROC, (long)WindowProcColorDlg ) to
    // redraw the button in WM_DRAWITEM msg etc .. etc ...

    With spy, I notice that the button window hasn't this style set. Why ? Where tu put this code ?

    Thanks,

    Sylvain

    Reply
  • How to add a menu

    Posted by Legacy on 07/09/2003 12:00am

    Originally posted by: Jacob Bensabat

    Is it possible to add a menu, in same way we can add menus to dialogs ?
    thanks
    jac

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: March 27, 2014 Teams need to deliver quality software faster and need integrated agile planning, task tracking, source control, auto deploy with continuous builds and a configurable process to adapt to the way you work. Rational Team Concert and DevOps Services (JazzHub) have everything you need to build great software, integrated seamlessly together right out of the box or available immediately in the cloud. And with the Rational Team Concert Client, you can connect your …

  • Hurricane Sandy was one of the most destructive natural disasters that the United States has ever experienced. Read this success story to learn how Datto protected its partners and their customers with proactive business continuity planning, heroic employee efforts, and the right mix of technology and support. With storm surges over 12 feet, winds that exceeded 90 mph, and a diameter spanning more than 900 miles, Sandy resulted in power outages to approximately 7.5 million people, and caused an estimated $50 …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds