Click here to Skip to main content
15,881,876 members
Articles / Desktop Programming / MFC

Creating Custom Controls

Rate me:
Please Sign up or sign in to vote.
4.87/5 (77 votes)
11 May 2000CPOL 561.6K   7.8K   248   100
An introduction to creating custom controls using MFC
  • Download source files - 21 Kb
  • Sample Image - CustomControl.jpg

    Introduction

    In a previous article I demonstrated subclassing a windows common control in order to modify its behaviour or extend its functionality. Sometimes you can only push the windows common controls so far. An example I came across was the common issue of needing a grid control to display and edit tabular data. I subclassed a CListCtrl and extended it to allow subitem editing, multiline cells, sort-on-click headers and a myriad of other features. However, deep down it was still a list control and there came a point where I seemed to be writing more code to stop the control performing actions than I was to actually make it do something.

    I needed to start from scratch, working from a base class that provided only the functionality I needed without any of the features (or liabilities) that I didn't need. Enter the custom control.

    Creating a Custom Control class

    Writing a custom control is very similar to subclassing a windows common control. You derive a new class from an existing class and override the functionality of the base class in order to make it do what you want.

    In this case we'll be deriving a class from CWnd, since this class provides the minimum functionality we need, without too much overhead.

    The first step in creating a custom control is to derive your class from your chosen base class (CWnd). In this example we'll create a custom control for displaying bitmaps, and we'll call this class CBitmapViewer. Obviously there is already the CStatic class that already displays bitmaps, but the example is only meant to demonstrate the possibilities available to the adventurous programmer.

    Image 2

    To your class you should add handlers for the WM_PAINT and WM_ERASEBKGND messages. I've also added an override for PreSubclassWindow in case you wish to perform any initialisation that requires the window to have been created. See my previous article for a discussion of PreSubclassWindow.

    Image 3

    The aim of this control is to display bitmaps, so we'll a method to set the bitmap and call it SetBitmap. We're not only talented, us programmers, but extremely imaginative as well.

    The internal code for the control is unimportant to this discussion but is included for completeness.

    Add a member variable of type CBitmap to the class, as well as the SetBitmap prototype:

    class CBitmapViewer : public CWnd
    {
    // Construction
    public:
        CBitmapViewer();
    
    // Attributes
    public:
        BOOL SetBitmap(UINT nIDResource);
    
        ...
        
    protected:
        CBitmap m_Bitmap;
    };

    In your CBitmapViewer implementation file add the following code for your SetBitmap method, and your WM_PAINT and WM_ERASEBKGND message handlers:

    void CBitmapViewer::OnPaint() 
    {
        // Draw the bitmap - if we have one.
        if (m_Bitmap.GetSafeHandle() != NULL)
        {
            CPaintDC dc(this); // device context for painting
    
            // Create memory DC
            CDC MemDC;
            if (!MemDC.CreateCompatibleDC(&dc))
                return;
    
            // Get Size of Display area
            CRect rect;
            GetClientRect(rect);
    
            // Get size of bitmap
            BITMAP bm;
            m_Bitmap.GetBitmap(&bm);
            
            // Draw the bitmap
            CBitmap* pOldBitmap = (CBitmap*) MemDC.SelectObject(&m_Bitmap);
            dc.StretchBlt(0, 0, rect.Width(), rect.Height(), 
                          &MemDC, 
                          0, 0, bm.bmWidth, bm.bmHeight, 
                          SRCCOPY);
            MemDC.SelectObject(pOldBitmap);      
        }
        
        // Do not call CWnd::OnPaint() for painting messages
    }
    
    BOOL CBitmapViewer::OnEraseBkgnd(CDC* pDC) 
    {
        // If we have an image then don't perform any erasing, since the OnPaint
        // function will simply draw over the background
        if (m_Bitmap.GetSafeHandle() != NULL)
            return TRUE;
        
        // Obviously we don't have a bitmap - let the base class deal with it.
        return CWnd::OnEraseBkgnd(pDC);
    }
    
    BOOL CBitmapViewer::SetBitmap(UINT nIDResource)
    {
        return m_Bitmap.LoadBitmap(nIDResource);
    }

    Making the class a Custom Control

    So far we have a class that allows us to load and display a bitmap - but as yet we have no way of actually using this class. We have two choices in creating the control - either dynamically by calling Create or via a dialog template created using the Visual Studio resource editor.

    Since our class is derived from CWnd we can use CWnd::Create to create the control dynamically. For instance, in your dialog's OnInitDialog you could have the following code:

    // CBitmapViewer m_Viewer; - declared in dialog class header
    
    m_Viewer.Create(NULL, _T(""), WS_VISIBLE, CRect(0,0,100,100), this, 1);
    m_Viewer.SetBitmap(IDB_BITMAP1);

    where m_Viewer is an object of type CBitmapViewer that is declared in your dialogs header, and IDB_BITMAP1 is the ID of a bitmap resource. The control will be created and the bitmap will display.

    However, what if we wished to place the control in a dialog template using the Visual Studio resource editor? For this we need to register a Windows Class name using the AfxRegisterClass function. Registering a class allows us to specify the background color, the cursor, and the style. See AfxRegisterWndClass in the docs for more information.

    For this example we'll register a simple class and call it "MFCBitmapViewerCtrl". We only need to register the control once, and a neat place to do this is in the constructor of the class we are writing

    #define BITMAPVIEWER_CLASSNAME    _T("MFCBitmapViewerCtrl")  // Window class name
    
    CBitmapViewer::CBitmapViewer()
    {
        RegisterWindowClass();
    }
    
    BOOL CBitmapViewer::RegisterWindowClass()
    {
        WNDCLASS wndcls;
        HINSTANCE hInst = AfxGetInstanceHandle();
    
        if (!(::GetClassInfo(hInst, BITMAPVIEWER_CLASSNAME, &wndcls)))
        {
            // otherwise we need to register a new class
            wndcls.style            = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
            wndcls.lpfnWndProc      = ::DefWindowProc;
            wndcls.cbClsExtra       = wndcls.cbWndExtra = 0;
            wndcls.hInstance        = hInst;
            wndcls.hIcon            = NULL;
            wndcls.hCursor          = AfxGetApp()->LoadStandardCursor(IDC_ARROW);
            wndcls.hbrBackground    = (HBRUSH) (COLOR_3DFACE + 1);
            wndcls.lpszMenuName     = NULL;
            wndcls.lpszClassName    = BITMAPVIEWER_CLASSNAME;
    
            if (!AfxRegisterClass(&wndcls))
            {
                AfxThrowResourceException();
                return FALSE;
            }
        }
    
        return TRUE;
    }

    In our example of creating the control dynamically, we should now change the creation call to

    m_Viewer.Create(_T("MFCBitmapViewerCtrl"), _T(""), WS_VISIBLE, CRect(0,0,100,100), this, 1);

    This will ensure the correct window styles, cursors and colors are used in the control. It's probably worthwhile writing a new Create function for your custom control so that users don't have to remember the window class name. For example:

    BOOL CBitmapViewer::Create(CWnd* pParentWnd, const RECT& rect, UINT nID, DWORD dwStyle /*=WS_VISIBLE*/)
    {
        return CWnd::Create(BITMAPVIEWER_CLASSNAME, _T(""), dwStyle, rect, pParentWnd, nID);
    }

    To use the custom control in a dialog resource, simply create a custom control on the dialog resource as you would any other control

    Image 4

    and then in the control's properties, specify the class name as "MFCBitmapViewerCtrl"

    Image 5

    The final step is to link up a member variable with the control. Simply declare an object of type CBitmapViewer in your dialog class (say, m_Viewer) and in your dialog's DoDataExchange add the following

    C++
    void CCustomControlDemoDlg::DoDataExchange(CDataExchange* pDX)
    {
        CDialog::DoDataExchange(pDX);
        //{{AFX_DATA_MAP(CCustomControlDemoDlg)
        DDX_Control(pDX, IDC_CUSTOM1, m_Viewer);
        //}}AFX_DATA_MAP
    }

    DDX_Control links the member variable m_Viewer with the control with ID IDC_CUSTOM1 by calling SubclassWindow. Creating a custom control in your dialog resource with the class name "MFCBitmapViewerCtrl" creates a window that behaves as your CBitmapViewer::RegisterWindowClass has specified, and then the DDX_Control call links your CBitmapViewer object with this pre-prepared window.

    Compile your project, run the application, and be amazed. You've just created a custom control.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


    Written By
    Founder CodeProject
    Canada Canada
    Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

    In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

    In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

    Comments and Discussions

     
    GeneralWM_MOUSEWHEEL and KEYDOWN Pin
    TomazZ12-Mar-04 1:21
    TomazZ12-Mar-04 1:21 
    GeneralRe: WM_MOUSEWHEEL and KEYDOWN Pin
    TomazZ12-Mar-04 1:34
    TomazZ12-Mar-04 1:34 
    GeneralCPU usage Pin
    Confused-216-Feb-04 6:11
    sussConfused-216-Feb-04 6:11 
    GeneralCPU usage Pin
    Confused-116-Feb-04 6:04
    sussConfused-116-Feb-04 6:04 
    QuestionHow can I provide my custom control with a 3D border? Pin
    emoscosocam9-Jan-04 6:56
    emoscosocam9-Jan-04 6:56 
    AnswerRe: How can I provide my custom control with a 3D border? Pin
    Peter Moonen9-Jan-04 22:47
    Peter Moonen9-Jan-04 22:47 
    GeneralHow can I reduce the size of the Client Area? Pin
    emoscosocam12-Jan-04 2:27
    emoscosocam12-Jan-04 2:27 
    Generalchange bitmap Pin
    craigsmith00713-Dec-03 5:22
    craigsmith00713-Dec-03 5:22 
    I can't seem to change the bitmap.

    What I want to do is mouse click and change the bitmap?
    I can capture the mouse clicks, but I can't load the new bitmap.
    GeneralRe: change bitmap Pin
    Peter Moonen3-Jan-04 11:31
    Peter Moonen3-Jan-04 11:31 
    GeneralNeed Help Pin
    Anonymous4-Dec-03 16:49
    Anonymous4-Dec-03 16:49 
    GeneralRe: Need Help Pin
    Peter Moonen3-Jan-04 11:34
    Peter Moonen3-Jan-04 11:34 
    QuestionHow can easily pass a Custom Control to ActiveX Pin
    ZeroCoolLP11-Nov-03 11:51
    ZeroCoolLP11-Nov-03 11:51 
    GeneralUsing custom control in formview gives an error Pin
    muharrem11-Oct-03 1:30
    muharrem11-Oct-03 1:30 
    GeneralRe: Using custom control in formview gives an error Pin
    Prakash Nadar13-Nov-03 18:56
    Prakash Nadar13-Nov-03 18:56 
    GeneralRe: Using custom control in formview gives an error Pin
    megan_v14-Nov-03 0:25
    megan_v14-Nov-03 0:25 
    GeneralRe: Using custom control in formview gives an error Pin
    S. Mahesh Poojary31-Aug-04 0:38
    S. Mahesh Poojary31-Aug-04 0:38 
    GeneralRe: Using custom control in formview gives an error Pin
    S. Mahesh Poojary31-Aug-04 0:59
    S. Mahesh Poojary31-Aug-04 0:59 
    GeneralWM_MouseMove, WM_LBUTTONDOWN Don't Work! Pin
    tunafish2425-Jul-03 8:42
    tunafish2425-Jul-03 8:42 
    GeneralRe: WM_MouseMove, WM_LBUTTONDOWN Don't Work! Pin
    QuangNT7-Nov-03 20:38
    QuangNT7-Nov-03 20:38 
    GeneralMultiLine Pin
    jason@zircon14-Jul-03 0:42
    sussjason@zircon14-Jul-03 0:42 
    GeneralNeed Help Pin
    RubenJ15-Jun-03 15:27
    RubenJ15-Jun-03 15:27 
    GeneralRe: Need Help Pin
    kwehfu15-Jan-04 9:15
    kwehfu15-Jan-04 9:15 
    GeneralCreating a custom Control on a Form View Pin
    Franz Klein14-May-03 1:47
    Franz Klein14-May-03 1:47 
    GeneralArray of controls ocx as visual basic Pin
    alexcc_0122-Aug-02 4:48
    alexcc_0122-Aug-02 4:48 
    QuestionHow build Tree view in Custom Control using Win 32 SDK ( C-programing)? Pin
    msubbareddy2-May-02 3:02
    msubbareddy2-May-02 3:02 

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.