MFC中richedit控制元件插入BMP圖片
阿新 • • 發佈:2019-01-08
1在對話方塊中拉入一個RichEdit控制元件。為它關聯一個控制元件值
CRichEditCtrl m_rch;
2加入2個頭檔案
#include <afxole.h>
#include <richole.h>
3在對話方塊中,新增成員函式
[cpp] view plain copy- void CDialogDlg::InsertBitmap(CString *pBmpFile)
- {
- HBITMAP bmp;
- //建立HBITMAP
- bmp = (HBITMAP)::LoadImage(NULL, *pBmpFile, IMAGE_BITMAP, 0, 0,
- LR_LOADFROMFILE|LR_DEFAULTCOLOR|LR_DEFAULTSIZE);
- STGMEDIUM stgm;
- stgm.tymed = TYMED_GDI;
- stgm.hBitmap = bmp;
- stgm.pUnkForRelease = NULL;
- FORMATETC fm;
- fm.cfFormat = CF_BITMAP;
- fm.ptd = NULL;
- fm.dwAspect = DVASPECT_CONTENT;
- fm.lindex = -1;
- fm.tymed = TYMED_GDI;
- //建立輸入資料來源
- IStorage *pStorage;
- //分配記憶體
- LPLOCKBYTES lpLockBytes = NULL;
- SCODE sc = ::CreateILockBytesOnHGlobal(NULL, TRUE, &lpLockBytes);
- if (sc != S_OK)
- AfxThrowOleException(sc);
- ASSERT(lpLockBytes != NULL);
- sc = ::StgCreateDocfileOnILockBytes(lpLockBytes,
- STGM_SHARE_EXCLUSIVE|STGM_CREATE|STGM_READWRITE, 0, &pStorage);
- if (sc != S_OK)
- {
- VERIFY(lpLockBytes->Release() == 0);
- lpLockBytes = NULL;
- AfxThrowOleException(sc);
- }
- ASSERT(pStorage != NULL);
- COleDataSource *pDataSource = new COleDataSource;
- pDataSource->CacheData(CF_BITMAP, &stgm);
- LPDATAOBJECT lpDataObject =
- (LPDATAOBJECT)pDataSource->GetInterface(&IID_IDataObject);
- //獲取RichEdit的OLEClientSite
- LPOLECLIENTSITE lpClientSite;
- m_rch.GetIRichEditOle()->GetClientSite(&lpClientSite);
- //建立OLE物件
- IOleObject *pOleObject;
- sc = OleCreateStaticFromData(lpDataObject,IID_IOleObject,OLERENDER_FORMAT,
- &fm,lpClientSite,pStorage,(void **)&pOleObject);
- if(sc!=S_OK)
- AfxThrowOleException(sc);
- //插入OLE物件
- REOBJECT reobject;
- ZeroMemory(&reobject, sizeof(REOBJECT));
- reobject.cbStruct = sizeof(REOBJECT);
- CLSID clsid;
- sc = pOleObject->GetUserClassID(&clsid);
- if (sc != S_OK)
- AfxThrowOleException(sc);
- reobject.clsid = clsid;
- reobject.cp = REO_CP_SELECTION;
- reobject.dvaspect = DVASPECT_CONTENT;
- reobject.poleobj = pOleObject;
- reobject.polesite = lpClientSite;
- reobject.pstg = pStorage;
- HRESULT hr = m_rch.GetIRichEditOle()->InsertObject( &reobject );
- delete pDataSource;
- }
然後就可以呼叫這個函數了
- void CWhatFuckDlg::OnFasong()
- {
- // TODO: Add your control notification handler code here
- InsertBitmap(&CString("d:\\haha.bmp"));
- }
值得注意的是,一定要API函式初始化,否則,執行之後是不會彈出視窗的
- BOOL CWhatFuckApp::InitInstance()
- {
- ::AfxInitRichEdit();。。。//要加入這個初始化函式
效果如下: