-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwman.cpp
More file actions
1439 lines (1438 loc) · 59.2 KB
/
wman.cpp
File metadata and controls
1439 lines (1438 loc) · 59.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ========================================================================= */
/* Window Manager Mhatxotic Design */
/* ========================================================================= */
#define WIN32_LEAN_AND_MEAN // Faster compulation of headers
#define WINVER 0x0500 // Windows 2000 or better required
#define _WIN32_WINNT WINVER // Windows 2000 or better required
#define _WIN32_WINDOWS WINVER // Windows 2000 or better required
/* ========================================================================= */
#include <process.h> // Process and thread headers
#include <windows.h> // Windows sdk headers
#include <commctrl.h> // windows common control headers
#include <shellapi.h> // Windows shell api headers
#include <commdlg.h> // windows common dialog headers
/* ========================================================================= */
#include <list> // Need std::list class
#include <map> // Need std::map class
#include <sstream> // Need std::*string* classes
#include <algorithm> // Need std::tramsform class
#include <vector> // Need std::vector class
/* ========================================================================= */
#pragma comment(lib, "User32.Lib") // User interface functions
#pragma comment(lib, "Gdi32.Lib") // Graphical interface functions
#pragma comment(lib, "ComDlg32.Lib") // Common dialog library functions
#pragma comment(lib, "ComCtl32.Lib") // Common control library functions
#pragma comment(lib, "Shell32.Lib") // Shell library functions
/* ========================================================================= */
class PROGRAM // Start of program class
{ /* --------------------------------------------------------------- */ public:
class MEMORY // Start of memory block class
{ /* ------------------------------------------------------------ */ private:
char *cpPtr; // Pointer to data
size_t stSize; // Size of data
/* --------------------------------------------------------------------- */
void InitialiseVars(void) { cpPtr = NULL; stSize = 0; }
/* --------------------------------------------------------------------- */
void InitObjectFromClass(const MEMORY &memClass)
{
// Set size
stSize = ((MEMORY&)memClass).Size();
// Set pointer
cpPtr = (char*)((MEMORY&)memClass).Ptr();
// Init this new class' vars
((MEMORY&)memClass).InitialiseVars();
}
/* ------------------------------------------------------------- */ public:
inline const size_t Size(void) { return stSize; }
/* --------------------------------------------------------------------- */
inline const char *Ptr(void) { return cpPtr; }
/* --------------------------------------------------------------------- */
const size_t Find(std::string strMatch)
{
// Bail if string invalid
if(strMatch.length() <= 0) return std::string::npos;
// Position and end of string
size_t stIndex, stLoc = 0;
// Until end of string
while(char *cpLoc = (char*)memchr(Ptr()+stLoc, strMatch.at(0), Size()-stLoc))
{
// Calculate index
stLoc = (size_t)(cpLoc-Ptr());
// Walk data until one of three things happen
// - End of match string
// - Character mismatch
// - End of memory block
for(stIndex = 0;
stIndex < strMatch.length() &&
strMatch.at(stIndex) == Ptr()[stLoc+stIndex] &&
stLoc+stIndex < Size();
++stIndex);
// If we read all of the string match then we succeeded
if(stIndex >= strMatch.length()) return stLoc;
// Incrememnt position and try again
stLoc += stIndex;
}
// Failed
return std::string::npos;
}
/* --------------------------------------------------------------------- */
void Set(const size_t stPosition, const unsigned char ucByte,
const size_t stLen)
{
// Bail if addr invalid
if(stLen <= 0) throw std::exception("write invalid params");
// Bail if position bad
if(stPosition >= Size()) throw std::exception("set pos invalid");
// Bail if size bad
if(stPosition+stLen > Size()) throw std::exception("set count invalid");
// Set the memory
memset((char*)Ptr()+stPosition, ucByte, stLen);
}
/* --------------------------------------------------------------------- */
char *Read(const size_t stPosition)
{
// Bail if size bad
if(stPosition >= Size()) throw std::exception("read pos invalid");
// Return pointer
return (char*)Ptr()+stPosition;
}
/* --------------------------------------------------------------------- */
template<typename T>void Write(const size_t stPosition, T tSource,
const size_t stToCopy)
{
// Bail if addr invalid
if(!tSource || stToCopy <= 0) throw std::exception("write invalid params");
// Bail if position bad
if(stPosition >= Size()) throw std::exception("write pos invalid");
// Bail if size bad
if(stPosition+stToCopy > Size()) throw std::exception("write count invalid");
// Do copy
memcpy((char*)Ptr()+stPosition, tSource, stToCopy);
}
/* --------------------------------------------------------------------- */
void Initialise(const size_t _stSize)
{
// Deinitialise
Deinitialise();
// Set size
stSize = _stSize;
// Allocate
cpPtr = new char[Size()];
}
/* --------------------------------------------------------------------- */
void Deinitialise(void)
{
// Free the pointer
if(Ptr()) { delete []Ptr(); }
// Reset vars
InitialiseVars();
}
/* --------------------------------------------------------------------- */
~MEMORY(void) { Deinitialise(); }
/* -- Assignment copy constructor -------------------------------------- */
MEMORY &operator=(const MEMORY &memClass)
{
// Initialise
InitObjectFromClass(memClass);
// Return this
return *this;
}
/* -- Copy constructor ------------------------------------------------- */
MEMORY(const MEMORY &memClass) { InitObjectFromClass(memClass); }
/* --------------------------------------------------------------------- */
MEMORY(void) { InitialiseVars(); }
/* --------------------------------------------------------------------- */
template<typename T>MEMORY(const size_t _stSize, T tBuffer)
{
// Init members
InitialiseVars();
// Initialise space
Initialise(_stSize);
// Copy memory
Write(0, tBuffer, _stSize);
}
};/* --------------------------------------------------------------------- */
/* ----------------------------------------------------------------------- */
class FSTREAM // Start of stream class
{ /* ------------------------------------------------------------- */ public:
FILE *fStream; // Stream handle
std::string strFilename; // Filename
/* --------------------------------------------------------------------- */
inline const size_t SetPosition(const long lPos, const int iFlags)
{ return fseek(fStream, (long)lPos, iFlags); }
/* --------------------------------------------------------------------- */
inline const size_t GetPosition(void) { return ftell(fStream); }
/* --------------------------------------------------------------------- */
inline const size_t Read(void *vpBuffer, const size_t stBytes,
const size_t stItems)
{ return fread(vpBuffer, stBytes, stItems, fStream); }
/* --------------------------------------------------------------------- */
inline const size_t Write(const void *vpBuffer, const size_t stBytes,
const size_t stItems)
{ return fwrite(vpBuffer, stBytes, stItems, fStream); }
/* --------------------------------------------------------------------- */
const size_t Size(void)
{
// Store current position
const size_t stCurrent = GetPosition();
// Set end psotion
SetPosition(0, SEEK_END);
// Store position
const size_t stSize = GetPosition();
// Restore position
SetPosition((long)stCurrent, SEEK_SET);
// Return size
return stSize;
}
/* --------------------------------------------------------------------- */
const int Open(const char *cpFile, const char *cpAccess)
{
// Close file
Close();
// Set filename
strFilename = cpFile;
// Open file
return fopen_s(&fStream, cpFile, cpAccess);
}
/* --------------------------------------------------------------------- */
void Close(void)
{
// Close stream if opened
if(fStream != NULL) fclose(fStream);
// Done
InitVariables();
}
/* --------------------------------------------------------------------- */
void InitVariables(void)
{
// Set members
fStream = NULL;
strFilename.clear();
}
/* --------------------------------------------------------------------- */
~FSTREAM(void) { Close(); }
/* --------------------------------------------------------------------- */
FSTREAM(void) { InitVariables(); }
};/* --------------------------------------------------------------------- */
/* ----------------------------------------------------------------------- */
class TOKEN
{ /* ------------------------------------------------------------- */ public:
typedef std::vector<std::string> TOKENLIST;
/* --------------------------------------------------------------------- */
TOKENLIST tokenList; // Token list
/* --------------------------------------------------------------------- */
TOKEN(std::string strString, std::string strSeparator)
{
// Location of cpSeparator
size_t stStart = 0, stLoc;
// Until eof
while((stLoc = strString.find(strSeparator, stStart)) !=
std::string::npos)
{
// Found
tokenList.push_back(strString.substr(stStart, stLoc-stStart));
// Increase position
stStart += stLoc-stStart+strSeparator.length();
}
// Push remainder of string
tokenList.push_back(strString.substr(stStart));
}
};/* --------------------------------------------------------------------- */
/* ----------------------------------------------------------------------- */
class VARS // Start of vars class
{ /* ------------------------------------------------------------- */ public:
typedef std::map<std::string,std::string> VARLIST; // Var list typedef
/* --------------------------------------------------------------------- */
VARLIST varList; // Vars list
/* --------------------------------------------------------------------- */
std::string GetHeader(std::string strName)
{
// Bail if invalid header
if(strName.length() <= 0) throw std::exception("invalid getheader name");
// Find header
VARLIST::iterator varItem = varList.find(strName);
// Return state
return varItem == varList.end() ? "" : (*varItem).second;
}
/* --------------------------------------------------------------------- */
std::string Trim(std::string strSource, const unsigned char ucChar)
{
// Remove leading whitespaces
while(strSource.length() > 0 && strSource.at(0) == ucChar)
strSource.erase(0, 1);
// Remove trailing whitespaces
while(strSource.length() > 0 && strSource.at(strSource.length()-1)
== ucChar) strSource.erase(strSource.length()-1, 1);
// Return string
return strSource;
}
/* --------------------------------------------------------------------- */
void PushLine(std::string strLine, std::string strSeparator)
{
// Bail if invalid
if(strLine.length() <= 0) throw std::exception("Invalid push source");
// Bail if invalid
if(strSeparator.length() <= 0) throw std::exception("Invalid push sep");
// Look for separator
const size_t stSepLoc = strLine.find(strSeparator);
// Not found?
if(stSepLoc == std::string::npos)
{
// Create unique variable
std::ostringstream ossVar;
// Push a unique number
ossVar << "?" << varList.size() << "?";
// Push string
varList[ossVar.str()] = Trim(strLine, ' ');
// Done
return;
}
// Push variable and value
varList[Trim(strLine.substr(0, stSepLoc), ' ')] =
Trim(strLine.substr(stSepLoc+strSeparator.length()), ' ');
}
/* --------------------------------------------------------------------- */
void Initialise(std::string strString, std::string strLineSep,
std::string strVarSep)
{
// Clear existing headers
DeInitialise();
// Location of cpSeparator
size_t stStart = 0, stLoc;
// Until eof
while((stLoc = strString.find(strLineSep, stStart)) !=
std::string::npos)
{
// Push line
PushLine(strString.substr(stStart, stLoc-stStart),
strVarSep);
// Increase position
stStart = stLoc + strLineSep.length();
}
// Push remainder of string if available
PushLine(strString.substr(stStart), strVarSep);
}
/* --------------------------------------------------------------------- */
void DeInitialise(void) { varList.clear(); }
/* --------------------------------------------------------------------- */
~VARS(void) { DeInitialise(); }
/* --------------------------------------------------------------------- */
VARS(void) { }
};/* --------------------------------------------------------------------- */
class WINDOW // Start of window class
{ /* ------------------------------------------------------------- */ public:
class CONTROL // Start of control class
{ /* ----------------------------------------------------------- */ public:
HWND hwndControl; // Handle to control
/* ------------------------------------------------------------------- */
CONTROL(void) { hwndControl = NULL; }
/* ------------------------------------------------------------------- */
CONTROL(const CONTROL &controlItem)
{
// Set control
hwndControl = controlItem.hwndControl;
// Nullify old control
((CONTROL&)controlItem).hwndControl = NULL;
}
/* ------------------------------------------------------------------- */
const CONTROL &operator=(const CONTROL &controlItem)
{
// Set control
hwndControl = controlItem.hwndControl;
// Nullify old control
((CONTROL&)controlItem).hwndControl = NULL;
// Return this
return *this;
}
/* ------------------------------------------------------------------- */
CONTROL(const size_t stId, const int iX, const int iY,
const unsigned int uiWidth, const unsigned int uiHeight,
const char *cpClassName, const char *cpText, const DWORD dwStyleEx,
const DWORD dwStyle)
{
// Create handle
hwndControl = CreateWindowEx(dwStyleEx, cpClassName, NULL,
dwStyle|WS_CHILD, iX, iY, uiWidth, uiHeight,
programClass.windowClass.hwndWindow, (HMENU)stId,
programClass.windowClass.classData.hInstance, this);
// Bail if not created
if(!hwndControl) return;
// Set font
SendMessage(WM_SETFONT, (WPARAM)programClass.windowClass.hfontWindow,
FALSE);
// If we are creating a bitmap
if(!_strcmpi(cpClassName, WC_STATIC) && dwStyle & SS_BITMAP && cpText)
{
// Create bitmap
const HBITMAP hB = (HBITMAP)LoadImage(
programClass.windowClass.classData.hInstance, cpText,
IMAGE_BITMAP, 0, 0, LR_DEFAULTCOLOR);
// If succeeded?
if(hB != NULL)
{
// Add to user data
SetWindowLongPtr(hwndControl, GWLP_USERDATA, (LONG_PTR)hB);
// Send control message
SendMessage(STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hB);
}
}
else SetText("%s",cpText);
}
/* ------------------------------------------------------------------- */
inline void Enable(void) { RemoveStyle(WS_DISABLED); }
/* ------------------------------------------------------------------- */
inline void Disable(void) { AddStyle(WS_DISABLED); }
/* ------------------------------------------------------------------- */
inline void Focus(void) { SetFocus(hwndControl); }
/* ------------------------------------------------------------------- */
inline void AddStyle(const DWORD dwStyle)
{
// Add style
SetStyle((DWORD)GetStyle() | dwStyle);
}
/* ------------------------------------------------------------------- */
inline void RemoveStyle(const DWORD dwStyle)
{
// Add style
SetStyle((DWORD)GetStyle() & ~dwStyle);
}
/* ------------------------------------------------------------------- */
inline const LONG_PTR GetStyle(void)
{
// Set style
return GetWindowLongPtr(hwndControl, GWL_STYLE);
}
/* ------------------------------------------------------------------- */
inline void SetStyle(const DWORD dwStyle)
{
// Set style and update control
SetWindowLongPtr(hwndControl, GWL_STYLE, dwStyle);
InvalidateRect(hwndControl, NULL, FALSE);
UpdateWindow(hwndControl);
}
/* ------------------------------------------------------------------- */
inline const LRESULT SendMessage(const UINT uM, const WPARAM wP,
const LPARAM lP)
{
// Return sent message
return ::SendMessage(hwndControl, uM, wP, lP);
}
/* ------------------------------------------------------------------- */
void SetText(std::string strFormat, ...)
{
// Create pointer to arguments
va_list vlArgs;
// Get pointer to arguments
va_start(vlArgs, strFormat);
// Build string
strFormat = programClass.FormatArguments(strFormat, vlArgs);
// Add item
SendMessage(WM_SETTEXT, 0, (LPARAM)strFormat.c_str());
// Clean up arguments
va_end(vlArgs);
}
/* ------------------------------------------------------------------- */
~CONTROL(void)
{
// If handle not set? return
if(!hwndControl||!IsWindow(hwndControl)) return;
// Check for bitmap handle
const HBITMAP hB = (HBITMAP)GetWindowLongPtr(hwndControl, GWLP_USERDATA);
// If set? Destroy it!
if(hB) DeleteObject(hB);
// Destroy handle
DestroyWindow(hwndControl);
}
};/* ------------------------------------------------------------------- */
typedef std::map<UINT,CONTROL> CONTROLLIST; // Control list
/* --------------------------------------------------------------------- */
typedef const bool(CALLBACK *EVENTCALLBACK)(const WPARAM,const LPARAM);
/* --------------------------------------------------------------------- */
typedef std::map<UINT,EVENTCALLBACK> EVENTLIST; // Event list
/* --------------------------------------------------------------------- */
HWND hwndWindow; // Window handle
WNDCLASSEX classData; // Window class data
HFONT hfontWindow; // Window font
HDC hdcWindow; // Window device context
DWORD dwStyle; // Window style
DWORD dwStyleEx; // Window extended style
EVENTLIST eventList; // Window events list
CONTROLLIST controlList; // Window control list
/* --------------------------------------------------------------------- */
CONTROL &GetControl(const size_t stId)
{
// Bail if item exists
CONTROLLIST::iterator controlItem = controlList.find(stId);
// If incorrect throw exception
if(controlItem == controlList.end()) throw std::exception("invalid control");
// Return item
return (*controlItem).second;
}
/* --------------------------------------------------------------------- */
void AddControl(const size_t stId, const int iX, const int iY,
const unsigned int uiWidth, const unsigned int uiHeight,
const char *cpClassName, const char *cpText, const DWORD dwStyleEx,
const DWORD dwStyle)
{
// Bail if item exists
if(controlList.find(stId) != controlList.end()) programClass.Error(2,
"Window control already registered!");
// Assign
controlList[stId] = CONTROL(stId, iX, iY, uiWidth, uiHeight,
cpClassName, cpText, dwStyleEx, dwStyle);
}
/* --------------------------------------------------------------------- */
const bool RemoveEvent(const unsigned int uMsgId)
{
// Find event
EVENTLIST::iterator eventItem = eventList.find(uMsgId);
// If event not exists bail
if(eventItem == eventList.end()) return false;
// Remove event
eventList.erase(eventItem);
// Done
return true;
}
/* --------------------------------------------------------------------- */
const bool AddEvent(const unsigned int uMsgId, EVENTCALLBACK cbFunc)
{
// Find event
EVENTLIST::iterator eventItem = eventList.find(uMsgId);
// If event already exists bail
if(eventItem != eventList.end()) return false;
// Set event
eventList[uMsgId] = cbFunc;
// Done
return true;
}
/* --------------------------------------------------------------------- */
const LRESULT Cb(const HWND hH, const unsigned int uM, const WPARAM wP, const LPARAM lP)
{
// Window is being destroyed?
if(uM == WM_DESTROY)
{
// Destroy controls
controlList.clear();
// Context is no longer valid
hdcWindow = NULL;
// Handle is no longer valid
hwndWindow = NULL;
// Post quit message
PostQuitMessage(0);
}
// Events list has window message
if(eventList.find(uM) != eventList.end())
// Call the function callback
if(eventList[uM](wP, lP) == true)
// Return event handled
return false;
// Event not handled
return DefWindowProc(hH, uM, wP, lP);
}
/* --------------------------------------------------------------------- */
static LRESULT CALLBACK CbStatic(HWND hH, unsigned int uM, WPARAM wP, LPARAM lP)
{
// Window is not being created?
if(uM != WM_NCCREATE)
// Return handled event
return reinterpret_cast<WINDOW*>(GetWindowLongPtr(hH, GWLP_USERDATA))->
Cb(hH, uM, wP, lP);
// Window is being created. Get class name
WINDOW &windowClass = *(WINDOW*)((LPCREATESTRUCT)lP)->lpCreateParams;
// Set window handle in class
windowClass.hwndWindow = hH;
// Set window device context
windowClass.hdcWindow = GetDC(hH);
// Set user data in handle to point to this class
SetWindowLongPtr(hH, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(&windowClass));
// Process the event
return windowClass.Cb(hH, uM, wP, lP);
}
/* --------------------------------------------------------------------- */
void Activate(void) { SetForegroundWindow(hwndWindow); }
/* --------------------------------------------------------------------- */
void Focus(void) { SetFocus(hwndWindow); }
/* --------------------------------------------------------------------- */
void Show(const int iState) { ShowWindow(hwndWindow, iState); }
/* --------------------------------------------------------------------- */
void MoveEnd(const int iX, const int iY)
{
// Desktop and window bounds
RECT sDeskRect = { 0 }, sRect = { 0 };
// Want working area parameters
SystemParametersInfo(SPI_GETWORKAREA, 0, &sDeskRect, NULL);
// AdjustWindowRectEx(&sDeskRect, dwStyle, FALSE, dwStyleEx);
// if(sDeskRect.left < 0) sDeskRect.right += sDeskRect.left;
// if(sDeskRect.top < 0) sDeskRect.bottom += sDeskRect.top;
sDeskRect.left = sDeskRect.top = 0;
// Get window bounds
GetWindowRect(hwndWindow, &sRect);
// Set new position info
sRect.right -= sRect.left;
sRect.bottom -= sRect.top;
sRect.left = sDeskRect.right - sRect.right;
sRect.top = sDeskRect.bottom - sRect.bottom;
// Adjust position
Move(sRect.left + iX, sRect.top + iY);
}
/* --------------------------------------------------------------------- */
void Move(const int iX, const int iY)
{
// Adjust position
SetWindowPos(hwndWindow, NULL, iX, iY, -1, -1,
SWP_NOSIZE | SWP_NOZORDER);
}
/* --------------------------------------------------------------------- */
void Centre(void)
{
// Get desktop bounds
RECT sDeskRect;
GetWindowRect(GetDesktopWindow(), &sDeskRect);
AdjustWindowRectEx(&sDeskRect, dwStyle, FALSE, dwStyleEx);
if(sDeskRect.left < 0) sDeskRect.right += sDeskRect.left;
if(sDeskRect.top < 0) sDeskRect.bottom += sDeskRect.top;
sDeskRect.left = sDeskRect.top = 0;
// Get window bounds
RECT sRect;
GetWindowRect(hwndWindow, &sRect);
// Set new position info
sRect.right -= sRect.left;
sRect.bottom -= sRect.top;
sRect.left = (sDeskRect.right / 2) - (sRect.right / 2);
sRect.top = (sDeskRect.bottom / 2) - (sRect.bottom / 2);
// Adjust position
Move(sRect.left, sRect.top);
}
/* --------------------------------------------------------------------- */
void Resize(const int iWidth, const int iHeight)
{
// Rect for window bounds
RECT sRect;
// Fill bounds
sRect.left = sRect.top = 0;
sRect.right = iWidth;
sRect.bottom = iHeight;
// Adjust size to accomodate window style
AdjustWindowRectEx(&sRect, dwStyle, FALSE, dwStyleEx);
sRect.right += -sRect.left;
sRect.bottom += -sRect.top;
// Adjust position
SetWindowPos(hwndWindow, 0, -1, -1, sRect.right, sRect.bottom, SWP_NOZORDER | SWP_NOREPOSITION | SWP_NOMOVE);
// Repaint all windows
InvalidateRect(NULL, &sRect, FALSE);
}
/* --------------------------------------------------------------------- */
void ClearFont(void)
{
// Delete font if created
if(hfontWindow) DeleteObject(hfontWindow);
// Nullify
hfontWindow = NULL;
}
/* --------------------------------------------------------------------- */
void SetFont(const char *cpFont, const int iSize)
{
// Destroy font if created
ClearFont();
// Create the font
hfontWindow = CreateFont(iSize, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, cpFont);
// Bail if failed
if(!hfontWindow) programClass.Error(1,
"Failed to create %dpt %s font (code:%x)", iSize, cpFont, GetLastError());
// Select object
if(!SelectObject(hdcWindow, hfontWindow)) programClass.Error(1,
"Failed to select %dpt %s font into context (code:%x)", iSize, cpFont,
GetLastError());
}
/* --------------------------------------------------------------------- */
void SetWindowTextF(const HWND hwndHandle, std::string strFormat, ...)
{
// Create pointer to arguments
va_list vlArgs;
// Get pointer to arguments
va_start(vlArgs, strFormat);
// Build string
strFormat = programClass.FormatArguments(strFormat, vlArgs);
// Show error
SetWindowText(hwndHandle, strFormat.c_str());
// Clean up arguments
va_end(vlArgs);
}
/* --------------------------------------------------------------------- */
void Initialise(std::string strClassName, const int iIconId,
const DWORD _dwStyleEx, const DWORD _dwStyle)
{
// Set styles
dwStyle = _dwStyle;
dwStyleEx = _dwStyleEx;
// Initialise class members
classData.style = CS_HREDRAW | CS_VREDRAW;
classData.lpfnWndProc = (WNDPROC)CbStatic;
classData.hInstance = GetModuleHandle(0);
classData.hIcon = (HICON)LoadImage(classData.hInstance,
MAKEINTRESOURCE(iIconId), IMAGE_ICON, GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
classData.hIconSm = (HICON)LoadImage(classData.hInstance,
MAKEINTRESOURCE(iIconId), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
classData.hCursor = LoadCursor(0, IDC_ARROW);
classData.lpszClassName = strClassName.c_str();
classData.hbrBackground = (HBRUSH)(COLOR_3DFACE+1);
// Register the class. Bail if failed
if(!RegisterClassEx(&classData))
programClass.Error(1, "Could not register window class (code:%x)",
GetLastError());
// Create window. Bail if failed
if(CreateWindowEx(dwStyleEx, classData.lpszClassName,
classData.lpszClassName, dwStyle, 1, 1, 1, 1, NULL, NULL,
classData.hInstance, this) == NULL || hwndWindow == NULL)
programClass.Error(2, "Could to create window handle (code:%x)",
GetLastError());
}
/* --------------------------------------------------------------------- */
void DeInitialise(void)
{
// Destroy font if created
ClearFont();
// Window handle created and really is window?
if(hwndWindow && IsWindow(hwndWindow))
{
// Release context if acquired
if(hdcWindow) ReleaseDC(hwndWindow, hdcWindow);
// Destroy handle if really is window
DestroyWindow(hwndWindow);
}
// Window class registeried?
if(classData.cbClsExtra)
// Unregister the class
UnregisterClass(classData.lpszClassName, classData.hInstance);
// Clear data
InitVariables();
}
/* --------------------------------------------------------------------- */
void InitVariables(void)
{
// Nullify font handle
hfontWindow = NULL;
// Nullify window handle
hwndWindow = NULL;
// Nullify device context
hdcWindow = NULL;
// Clear structure
memset(&classData, '\0', sizeof(classData));
// Set structure size
classData.cbSize = sizeof(classData);
// Set styles
dwStyle = dwStyleEx = 0;
}
/* --------------------------------------------------------------------- */
void Main(void)
{
// Create message queue structure
MSG sMsg;
// Until WM_QUIT or error occurs
while(GetMessage(&sMsg, 0, 0, 0) > 0)
{
// Is a dialog message? Ignore it
if(IsDialogMessage(hwndWindow, &sMsg)) continue;
// Translate the message
TranslateMessage(&sMsg);
// Dispatch the message
DispatchMessage(&sMsg);
}
}
/* --------------------------------------------------------------------- */
~WINDOW(void)
{
// DeInitialise
DeInitialise();
}
/* --------------------------------------------------------------------- */
WINDOW(void)
{
// Initialise members
InitVariables();
}
/* --------------------------------------------------------------------- */
} windowClass; // Window class
/* ----------------------------------------------------------------------- */
class TRAYICON // Tray icon class
{ /* -- Typedefs ------------------------------------------------------- */
typedef const bool (CALLBACK *TC_CALLBACK)(void); // Callback
/* ------------------------------------------------------------------- */
private: // All declarations are now private
/* -- Structs -------------------------------------------------------- */
typedef struct _TC_EVT // Tray icon event structure
{
LPARAM lParam; // Tray icon click message
TC_CALLBACK cbCallback; // Event callback function
}
TC_EVT; // Static
typedef std::map<LPARAM,TC_EVT> LST_EVT; // Event list
/* --------------------------------------------------------------------- */
NOTIFYICONDATA nidData; // Notify icon data
LST_EVT listEvents; // Click events
UINT uiTbRestartEvent; // Taskbar restart event id
/* --------------------------------------------------------------------- */
public: // All declarations are now public
/* -- Restart Callback event ------------------------------------------- */
static const bool CALLBACK CbRestart(const WPARAM, const LPARAM)
{
// Simulate hiding the tray icon to reset internal variables
programClass.trayIcon.Hide();
// Reshow the icon
programClass.trayIcon.Show();
// Event was handled
return true;
}
/* -- Callback event --------------------------------------------------- */
static const bool CALLBACK Cb(const WPARAM, const LPARAM lParam)
{
// For each event
for(LST_EVT::iterator itemEvent = programClass.trayIcon.listEvents.begin();
itemEvent != programClass.trayIcon.listEvents.end();
++itemEvent)
{
// Get pointer to data
TC_EVT &sEventData = (*itemEvent).second;
// Event id matches
if(lParam == sEventData.lParam)
// Run callback and return status
return sEventData.cbCallback();
}
// Event was not handled
return false;
}
/* -- UnregisterAllEvents --------- Unregister all mouse click events -- */
void UnregisterAllEvents(void)
{
// Clear list
listEvents.clear();
}
/* -- SetTip ----------------------------------------------------------- */
BOOL SetTip(char *cpFormat, ...)
{
// No tip?
if(cpFormat == NULL)
// Remove flag
nidData.uFlags &= ~NIF_TIP;
// Want tip
else
{
// Parse the format string and fill the tip buffer
_vsnprintf_s(nidData.szTip, sizeof(nidData.szTip), cpFormat, (va_list)(&cpFormat + 1));
// Add flag
nidData.uFlags |= NIF_TIP;
}
// Modify the icon
return Shell_NotifyIcon(NIM_MODIFY, &nidData);
}
/* -- SetIcon ---------------------------------------------------------- */
BOOL SetIcon(LPCTSTR lpszResource)
{
// Existing icon loaded?
if(nidData.hIcon != NULL)
{
// Unload it from memory
DeleteObject(nidData.hIcon);
// Nullify
nidData.hIcon = NULL;
}
// Remove icon?
if(lpszResource == NULL)
// Remove the icon flag
nidData.uFlags &= ~NIF_ICON;
// New icon?
else
{
// Load up the icon
nidData.hIcon = (HICON)LoadImage(programClass.windowClass.classData.hInstance, lpszResource, IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
// Add the icon flag
nidData.uFlags |= NIF_ICON;
}
// Modify the icon
return Shell_NotifyIcon(NIM_MODIFY, &nidData);
}
/* -- Hide ------------------------------------------------------------- */
BOOL Hide(void)
{
// Unregister the event
programClass.windowClass.RemoveEvent(nidData.uCallbackMessage);
// Restart event registered? Unregister the event
programClass.windowClass.RemoveEvent(uiTbRestartEvent);
// Hide the icon
return Shell_NotifyIcon(NIM_DELETE, &nidData);
}
/* -- Show ------------------------------------------------------------- */
BOOL Show(void)
{
// Register monitor event
programClass.windowClass.AddEvent(nidData.uCallbackMessage, Cb);
// Restart event registered?
if(uiTbRestartEvent != 0)
// Register taskbar restart event
programClass.windowClass.AddEvent(uiTbRestartEvent, CbRestart);
// Show the icon
return Shell_NotifyIcon(NIM_ADD, &nidData);
}
/* -- UnregisterEvent ---------------- Unregister a mouse click event -- */
bool UnregisterEvent(LPARAM lEventId)
{
// Bail if invalid
if(lEventId <= 0) return false;
// Look for item
LST_EVT::iterator itemEvent = listEvents.find(lEventId);
// Not found? Bail
if(itemEvent == listEvents.end()) return false;
// Remove item
listEvents.erase(itemEvent);
// Done
return true;
}
/* -- RegisterEvent -------------------- Register a mouse click event -- */
bool RegisterEvent(LPARAM lParam, TC_CALLBACK cbFunc)
{
// Bail if invalid parameters
if(lParam <= 0 || cbFunc == NULL) return false;
// Look for item
LST_EVT::iterator itemEvent = listEvents.find(lParam);
// Found? Bail
if(itemEvent != listEvents.end()) return false;
// Create data structure
TC_EVT sEvent;
// Allocate structure
sEvent.cbCallback = cbFunc;
// Set message id
sEvent.lParam = lParam;
// Add to list
listEvents[lParam] = sEvent;
// Success
return true;
}
/* -- Initialise ------------------------------------------------------- */
void Initialise(LPCTSTR lpszResource, LPSTR szTip)
{
// Setup structure
nidData.cbSize = sizeof(nidData);
nidData.uID = 1;
nidData.uFlags = NIF_MESSAGE;
nidData.hWnd = programClass.windowClass.hwndWindow;
nidData.uCallbackMessage = WM_APP + nidData.uID;
// Get register window message event
uiTbRestartEvent = RegisterWindowMessage(TEXT("TaskbarCreated"));
// Set the icon
SetIcon(lpszResource);
// Set tip
SetTip(szTip);
}
/* -- DeInitialise ----------------------------------------------------- */
void DeInitialise(void)
{
// Remove icon
Hide();
// Unregister all mouse click events
UnregisterAllEvents();
// Reinit variables
InitVariables();
}
/* -- InitVariables ---------------------------------------------------- */
void InitVariables(void)
{
// Zero structure
memset(&nidData, '\0', sizeof(nidData));
// Reset restart event
uiTbRestartEvent = 0;
}
/* -- Constructor ------------------------------------------------------ */
TRAYICON(void) { InitVariables(); }
/* -- Destructor ------------------------------------------------------- */
~TRAYICON(void) { DeInitialise(); }
/* --------------------------------------------------------------------- */
} trayIcon;
/* ----------------------------------------------------------------------- */
class MENU // Start of menu class
{ /* ----------------------------------------------------------- */ public:
typedef struct _MENUITEM // Start of menu item structure
{ /* ----------------------------------------------------------------- */
UINT uiParent; // Parent menu id
UINT uiFlags; // Menu flags
HMENU hMenu; // Sub menu
/* ----------------------------------------------------------------- */
} MENUITEM; // End of menu item structure
/* ------------------------------------------------------------------- */
typedef std::map<UINT,MENUITEM> MENULIST; // Menu list
/* ------------------------------------------------------------------- */
MENULIST menuData; // Menu list
HMENU hmRootMenu; // Root menu item
const HMENU (CALLBACK MENU::*cbFunc)(void); // Create(Popup)Menu function
/* ------------------------------------------------------------------- */
inline const bool ItemExists(const size_t stId)
{
// Return if found
return menuData.find(stId) != menuData.end();
}
/* ------------------------------------------------------------------- */
inline MENULIST::iterator GetItem(const size_t stId)
{
// Return titem
return menuData.find(stId);
}
/* ------------------------------------------------------------------- */
const HMENU CALLBACK _CreatePopupMenu(void)
{ return CreatePopupMenu(); }
/* ------------------------------------------------------------------- */
const HMENU CALLBACK _CreateMenu(void)
{ return CreateMenu(); }
/* ------------------------------------------------------------------- */
const HMENU AddItem(const size_t _stId, const UINT _uiParent,
const UINT _uiFlags, const LPCTSTR _lpszData)
{
// Bail if item exists
if(ItemExists(_stId)) return NULL;
// Find parent
MENULIST::iterator menuItemClass = GetItem(_uiParent);
// Bail if parent not found
if(_uiParent > 0 && menuItemClass == menuData.end()) return NULL;
// Create menu item structure
MENUITEM menuItem = { _uiParent, _uiFlags, NULL };
// Submenu required. Create it. Bail if failed