Insert any HBITMAP (Bitmap) in your RichEdit Control
Environment: VC6 SP5, Win2000 SP2
There are a lot of articles in Codeguru or MSDN that discuss how to insert a bitmap file inside the RichEdit control. Those articles are not working when the image is in the resource or within a handle (HBITMAP).
My article is based on the MSDN code "HOWTO: Insert a Bitmap Into an RTF Document Using the RichEdit Control", and the use of IDataObject Interface. When you refer back to the MSDN article, you will find that it uses the OLE API (OleCreateFromFile), which accepts the name of the file as a string. There are many other ways to create an OLE object (IOleObject). Those OLE APIs are started with the prefix (OleCreate). The one that I will use here is (OleCreateStaticFromData), which allows us to build an Ole object that contains only a representation without any relative data. The data for sure might be an HBITMAP value that represents an image.
How do you create an OleObject (IOleObject) using the mentioned OLE API? In order for that function to return an IOleObject pointer, you should prepare many objects before invoking it. This includes objects like IDataObject, IStorage, and IOleClientSite. Preparing the last two objects is the same method shown in the MSDN article. But, what about IDataObject?
There are two methods to get the data object of the HBITMAP. One uses COleDataSource, the MFC implementation for IDataObject interface. The second method is to supply your own implementation of IDataObject. The second one, which I use in the code, is the preferable method if you are not going to use MFC in your application.
The first method uses the following code:
STGMEDIUM stgm; stgm.tymed = TYMED_GDI; // Storage medium = HBITMAP handle stgm.hBitmap = hBitmap; stgm.pUnkForRelease = NULL; // Use ReleaseStgMedium COleDataSource *pDataSource = new COleDataSource; pDataSource->CacheData(CF_BITMAP, &stgm); LPDATAOBJECT lpDataObject = (LPDATAOBJECT)pDataSource->GetInterface(&IID_IDataObject);
Using the returned lpDataObject and the other objects you can insert the Object in the RichEdit.
The second method is to write your own IOleObject Implementation as shown in the next code:
class CImageDataObject : IDataObject
{
public:
// This static function accepts a pointer to IRochEditOle
// and the bitmap handle.
// After that the function insert the image in the current
// position of the RichEdit
//
static void InsertBitmap(IRichEditOle* pRichEditOle,
HBITMAP hBitmap);
private:
ULONG m_ulRefCnt;
BOOL m_bRelease;
// The data being bassed to the richedit
//
STGMEDIUM m_stgmed;
FORMATETC m_fromat;
public:
CImageDataObject() : m_ulRefCnt(0) {
m_bRelease = FALSE;
}
~CImageDataObject() {
if (m_bRelease)
::ReleaseStgMedium(&m_stgmed);
}
// Methods of the IUnknown interface
//
STDMETHOD(QueryInterface)(REFIID iid, void ** ppvObject)
{
if (iid == IID_IUnknown || iid == IID_IDataObject)
{
*ppvObject = this;
AddRef();
return S_OK;
}
else
return E_NOINTERFACE;
}
STDMETHOD_(ULONG, AddRef)(void)
{
m_ulRefCnt++;
return m_ulRefCnt;
}
STDMETHOD_(ULONG, Release)(void)
{
if (--m_ulRefCnt == 0)
{
delete this;
}
return m_ulRefCnt;
}
// Methods of the IDataObject Interface
//
STDMETHOD(GetData)(FORMATETC *pformatetcIn,
STGMEDIUM *pmedium) {
HANDLE hDst;
hDst = ::OleDuplicateData(m_stgmed.hBitmap,
CF_BITMAP, NULL);
if (hDst == NULL)
{
return E_HANDLE;
}
pmedium->tymed = TYMED_GDI;
pmedium->hBitmap = (HBITMAP)hDst;
pmedium->pUnkForRelease = NULL;
return S_OK;
}
STDMETHOD(GetDataHere)(FORMATETC* pformatetc,
STGMEDIUM* pmedium ) {
return E_NOTIMPL;
}
STDMETHOD(QueryGetData)(FORMATETC* pformatetc ) {
return E_NOTIMPL;
}
STDMETHOD(GetCanonicalFormatEtc)(FORMATETC* pformatectIn ,
FORMATETC* pformatetcOut ) {
return E_NOTIMPL;
}
STDMETHOD(SetData)(FORMATETC* pformatetc ,
STGMEDIUM* pmedium ,
BOOL fRelease ) {
m_fromat = *pformatetc;
m_stgmed = *pmedium;
return S_OK;
}
STDMETHOD(EnumFormatEtc)(DWORD dwDirection ,
IEnumFORMATETC** ppenumFormatEtc ) {
return E_NOTIMPL;
}
STDMETHOD(DAdvise)(FORMATETC *pformatetc,
DWORD advf,
IAdviseSink *pAdvSink,
DWORD *pdwConnection) {
return E_NOTIMPL;
}
STDMETHOD(DUnadvise)(DWORD dwConnection) {
return E_NOTIMPL;
}
STDMETHOD(EnumDAdvise)(IEnumSTATDATA **ppenumAdvise) {
return E_NOTIMPL;
}
// Some Other helper functions
//
void SetBitmap(HBITMAP hBitmap);
IOleObject *GetOleObject(IOleClientSite *pOleClientSite,
IStorage *pStorage);
};
The previous implementation for IDataObject is specialized for holding HBITMAP handle.
To use the previous implementation to insert any image in the RichEdit, use the static member function CImageDataObject::InsertBitmap. This static function accepts two parameters:
IRichEditOle* pRichEditOle : A pointer to IRichEditOle interface for the RichEdit control. You can use the method GetRichEditOle() in the MFC CRichEditCtrl class to obtain that pointer, or use the following code:
::SendMessage((HWND)m_ctlRichText.GetHwnd(), EM_GETOLEINTERFACE, 0, (LPARAM)&m_pRichEditOle);
HBITMAP hBitmap : The bitmap handle of the image. The class is responsible of freeing or closing the handle. So, don't close it your self.
For a bonus you will learn how to use high-color images in the toolbar by using CImageList. One of the advantages of using CImageList is that it automatically masks out the background color.
That's it, and enjoy!
Downloads
Download demo project - 55 KbDownload source - 3 Kb

