天天看點

【MFC動态建立按鈕,并在按鈕上實作位圖的切換顯示】

這是從我百度空間複制過來的

動态建立按鈕,并在按鈕中添加位圖,通過單擊按鈕顯示不同的位圖,可設定為顯示按鈕按下和彈起兩種狀态。隻要判斷a值進而輸入不同的響應代碼。

1、在頭檔案中添加:

    CButton *pBtn;

2、在初始化函數中添加:

    pBtn = new CButton();

    pBtn->Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON|BS_BITMAP, CRect(0,0,100,40), this, IDC_BUTTON);//按鈕顯示名、屬性、ID号

    pBtn->MoveWindow(CRect(400,100,500,140));//位置和按鈕大小

    pBtn->SetBitmap((HBITMAP)LoadImage(AfxGetInstanceHandle(), "1.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION));//插入位圖的,位圖的位置要放在程式中

    此時運作程式就可顯示按鈕,并且如果有位圖,位圖會顯示在按鈕上面;

3、在Resource.h中

    添加ID号:比如#define IDC_BUTTON 1002

4、在頭檔案下方

    protected:

    //{{AFX_MSG(CMy3View)

        // NOTE - the ClassWizard will add and remove member functions here.

        //    DO NOT EDIT what you see in these blocks of generated code !

    //}}AFX_MSG

    afx_msg void OnButton();//這句函數聲明

    DECLARE_MESSAGE_MAP()

5、在

    BEGIN_MESSAGE_MAP(CMy3View, CFormView)

    //{{AFX_MSG_MAP(CMy3View)

        // NOTE - the ClassWizard will add and remove mapping macros here.

        //    DO NOT EDIT what you see in these blocks of generated code!

    //}}AFX_MSG_MAP

    // Standard printing commands

    ON_BN_CLICKED(IDC_BUTTON, OnButton)//在外面(ID号,響應函數名)

    END_MESSAGE_MAP()

6、手動添加響應函數

    void CMyView::OnButton()

    {

        MessageBox("響應函數添加測試成功");

    }

7、在頭檔案中添加一個整形的成員變量

    int a;

8、構造函數中初始化

    a = 0;

9、在按鈕響應函數中添加

    void CMyView::OnButton()

    {

        if(a%2 == 0)

        {    

            pBtn->SetBitmap((HBITMAP)LoadImage(AfxGetInstanceHandle(), "2.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION));

        }

        else if(a%2 == 1)

        {

            pBtn->SetBitmap((HBITMAP)LoadImage(AfxGetInstanceHandle(), "1.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION));

        }

        a++;

    }