#include "stdafx.h"
#include "CPNControls.h"

// CPNSetButtonImage - Simplified function to set image for a button
// Parameters:
//     hParent - Window that is parent for the button
//     uButtonID - ID for button to set image for
//     uImageID - ID of bitmap or icon resource to use as image
// Returns: TRUE if all went OK, FALSE upon failure
BOOL CPNSetButtonImage( CWnd* pParent, UINT uButtonID, UINT uImageID )
{
	HANDLE hImage;
	int Type;
	BOOL IsIcon=FALSE, IsBitmap=FALSE;

	// Get window handle for the button
	CButton* pChild = (CButton*)pParent->GetDlgItem( uButtonID );
	if( pChild )
	{
		// Determine if window style is bitmap or icon (should be 1 of the 2).
		if( pChild->GetStyle() & BS_BITMAP )
		{
			IsBitmap = TRUE;
			Type = IMAGE_BITMAP;
		}
		if( pChild->GetStyle()  & BS_ICON )
		{
			IsIcon = TRUE;
			Type = IMAGE_ICON;
		}
		if( IsBitmap || IsIcon )
		{
			// Load the bitmap or icon specified by ImageID parameter
			hImage = LoadImage( GetModuleHandle(NULL), MAKEINTRESOURCE(uImageID), Type, 
				16, 16, LR_DEFAULTCOLOR );
			if( hImage ) // and tell the button to display it (set the button image)
			{
				if( IsBitmap )
					pChild->SetBitmap( (HBITMAP)hImage );
				else
					pChild->SetIcon( (HICON)hImage );
			}

		}
	}
	return( hImage ? TRUE : FALSE );
}

// CPNClearButtonImage - Simplified function to remoave image from a button
// Parameters:
//     hParent - Window that is parent for the button
//     uButtonID - ID for button to clear image for
// Comment: Call before button is destroyed, to release image resources.
void CPNClearButtonImage( CWnd* pParent, UINT uButtonID )
{
	BOOL IsIcon=FALSE, IsBitmap=FALSE;

	// Get Handle for the desired button
	CButton* pChild = (CButton*)pParent->GetDlgItem( uButtonID );
	if( pChild )
	{
		// Determine if the button has the Bitmap or Icon property set true (should be one of the two)
		if( pChild->GetStyle() & BS_BITMAP )
			IsBitmap = TRUE;
		else if( pChild->GetStyle() & BS_ICON )
			IsIcon = TRUE;

		if( IsBitmap || IsIcon ) // If properties are OK
		{
			if( IsBitmap ) // If the image was a bitmap, the use DeleteObject to unload it
			{
				// Get a handle for the image the button is currently using
				HBITMAP hBitmap = pChild->GetBitmap();
				DeleteObject( hBitmap );
			}
			else if ( IsIcon )
			{
				HICON hIcon = pChild->GetIcon();
				DestroyIcon( hIcon );
			}
		}
	}
}

