MFC应用实例:[38]Picture Box打开位图
的有关信息介绍如下:使用Picture Box控件打开位图。
新建一个基于对话框的应用程序,应用程序名称为PictureBox。
对对话框进行如下图的设计,添加一个Picture Box控件和两个按钮。
对"打开"按钮的响应函数OnOpen()进行如下处理,添加一下代码:
void CPictureBoxDlg::OnOpen()
{
CFileDialog dlg(TRUE,"bmp",".bmp",
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
"位图文件(*.BMP)|*.BMP||");
dlg.DoModal();
m_strPath = dlg.GetPathName();
Invalidate();
}
对CPictureBoxDlg类的OnPaint()函数做一下处理,加入一下代码:
void CPictureBoxDlg::OnPaint()
{
if(m_strPath == "")
{
return;
}
CPaintDC dc(this); // device context for painting
HBITMAP bmpHandle = (HBITMAP)LoadImage(NULL,m_strPath,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
CBitmap bmpPicture;
CDC mdcPicture;
CBitmap *bmpFromHandle = bmpPicture.FromHandle(bmpHandle);
CRect rctPicture;
GetDlgItem(IDC_IMAGE)->GetWindowRect(&rctPicture);
mdcPicture.CreateCompatibleDC(&dc);
CBitmap * bmpPrevious = mdcPicture.SelectObject(bmpFromHandle);
ScreenToClient(&rctPicture);
dc.BitBlt(rctPicture.left, rctPicture.top,
rctPicture.Width(), rctPicture.Height(),
&mdcPicture, 0, 0, SRCCOPY);
dc.SelectObject(bmpPrevious);
}
程序运行如下,打开桌面上的*.bmp位图显示如下: