现在的位置: 首页 > 综合 > 正文

MFC的对话框中创建位图按钮

2014年02月03日 ⁄ 综合 ⁄ 共 2568字 ⁄ 字号 评论关闭

1.可新建一个类ImageButton(继承自CButton),并设置其风格为自绘: ModifyStyle(0,BS_OWNERDRAW);
ImageButton.h:
class ImageButton : public CButton
{
private:
 
public:
 ImageButton();

 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(ImageButton)
 protected:
 virtual void PreSubclassWindow();//修改其风格属性
 //}}AFX_VIRTUAL

// Implementation
public:
 void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);//绘图
 
 virtual ~ImageButton(); 
 DECLARE_MESSAGE_MAP() 
};
2.ImageButton.cpp:
#include "ImageButton.h"

ImageButton::ImageButton()
{
 
}
ImageButton::~ImageButton()
{
}

//当主框架的OnDraw调用后,此按钮会自动更新显示(一直循环)
void ImageButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)

{

  CClientDC   dc(this);  
  HBITMAP   hBitmap;    //位图句柄
  hBitmap=(HBITMAP)LoadImage(
              ::AfxGetInstanceHandle(),_T("ok.bmp"),  
              IMAGE_BITMAP,0,0,  
              LR_LOADFROMFILE|LR_CREATEDIBSECTION);  
  ASSERT(hBitmap);  
  HBITMAP   hOldBitmap;    
  CDC   memDC;  
  memDC.CreateCompatibleDC(&dc);  
  hOldBitmap  =  (HBITMAP)memDC.SelectObject(/*&bmpDraw*/hBitmap);   //添加新的句柄
  dc.BitBlt(0,0,100,40,&memDC,0,0,SRCCOPY);//将缓存DC放入实际客户DC  

  //显示文字
  CString text(_T("FUCK"));
  CRect rect( 0, 0, 100,100);
 
  dc.DrawText(text,rect,DT_LEFT|DT_SINGLELINE|DT_VCENTER);

  memDC.SelectObject(hOldBitmap);  //恢复句柄

 
}

void ImageButton::PreSubclassWindow()
{
 // TODO: Add your specialized code here and/or call the base class 
 CButton::PreSubclassWindow();
 ModifyStyle(0,BS_OWNERDRAW);//注意,此句一定要,这样才能设置按钮为自绘,否则不有显示图片
}

此后有两种方法调用:一是纯代码,二是通过按钮控件.
一.在对话框DLGDlg.h中添加上面ImageButton类的对象:
在class CDLGDlg : public CDialog
{
 ImageButton m_btnImg;
}
在DLGDlg.cpp加入:
#define   IDC_MYBUTTON   1010 //先定义一个资源号,以便和按钮绑定

BEGIN_MESSAGE_MAP(CDLGDlg, CDialog)
 ON_BN_CLICKED(IDC_MYBUTTON, CDLGDlg::OnBnClickedOk) //资源号与函数事件绑定
END_MESSAGE_MAP()

在的BOOL CDLGDlg::OnInitDialog()里加入
//通过代码创建按钮
 m_btnImg.Create(_T   ( "Title   "),   WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON|BS_BITMAP/*|BS_ICON*/   ,CRect(0,0,100,124),this,IDC_MYBUTTON); //与资源号IDC_MYBUTTON绑定,在前面资源号已与函数事件绑定

二.拖一个按钮控件,设置其[属性]中的[owner draw]为true,设置其ID号为IDC_BUTTON1.
 在对话框DLGDlg.h中添加上面ImageButton类的对象:
在class CDLGDlg : public CDialog
{
 ImageButton m_btnImg;
}
在DLGDlg.cpp中:
将按钮与按钮变量关联:
 DDX_Control(pDX, IDC_BUTTON1, m_button1);

BEGIN_MESSAGE_MAP(CDLGDlg, CDialog)
 ON_BN_CLICKED(IDC_BUTTON1, CDLGDlg::OnBnClickedOk) //资源号与函数事件绑定
END_MESSAGE_MAP()

上面两者区别:用纯代码,要自己定义资源号(IDC_MYBUTTON),并显示创建按钮(Create函数).而用按钮控件时,要拖放按钮,设置其属性[owner draw]为true,再将其ID与变量绑定,并与事件绑定.

 

 

三.也可用按钮的成员函数SetBitmap()来直接设置位图:

CButton CBtn;

CBtn.ModifyStyle(0, BS_BITMAP );//可以画位图,但注意,不能要WS_OWNERDRAW,因为WS_OWNERDRAW要自己写绘制函数
 CBtn.SetBitmap( (HBITMAP)LoadImage(
  ::AfxGetInstanceHandle(),_T("res//out.bmp"),  
  IMAGE_BITMAP,0,0,  
  LR_LOADFROMFILE|LR_CREATEDIBSECTION) );

抱歉!评论已关闭.