Code:
#include "Thread.h"
class Label {
public:
Label()
: hwnd()
{}
bool create( HWND parent,
LPCTSTR text = 0,
DWORD style = WS_CHILD|WS_VISIBLE|SS_CENTERIMAGE,
DWORD stylex = 0,
int x=0,
int y=0,
int w=0,
int h=0 )
{
hwnd = CreateWindowEx( stylex, TEXT("Static"), text, style, x, y, w, h,
parent, 0, GetModuleHandle(0), 0 );
return NULL != hwnd ;
}
void setHandle( HWND h ) {
hwnd = h ;
}
HWND getHandle() const {
return hwnd ;
}
void setText( LPCTSTR text ) {
SetWindowText( hwnd, text ) ;
}
private:
HWND hwnd ;
};
class Button {
public:
Button()
: hwnd()
{}
bool create( HWND parent,
LPCTSTR text = 0,
DWORD style = WS_CHILD|WS_VISIBLE,
DWORD stylex = 0,
int x=0,
int y=0,
int w=0,
int h=0 )
{
hwnd = CreateWindowEx( stylex, TEXT("Button"), text, style, x, y, w, h, parent,
0, GetModuleHandle(0), 0 );
return NULL != hwnd ;
}
void setHandle( HWND h ) {
hwnd = h ;
}
HWND getHandle() const {
return hwnd ;
}
void setText( LPCTSTR text ) {
SetWindowText( hwnd, text ) ;
}
private:
HWND hwnd ;
};
class CounterThread : public Thread {
public:
virtual void run() {
int i = 0 ;
int past = GetTickCount() ;
while ( i < 100 ) {
int now = GetTickCount() ;
if ( now - past > 100 ) {
past = now ;
++i ;
TCHAR buf[ 100 ] ;
wsprintf( buf, "%d", i ) ;
label.setText( buf ) ;
}
Sleep( 10 );
}
}
void setLabel( HWND hwnd ) {
label.setHandle( hwnd ) ;
}
private:
Label label ;
};
Button startButton, stopButton ;
Label label ;
CounterThread counterThread ;
LRESULT CALLBACK WndProc( HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam )
{
switch(msg)
{
case WM_CREATE: {
startButton.create( hwnd, TEXT("Start"), WS_CHILD|WS_VISIBLE,
0,
10, 10, 80, 22 );
stopButton.create( hwnd, TEXT("Stop"), WS_CHILD|WS_VISIBLE,
0,
100, 10, 80, 22 );
label.create( hwnd, TEXT("0%"), WS_CHILD|WS_VISIBLE|SS_CENTERIMAGE, 0,
10, 40, 80, 22 ) ;
counterThread.setLabel( label.getHandle() );
if ( label.getHandle() == NULL ) {
return 1 ;
}
return 0 ;
}
case WM_COMMAND:
{
HWND ctrl = (HWND) lParam ;
if ( ctrl == startButton.getHandle() ) {
if ( !counterThread.isRunning() ) {
if ( !counterThread.start() ) {
MessageBox( hwnd, TEXT("Error creating thread"), 0, 0 );
}
}
}
else if ( ctrl == stopButton.getHandle() ) {
counterThread.stop() ;
}
return 0 ;
}
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
default: return DefWindowProc(hwnd,msg,wParam,lParam);
}
}
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrev, LPSTR args, int nShow )
{
MSG msg ;
WNDCLASS wc = {0};
wc.lpszClassName = TEXT( "Boilerplate" );
wc.hInstance = hInst ;
wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc.lpfnWndProc = WndProc ;
wc.hCursor = LoadCursor(0,IDC_ARROW);
RegisterClass(&wc);
CreateWindow( wc.lpszClassName,TEXT("Boilerplate Windows Program"),
WS_OVERLAPPEDWINDOW|WS_VISIBLE,
0,0,300,200,0,0,hInst,0);
while( GetMessage(&msg,0,0,0) > 0 ) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}