2013-03-08 63 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