Comments
Licencing information?
Posted by freds72 on 11/16/2010 11:33amWould it be possible to precise the licencing terms for this article?
ReplyHow to implement a progress bar in RichEdit control like MSN messenger?
Posted by Zhoudi on 04/04/2005 05:06amI want implement a progress bar in RichEdit control
-
ReplyGood
Posted by cyanmoonlight on 06/13/2006 02:12amVery useful
ReplyWhen you delete an image from the edit, how can u free the memory?
Posted by skyvense on 08/26/2004 02:30amI found when you delete an image, the memory that the image used hadn't been freed, how could we do this?
-
ReplyWhen you delete an image from the edit, how can u free the memory?
Posted by crocodilu on 11/12/2004 08:00pmI would like to know the answer to this question too. :) I google it and it appears that a lot of people have this problem but nobody has a solution for it. I ran some tests and the problem exists even for plain text too. If you remove text from the edit, the memory is not freed. I posted messages on different forums, so , if I get any feedback, I will post it here. I hope somebody will hear our cry for help and give us a hand ( or a hint ).
ReplyAddin masked bitmaps?
Posted by allanmb on 06/07/2004 02:59pmIs there a way to alter the code so that we can add masked bitmpas, or set a colour which will be the mask? Thanks Allan
-
Reply
ReplyHow did DynaChange the BackgroundColor of a Bitmap in my RichEdit Ctrl?
Posted by anny on 08/02/2004 11:36pmSend EM_GETOLEINTERFACE as often as possible
Posted by Legacy on 02/13/2004 12:00amOriginally posted by: Mak
While working with RichEdit, I came across such a problem: when you retreive IRichEditOle, then do insertion of some IOleObject, then delete it and then, insert again the same or another object, the IRichEditOle and it's IOleClientSite are INVALID and insertion rizes access violation. So, before involving any OLE operation, I advise you to retreive "fresh" IRichEditOle and it's IOleClientSite. Be warned ;)
ReplySomething is wrong with the Creation of Static Object Please Help
Posted by Legacy on 11/02/2003 12:00amOriginally posted by: Haim
Facing same problem as Togak below:
The call to: OleCreateStaticFromData returns:
0x8007000e which is 'E_OUTOFMEMORY' and the 'pOleObject' is NULL.
In the CImageDataObject::GetOleObject()
...
SCODE sc;
IOleObject *pOleObject;
sc = ::OleCreateStaticFromData(this, IID_IOleObject, OLERENDER_FORMAT, &m_fromat, pOleClientSite, pStorage, (void **)&pOleObject);
ASSERT(sc == S_OK);
Guys, does anyone have a clue what can be wrong?
ReplyAny help is appreciated.
Help with some line
Posted by Legacy on 10/15/2003 12:00amOriginally posted by: Marques
I would like to know how can I translate this code to pure c because, because I dont use classes.
CImageDataObject *pods = new CImageDataObject;
LPDATAOBJECT lpDataObject;
pods->QueryInterface(IID_IDataObject, (void**)&lpDataObject);
Thanks
Replymemory not release on backspace
Posted by Legacy on 10/02/2003 12:00amOriginally posted by: mkd
whenever an image is inserted, the memory usage goes up (as shown in the task manager). so, when the user presses bckspace to remove the image, the memory usage should go down .. right?? but it doesn't !!
Replyevery image i enter (size is 18x18 pixels only) takes up nearly 32 kb of memory ..
Code doesnt work!
Posted by Legacy on 09/19/2003 12:00amOriginally posted by: Tugak
your code will not work if i create dialog using SDK method, and the richedit is the child of that dialog. i traced everything in your code but it got failed in
sc = ::OleCreateStaticFromData(this, IID_IOleObject, OLERENDER_FORMAT, &m_format, pOleClientSite, pStorage, (void **)&pOleObject);
sc != S_OK
and the rest of codes will generate application error.
did i missd something?
ReplyPlease delete the HBITMAP Handle
Posted by Legacy on 09/13/2003 12:00amOriginally posted by: bruce
after:
CImageDataObject::InsertBitmap(m_pRichEditOle, hBitmap);
please add:
DeleteObject(hBitmap);
otherwise GDI Resource Leak
ReplyLoading, Please Wait ...