I try to display a bitmap (gray image) by using MFC but failed. I am using standard windows API in my MFC codes. Below is the code (view.cpp and I put own code in ::OnDraw()
):
lpBits
is the BYTE
array contains the bitmap BYTE
data.
When I run the code, I got an "exception thrown" error message and no display of the bitmap (a black bitmap image).
Below you can find the code as well as the error message.
extern BYTE lpBits[510][1024 * 4] = { 0 };
extern CRITICAL_SECTION g_cs;
View.h:
class Cmfc_gui_test1View : public CView
{
protected: // create from serialization only
Cmfc_gui_test1View();
DECLARE_DYNCREATE(Cmfc_gui_test1View)
// Attributes
public:
Cmfc_gui_test1Doc* GetDocument() const;
// Operations
public:
// Overrides
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
// Implementation
public:
virtual ~Cmfc_gui_test1View();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
afx_msg void OnFilePrintPreview();
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
DECLARE_MESSAGE_MAP()
public:
CBitmap* pBitmap;
CDC* pcdcMem;
CDC* m_pDC;
CRect crect;
CWnd* pwndParent;
int screenX;
int screenY;
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
};
View.cpp:
// Cmfc_gui_test1View drawing
void Cmfc_gui_test1View::OnDraw(CDC* pDC)
{
Cmfc_gui_test1Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
screenX = GetSystemMetrics(SM_CXSCREEN);
screenY = GetSystemMetrics(SM_CYSCREEN);
pBitmap->CreateCompatibleBitmap(m_pDC, 1024, 510); // Error here
pBitmap->SetBitmapBits(510*1024*4, lpBits);
pcdcMem->CreateCompatibleDC(m_pDC);
pcdcMem->SelectObject(pBitmap);
m_pDC->StretchBlt( 0, 0, screenX, screenY, pcdcMem, 0, 0, 1024, 510, SRCCOPY);
pDC->DeleteDC();
}
// Cmfc_gui_test1View message handlers
int Cmfc_gui_test1View::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: 在此添加您专用的创建代码
m_pDC = new CClientDC(this);
return 0;
}
Error message occurs when execution hits the line pBitmap->CreateCompatibleBitmap(m_pDC, 1024, 510);
:
0x0F7C0AEA (mfc140d.dll)处(位于 mfc_gui_test1.exe 中)引发的异常: 0xC0000005: 读取位置 0xCDCDCDD1 时发生访问冲突。
如有适用于此异常的处理程序,该程序便可安全地继续运行。
Translated:
Exception thrown at 0x0F7C0AEA (mfc140d.dll) (in mfc_gui_test1.exe): 0xC0000005: Access violation while reading location 0xCDCDCDD1.
If there is a handler for this exception, the program can safely continue running.