我一直在尝试编写一个基于框架的MFC应用程序,其中包含一个简单响应点击的按钮。不幸的是,按钮似乎对我的行为没有反应。这是应用程序的代码:
1)OS.cpp:
#include "stdafx.h"
#include "mfc_includes.h" // some general includes like afxwin.h
#include "OS.h"
#include "MainFrm.h"
#include "button.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
BEGIN_MESSAGE_MAP(COSApp, CWinApp)
END_MESSAGE_MAP()
COSApp::COSApp() {}
COSApp theApp;
btnHelloWorld_t my_button;
BOOL COSApp::InitInstance()
{
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
CMainFrame* pFrame = new CMainFrame;
if (!pFrame)
return FALSE;
m_pMainWnd = pFrame;
pFrame->Create(L"", L"The application", WS_OVERLAPPEDWINDOW, CRect(100, 100, 500, 500));
my_button.Create(L"Hello World!", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(30, 30, 150, 80), pFrame, btnHelloWorld_t::GetID());
HFONT font = CreateFont(20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L"Times New Roman");
SendMessage(my_button.m_hWnd, WM_SETFONT, (WPARAM)font, true);
pFrame->ShowWindow(SW_SHOW);
pFrame->UpdateWindow();
return TRUE;
}
2)OS.h:
class COSApp : public CWinApp
{
public:
virtual BOOL InitInstance();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern COSApp theApp;
3)button.h(包含自定义按钮类):
#pragma once
#include "mfc_includes.h"
class btnHelloWorld_t : public CButton
{
static const int is_button = 0x200;
static int id;
public:
btnHelloWorld_t()
{
id++;
};
static const int GetID()
{
return id;
};
afx_msg void Click();
DECLARE_MESSAGE_MAP()
};
int btnHelloWorld_t::id = 0x200;
afx_msg void btnHelloWorld_t::Click()
{
SetWindowText(L"Hello!");
}
BEGIN_MESSAGE_MAP(btnHelloWorld_t, CButton)
ON_BN_CLICKED(btnHelloWorld_t::GetID(), &btnHelloWorld_t::Click)
END_MESSAGE_MAP()
你能告诉我什么是错的,以及如何在点击后让按钮更改文字?提前谢谢。
答案 0 :(得分:0)
你的btnHelloWorld_t :: GetID()是静态方法!!当你创建第一个按钮时,GetID()返回201.然后当调用消息映射时,GetID()返回202.然后,如果再次调用消息映射,GetID()返回203.然后204,205 ....
你必须在CMainFrame中处理BN_CLICKED命令,而不是btnHelloWorld_t!如果单击该按钮,其父窗口将获得WM_COMMAND消息,其中notifyCode == BN_CLICKED,controlID ==您传递给CButton :: Create()的ID。