Return to Tech

MFC - CTime

MFCは
Win32 SDKレベルのプログラミング手法に
C++の概念を取り入れた
アプリケーションの作成を容易にするクラスライブラリ。
※Borland社コンパイラ付属の OWL:Object Window Libraryに相当。

CTime Timer Sample


時刻表示サンプル

最少構成のサンプルに
下記を追加し、画面上部に現在時刻を表示する例です。

時刻表示例

file:app.h
// Main Window Class
class MFCBase : public CFrameWnd {
public:
 MFCBase(); // Constructor
 
 // Processing Left-Click Message
 afx_msg void OnLButtonDown(UINT, CPoint);
 afx_msg void OnPaint();
 afx_msg void OnTimer(UINT);
 afx_msg void OnDestroy();
 DECLARE_MESSAGE_MAP()
};

// Application Class
class MFCApp : public CWinApp {
public:
 BOOL InitInstance();
};
file:app.cpp
// Minimum MFC app
#include <afxwin.h>
#include <time.h>
#include "app.h"

// Message Buffer
char szBuff[128];

// Create Window
MFCBase::MFCBase() {

 // 画面左上部配置、320x240のサイズ
 RECT rect;
 rect.top = 0;
 rect.left = 0;
 rect.right = 320;
 rect.bottom = 240;

 Create(NULL, "MFC CTime Sample",
   WS_OVERLAPPEDWINDOW, rect);
 
}


// Initialize Application
BOOL MFCApp::InitInstance() {
 m_pMainWnd = new MFCBase;

 // Launch Timer
 if(m_pMainWnd->SetTimer(1, 1000, NULL) != 1) {
  return FALSE;
 }

 m_pMainWnd->ShowWindow(m_nCmdShow);
 m_pMainWnd->UpdateWindow();

 return TRUE;
}

// Message of Application
BEGIN_MESSAGE_MAP(MFCBase, CFrameWnd)
 ON_WM_PAINT()
 ON_WM_TIMER(()
 ON_WM_DESTROY()
 ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

// WM_LBUTTONDOWN
afx_msg void MFCBase::OnLButtonDown(UINT flg, CPoint location) {
 MessageBox("左クリック検知", "Debug", MB_OK);
}

// Processing WM_PAINT
afx_msg void MFCBase::OnPaint() {
 CPaintDC dc(this);
 dc.TextOut(1, 1, strBuff, strlen(strBuff));
}

// Processing WM_ON_TIMER
afx_msg void MFCBase::OnTimer(UINT id) {
 CTime currentTime = CTime::GetCurrentTime();

 struct tm newtm; // A structure containing time elements.

 currentTime.GetLocalTime(&newtm);

 asctime_s(strBuff, sizeof(strBuff), &cur);

 strBuff[strlen(strBuff) - 1] = '\0';
 InvalidateRect(NULL, 0);
}

// Processing WM_DESTROY
afx_msg void MFCBase::OnDestroy() {
 KillTimer(1);
}

MFCApp App; // Create instance of application.

Return to Tech