2013-03-08 32 views
0

我一直在尝试编写一个基于框架的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

你的问题与一个静态的'btnHelloWorld_t :: GetID()'我不明白你为什么要做的事情,你这样做...然后这个代码只是一场灾难。 – 2013-03-08 22:32:51

回答

0
  1. 您的btnHelloWorld_t :: GetID()是静态方法!当您创建第一个按钮时,GetID()返回201.然后,当调用消息映射时,GetID()返回202.然后如果再次调用消息映射,则GetID()返回203.然后204,205 ....

  2. 您必须在CMainFrame中处理BN_CLICKED命令,而不是btnHelloWorld_t!如果按钮被点击,它的父窗口将得到一个WM_COMMAND消息,其中notifyCode == BN_CLICKED和controlID ==你传递给CButton :: Create()的ID。

+0

1.对不起,我忘记了静态方法的这种行为。我打算使用它来允许新创建的按钮具有不同的ID。 – alexdelphi 2013-03-08 09:35:15