2012年4月28日土曜日

Win32++ (1) ボタン

main.cpp

// ボタンのテスト
#include <stdcontrols.h>
#include <controls.h>
#include <cstring.h>
#pragma comment(lib, "comctl32.lib")

// メッセージ
#define MY_MSG_001  (WM_APP + 1)

// ボタン
class MyButton : public CButton {
protected:
  int   m_nID;
public:
  MyButton(int id) : m_nID(id), CButton() {}
  virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam) {
    switch (HIWORD(wParam)) {
    case BN_CLICKED:
      {
        CWnd* pParent = this->GetParent();
        if(pParent) {
          this->SendMessage(pParent->GetHwnd(), MY_MSG_001, m_nID, 0);
        }
      }
      return TRUE;
    }
    return FALSE;
  }
};

// ビュー
class CView : public CWnd {
public:
  CView()       {}
  virtual ~CView()  {
    delete m_pButton1;
    delete m_pButton2;
  }

  virtual void OnCreate() {
    // ボタンを作成
    m_pButton1 = new MyButton(1);
    m_pButton1->Create(this);
    m_pButton1->MoveWindow(10, 10, 100, 24);
    m_pButton1->SetWindowTextW(L"ボタン1");

    m_pButton2 = new MyButton(2);
    m_pButton2->Create(this);
    m_pButton2->MoveWindow(10, 50, 100, 24);
    m_pButton2->SetWindowTextW(L"ボタン2");
  }
protected:
  virtual LRESULT WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam);

  MyButton* m_pButton1;
  MyButton* m_pButton2;
};

LRESULT CView::WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam) {
  CString str;

  switch (uMsg) {
  case MY_MSG_001:
    str.Format(L"%d %d\n", uMsg, wParam);
    TRACE(str);
    break;
  case WM_DESTROY:
    m_pButton1->Destroy();
    m_pButton2->Destroy();
    ::PostQuitMessage(0);
    break;
  }
  return WndProcDefault(uMsg, wParam, lParam);
}

class MyApp : public CWinApp {
public:
  MyApp() {}
    virtual ~MyApp() {}
  virtual BOOL InitInstance() {
    m_View.Create();
    return TRUE;
  }
private:
    CView m_View;
};

int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) 
{
    MyApp MyApp;
    return MyApp.Run();
}