SamuelRobinson.com

Attaching a control

A resource for Windows programmers


Quite frequently, in order to add some desirable feature to a common control, we place that control in a wrapper class and make our changes to it. Unfortunately, this causes us to lose one of the more desirable features of the Visual C++ IDE, the ability to use the resource editor to lay out the controls for a dialog. Fortunately, it's very easy to work around this problem by attaching our control to the window of an unmodified control.

This example is for a control based on MFC.
BOOL MyCommonCtrlDerivedClass::AttachDerivedClass( UINT nID, CWnd* pParentWnd,DWORD dwStyle)

{
	// Test that the parent is a valid window
	ASSERT_VALID( pParentWnd );
	
	BOOL bRet = this->Create(dwStyle, CRect(0,0,0,0),pParentWnd,nID);
	ASSERT( bRet );

	//Get the control to replace
	CWnd* pCtrlToReplace = pParentWnd->GetDlgItem(nID);
	// Just in case we've passed a bad ID
	ASSERT_VALID(pCtrlToReplace);

    // Save help context identifier so that context sensitive help can 
    // continue to work
    DWORD dwContextHelpId = pCtrlToReplace->GetWindowContextHelpId();

	CRect rcOld;
	pCtrlToReplace->GetWindowRect(&rcOld);
	pParentWnd->ScreenToClient(&rcOld);

	this->SetWindowPos( pCtrlToReplace, rcOld.left, rcOld.top, rcOld.Width(), rcOld.Height(), 
		                SWP_SHOWWINDOW|SWP_NOREDRAW|SWP_NOACTIVATE);
	
    // Set the help context identifier
    SetWindowContextHelpId(dwContextHelpId);

	//Destroy the old control...we don't need it anymore
	pCtrlToReplace->DestroyWindow();

	return bRet;
}

As you can see the procedure is reasonably simple. We start by creating the derived class's window, and then get the window for the control we wish to attach to. We do some minor housekeeping, set our window into the position of the control, and then destroy the control's window.


Comments and Suggestions

Please tell me what you think about this content and how I might improve it.

Back to Top

Back to home page


Last revised: April 25, 2002