員工管理系統中,主對話框的 List Control 選取某員工,點擊「顯示全部資訊」按鈕,彈出次對話框並在 Picture Control 顯示該員工照片(路徑已知)。
IDC_PIC_PHOTO,屬性勾選 Notify、Sunken、Type: Bitmap 或 Icon。CDetailDlg)用 Class Wizard 對 IDC_PIC_PHOTO 新增控制項型別變數 m_picPhoto(型別 CStatic)。// CDetailDlg.h
public:
void SetPhotoPath(const CString& strPath);
// CDetailDlg.cpp
void CDetailDlg::SetPhotoPath(const CString& strPath) {
HBITMAP hBmp = (HBITMAP)::LoadImage(NULL, strPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
if (hBmp) {
m_picPhoto.SetBitmap(hBmp);
// 若需自動釋放,可儲存 hBmp 於成員變數,在 OnDestroy 刪除
}
}
void CMainDlg::OnBnClickedBtnShowDetail() {
int nSel = m_listCtrl.GetNextItem(-1, LVNI_SELECTED);
if (nSel == -1) return;
CString strPhotoPath = GetPhotoPathByItem(nSel); // 自行實作取得路徑
CDetailDlg dlg;
dlg.SetPhotoPath(strPhotoPath);
dlg.DoModal();
}
SetPhotoPath 中用 StretchBlt 繪製到相容 DC 再 SetBitmap,或改用 CPictureEx、CImage (ATL/MFC) 支援 JPG/PNG。.rc),改用 AfxGetResourceHandle() 配合 LoadBitmap。LoadImage 失敗情況,避免殘留舊圖片。CSDN 下載範例:MFC Picture Control 顯示圖片完整專案