65.9K
CodeProject is changing. Read more.
Home

Easy way to Load Image in MFC dialog

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.88/5 (7 votes)

Jun 16, 2007

viewsIcon

72966

downloadIcon

2518

This artcle describes how to load image into dialogs easily

Introduction

This article tells how to link a bitmap image into dialog background.

How to do...?

Create a dialog based application, open the dialog.cpp file and go to OnPaint function, it looks like below coding...

void CLoad_ImageDlg::OnPaint() 
{
 if (IsIconic())
 {
  CPaintDC dc(this); // device context for painting
  SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
  // Center icon in client rectangle
  int cxIcon = GetSystemMetrics(SM_CXICON);
  int cyIcon = GetSystemMetrics(SM_CYICON);
  CRect rect;
  GetClientRect(&rect);
  int x = (rect.Width() - cxIcon + 1) / 2;
  int y = (rect.Height() - cyIcon + 1) / 2;
  // Draw the icon
  dc.DrawIcon(x, y, m_hIcon);
 }
 else
 {
  CDialog::OnPaint();
 }
}

just erase the coding (if you dont need of icon for your dialog) which is available in the paint and modify the function as below

void CLoad_ImageDlg::OnPaint() 
{
    CPaintDC dc(this); // device context for painting
    HBITMAP m_Bmap;
    CRect rect;
    HDC memdc;
    CString path,m_ifilename1,m_ifilename2;

    path=AfxGetApp()->m_pszHelpFilePath;

    for(int i=1;i<=path.GetLength();i++)
    {    
        if(path.Mid(i,10)=="Load_Image")
        {
            path = path.Mid(0,i+10);
            break;
        }
    }
    m_ifilename1 = path + "\\"+"AK.bmp";

    GetClientRect(&rect);

    m_Bmap=(HBITMAP)::LoadImage(NULL,m_ifilename1,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
    memdc=::CreateCompatibleDC(dc.m_hDC);
    ::SelectObject(memdc,m_Bmap);

    BitBlt(dc.m_hDC,0,0,rect.right,rect.bottom,memdc,0,0,SRCCOPY); 

}

the above source will get the current path of application folder and load the image from that folad into dialog.

hope that this article helps you to link image into mfc dialog that you write.

This is my first article. If there is anything missing of explanation please mail me..

my email id : ak_from_cbe@yahoo.com

History

June 16 - 2007