状态栏,大部分软件通常会看到的一个子窗口,显示一些程序的状态信息,有些信息通常对我们来说是很有用处的。
今天用了一下午在MSDN上翻看了一堆英文文献,看的头好大,终于学会了状态栏的生成方法,还好付出得到结果了,于是利用状态栏写了个小程序,顺便复习一下前边学到的东西,其功能如下:
1.将状态栏分成三格,每格大小固定
2.第一格显示系统当前时间
3.第二格显示鼠标在窗口上移动的坐标
4.第三格显示窗口尺寸
截图如下:
CODE如下(分两部分,头文件和cpp):
//Time.h
#include <windows.h>
#include <windowsx.h>
#include <tchar.h>
#include <commctrl.h>
#define ID_TIMER 1
class Time //定义一个Time类
{
private:
CHAR m_time[128];
public:
CONST CHAR *GetTime()
{
SYSTEMTIME st;
GetLocalTime(&st); //得到系统当前时间
wsprintf(m_time, "%04d.%02d.%02d %02d:%02d:%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return m_time;
}
} t;
//StatusBar.cpp
#include "time.h"
HWND hStat;
LPINT lpParts;
HLOCAL hloc;
RECT rc;
int i, nWidth,nParts=3; //定义状态栏的宽度和栏数
BOOL OnCreate(HWND hwnd, LPCREATESTRUCT lpCreateStruct) {
SetTimer(hwnd, ID_TIMER, 1000, NULL); //创建窗口的同时设置定时器
hStat=CreateWindow(_T("msctls_statusbar32"),NULL, WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, hwnd, NULL, lpCreateStruct->hInstance, NULL); //创建状态栏
hloc = LocalAlloc(LHND, sizeof(int)*nParts);
lpParts = (int *)LocalLock(hloc);
return TRUE;
}
VOID OnSize(HWND hwnd, UINT, INT cx, INT cy) {
TCHAR sz[32];
GetClientRect(hwnd, &rc); //获取窗口客户区的坐标
nWidth = rc.right / nParts;
for (i = 0; i < nParts; i++) { //使每栏的宽度相等
lpParts[i] = nWidth;
nWidth += nWidth;
}
SendMessage(hStat,SB_SETPARTS,3,(long)lpParts); //将状态栏分成三栏
GetWindowRect(hwnd, &rc); //窗口的边框矩形的尺寸
wsprintf(sz, _T("%dx%d"), rc.right - rc.left, rc.bottom - rc.top);
SendMessage(hStat, SB_SETTEXT, 2, (LPARAM)sz); //显示窗口尺寸
MoveWindow(hStat, 0, 0, 0, 0, TRUE); //改变状态栏的位置和尺寸
}
VOID OnDestroy(HWND) {
PostQuitMessage(0);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
HANDLE_MSG(hwnd, WM_CREATE, OnCreate);
HANDLE_MSG(hwnd, WM_SIZE, OnSize);
HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy);
case WM_TIMER:
SendMessage(hStat,SB_SETTEXT,0 ,(long)t.GetTime()); //显示当前系统时间
break;
case WM_MOUSEMOVE: //显示鼠标移动的坐标
TCHAR pos[32];
wsprintf(pos, _T("%d,%d"), LOWORD(lParam), HIWORD(lParam));
SendMessage(hStat, SB_SETTEXT, 1, (LPARAM)pos);
break;
default: return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
VOID Main() {
MSG msg;
WNDCLASS wnd = { 0 };
wnd.lpfnWndProc = WndProc;
wnd.hInstance = GetModuleHandle(NULL);
wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
wnd.hbrBackground = (HBRUSH)COLOR_WINDOW;
wnd.lpszClassName = _T("StatusBar");
if (!CreateWindow((TCHAR*)RegisterClass(&wnd), _T("StatusBar"),
WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 500, 350,
NULL, NULL, wnd.hInstance, NULL)) ExitProcess(0);
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
ExitProcess(msg.wParam);
}
转自人人网:http://blog.renren.com/blog/239077290/410985306