1.创建状态栏变量
假设创建的项目名为TimeBar,则在TimeBarDlg.h 头文件中添加CStatusBar m_bar;
//TimeBarDlg.h
private:
CStatusBar m_bar;
2.添加String
点开资源试图,打开string table
,在右边添加两个string
,ID分别命名为IDS_INDICATOR_MESSAGE
,IDS_INDICATOR_TIME
,标题为message
和00:00:00
。
然后在TimeBarDlg.cpp
添加如下代码
static UINT indicators[] =
{
IDS_INDICATOR_MESSAGE,
IDS_INDICATOR_TIME
};
3.初始化状态栏
1. 在TimeBarDlg.cpp
中的BOOL CTimeBarDlg::OnInitDialog()
函数中添加如下代码:
//TimeBarDlg.cpp
m_bar.Create(this); //We create the status bar
m_bar.SetIndicators(indicators, 2); //Set the number of panes
CRect rect1;
GetClientRect(&rect);//Size the two panes
m_bar.SetPaneInfo(0, IDS_INDICATOR_MESSAGE, SBPS_NORMAL,rect.Width() - 80);
m_bar.SetPaneInfo(1, IDS_INDICATOR_TIME, SBPS_STRETCH, 0);
RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, IDS_INDICATOR_TIME);
注:需要在
stdafx.h
中添加Resource.h
头文件,才能获取上面设置的string ID。
2. 继续在OnInitDialog()
添加时间显示函数
//添加时间显示函数
SetTimer(1, 1000, NULL);
3. 在TimeBarDlg.cpp
创建时间显示函数
1.在TimeBarDlg.h
中添加声明
//TimeBarDlg.h
public:
afx_msg void OnTimer(UINT_PTR nIDEvent);
2.在TimeBarDlg.cpp
中定义OnTimer()
void CTimeBarDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CTime t1;
t1 = CTime::GetCurrentTime();
m_bar.SetPaneText(1, t1.Format("%H:%M:%S"));
CDialogEx::OnTimer(nIDEvent);
}
3.初始化时间显示,在OnInitDialog()
中继续添加如下代码
//OnInitDialog()
//确保在程序刚启动时就会显示系统时间,然后实时更新。
CTime t1;
t1 = CTime::GetCurrentTime();
m_bar.SetPaneText(1, t1.Format("%H:%M:%S"));
最后运行即可。