예제는 Visual Studio 2008 Sp1 Eng , Console Project + MFC 로 작성하엿다
// MethodPointer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "MethodPointer.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
template <typename T>
class CLynButton : public CObject //범용적인 버튼클래스라고 가정하자
{
public:
T* Owner; //Owner변수
void (T::*OnClick)(CLynButton *Sender); //이벤트핸들러라고 가정
CLynButton(T* AOwner)
{
this->Owner = AOwner;
this->OnClick = NULL;
}
void ON_WM_MOUSELDOWN() //메세지 핸들러라고 가정하자
{
//원래 작업 하고
if((OnClick != NULL) && (Owner != NULL))
{
(*Owner.*OnClick)(this);
}
//뭐 마무리 할거있음 하고
}
};
class MainDlg : public CObject
{
public:
void Programstart(); //뭐 프로그램의 시작이라고 가정해볼까요
void OnButton1Click(CLynButton<MainDlg> *Sender)
{
printf("Hello!"); //클릭하면 Hello 라고 출력하자고 가정
}
};
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
MainDlg dlg;
dlg.Programstart();
}
return nRetCode;
}
void MainDlg::Programstart()
{
CLynButton<MainDlg> Button1(this);
Button1.OnClick = &MainDlg::OnButton1Click; //메시지 핸들러를 연결
Button1.ON_WM_MOUSELDOWN(); //마우스 메시지가 발생했다고 가정하자
//결과적으로 Hello가 출력된다.
}