[C++]LAB7-ON_BN_CLICKED

           โปรแกรมนี้ จะสร้าง ปุ่มบนหน้าต่างขึ้นมา2 ปุ่ม เมื่อทำการกดปุ่มแล้วจะมี MessageBox เด้งขึ้นมาบอกว่า Hello1 เมื่อกดปุ่มClick me1  และ Hello2 เมื่อกดปุ่มClick me2





  • เริ่มจากเขียนไฟล์ .h 
#include <afxwin.h>

#define IDC_MYBUTTON1 1001 // (1) define
#define IDC_MYBUTTON2 1002
class CMyApp : public CWinApp // create application
{
public:
virtual BOOL InitInstance();
};

class CWin : public CFrameWnd //create window
{
 public:CWin();
 ~CWin();
 CButton *myButton1;
 CButton *myButton2;
 afx_msg void OnClick1();
 afx_msg void OnClick2();
 DECLARE_MESSAGE_MAP(); // (2) declare button control
};




  • เขียนไฟล์ .cpp 
#include "lab7a.h"

CMyApp theApp; // create application object

BEGIN_MESSAGE_MAP(CWin, CFrameWnd)
 ON_BN_CLICKED(IDC_MYBUTTON1, OnClick1)
 ON_BN_CLICKED(IDC_MYBUTTON2, OnClick2)
END_MESSAGE_MAP()

void CWin::OnClick1()
{
 MessageBox("Hello 1");
}

void CWin::OnClick2()
{
 MessageBox("Hello 2");
}


BOOL CMyApp::InitInstance()
{
m_pMainWnd = new CWin(); // create windows frame object and link to application
m_pMainWnd->ShowWindow(m_nCmdShow); //show frame windows

m_pMainWnd->UpdateWindow(); // update frame windows
return TRUE;
}

CWin::CWin()
{ 
myButton1 = new CButton(); // (3) memory allocation
myButton2 = new CButton();
Create(NULL,"Hello Visual c++, Easy MFC 01", 
WS_OVERLAPPEDWINDOW, CRect(100,100,500,300));
// (4) create control
(*myButton1).Create("Click me1", 
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
CRect(10,10,100,50),this,IDC_MYBUTTON1);

(*myButton2).Create("Click me2", 
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
CRect(110,10,200,50),this,IDC_MYBUTTON2);
}





CWin::~CWin()
{
delete myButton1;
delete myButton2;
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

VISITOR