In an effort to make it easier for me to work with bitmaps, without MFC or
ATL, I created this class.
Nothing spectacular, but I'm wondering if this leaks memory or needs
improvement.
The thing I find most ugly in writing classes to use with native code, is
the HINSTANCE required for many functions.. getting this HINSTANCE seems to
be done by storing this in a global variable and refencing it.
I store it in
HINSTANCE g_hInst;
This isn't very portable, because my classes then need to reference to this
by defining
extern HINSTANCE g_hInst;
Shouldn't there be a way to get the instance handle through some API's
instead ?
Anyway, most important is to make sure this class is usable and doesn't leak
any memory.
Lisa
// Bitmap.h: interface for the CBitmap class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_BITMAP_H__14C7E26D_7024_4B10_A80A_CB4789F4F6E0__INCLUDED_)
#define AFX_BITMAP_H__14C7E26D_7024_4B10_A80A_CB4789F4F6E0__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CBitmap
{
public:
HBITMAP GetBitmapHandle();
BITMAP* GetBitmapPtr();
BOOL DrawBitmap(int x, int y);
BOOL LoadImageResource(UINT nResourceId);
void Detach();
BOOL Attach(HDC hDC);
CBitmap();
virtual ~CBitmap();
protected:
BITMAP m_Bitmap;
HDC m_hMemDC;
HDC m_hDC;
HBITMAP m_hBitmap;
};
#endif //
!defined(AFX_BITMAP_H__14C7E26D_7024_4B10_A80A_CB4789F4F6E0__INCLUDED_)
// Bitmap.cpp: implementation of the CBitmap class.
//
//////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <windowsx.h>
#include <aygshell.h>
#include "Bitmap.h"
extern HINSTANCE g_hInst;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CBitmap::CBitmap()
: m_hBitmap(NULL), m_hMemDC(NULL)
{
}
CBitmap::~CBitmap()
{
if (m_hMemDC)
Detach();
}
BOOL CBitmap::Attach(HDC hDC)
{
if (m_hMemDC)
Detach();
m_hDC = hDC;
m_hMemDC = ::CreateCompatibleDC(hDC);
return (BOOL) m_hMemDC;
}
void CBitmap::Detach()
{
::DeleteObject(m_hMemDC);
m_hMemDC = NULL;
}
BOOL CBitmap::LoadImageResource(UINT nResourceId)
{
if (m_hBitmap)
::DeleteObject(m_hBitmap);
m_hBitmap = ::SHLoadImageResource(g_hInst, nResourceId);
::GetObject(m_hBitmap, sizeof(BITMAP), &m_Bitmap);
return (BOOL) m_hBitmap;
}
BOOL CBitmap::DrawBitmap(int x, int y)
{
if (!m_hMemDC || !m_hBitmap)
return FALSE;
HGDIOBJ hOld = ::SelectObject(m_hMemDC, m_hBitmap);
::BitBlt(m_hDC, x, y, m_Bitmap.bmWidth, m_Bitmap.bmHeight,
m_hMemDC, 0, 0, SRCCOPY);
::SelectObject(m_hMemDC, hOld);
return TRUE;
}
BITMAP* CBitmap::GetBitmapPtr()
{
return &m_Bitmap;
}
HBITMAP CBitmap::GetBitmapHandle()
{
return m_hBitmap;
}