-
Notifications
You must be signed in to change notification settings - Fork 3
/
BiggerDirectories.c
4960 lines (4136 loc) · 150 KB
/
BiggerDirectories.c
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
#include <stdio.h> //sprintf
#include <stdlib.h> //malloc
#include <fcntl.h>
#include <io.h> //setmode
#include <shlwapi.h>
#include <sddl.h>
#include <windows.h>
#include <strsafe.h> //safe string copy & StringCchPrintf
#include <tlhelp32.h> //Find process stuff
#include <winternl.h> //NtCreateFile
#include <errno.h>
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include "BiggerDirectories.h" //my file
//#include <afxwin.h>
//#include <ntstatus.h>
//#include <ntstrsafe.h>
wchar_t hrtext[256] = {'\0'}; //An array name is essentially a pointer to the first element in an array.
wchar_t hrWarn[8] = L"Warning";
WIN32_FIND_DATAW dw; // directory data this will use stack memory as opposed to LPWIN32_FIND_DATA
WIN32_FIND_DATAA da;
int const pathLength = 32759, maxDWORD = 32767, maxPathFolder = MAX_PATH - 3, treeLevelLimit = 2000, branchLimit = 1000;
const wchar_t BOM = L'\xFEFF'; //65279
wchar_t const *invalidPathName = L":\"/\\|?*<>";
wchar_t const eolFTA = L'\n';
wchar_t const separatorFTA = L'\\';
wchar_t const *lPref = L"\\\\?\\";
//wchar_t const * hrWarn = L"Warning";
wchar_t const APP_CLASS_NAME[] = L"BiggerDirectories";
wchar_t driveInfo[26][2], driveIndex[2];
wchar_t driveIDBaseW[8], driveIDBaseWNT[8], driveIDBaseAW[4];
char driveIDBase[4];
UINT const WM_COPYGLOBALDATA = 0x0049; //Drop files filter
wchar_t rootDir [pathLength], dblclkPath [treeLevelLimit + 1][maxPathFolder], dblclkString [pathLength], reorgTmpW[pathLength];//maxPathFolder unless delete fails
wchar_t *pathToDeleteW, *currPathW, *findPathW, *tempDest, *thisexePath, *BiggerDirectoriesVAR; // directory pointers. cannot be initialised as a pointer
char *currPath;
//http://stackoverflow.com/questions/2516096/fastest-way-to-zero-out-a-2d-array-in-c
char dacfolders[branchLimit][MAX_PATH-3]; //[32768 / 257] [ MAX_PATH- 3] double array char is triple array
wchar_t dacfoldersW[branchLimit][MAX_PATH-3], dacfoldersWtmp[branchLimit][maxPathFolder], folderTreeArray[branchLimit][treeLevelLimit + 1][maxPathFolder] = { NULL };
wchar_t reorgTmpWFS[treeLevelLimit + 1][maxPathFolder], pathsToSave [branchLimit][pathLength];
int rootFolderCS, rootFolderCW, branchLevel, branchTotal, branchLevelCum, branchLevelClickOld, branchLevelClick, branchTotalSaveFile, branchLevelInc, branchLevelIncCum, branchSaveI, branchTotalCum, branchTotalCumOld, dblclkLevel = 0;
int i,j,k, errCode, verifyFail;
int idata, index, folderIndex, listTotal = 0, sendMessageErr = 0;
int treeLevel, trackFTA[branchLimit][2];
int resResult;
bool resWarned;
bool wideScr = true;
bool foundResolution = false;
bool pCmdLineActive = false;
bool secondTryDelete = false;
bool createFail = false;
bool setforDeletion = false;
bool removeButtonEnabled = true;
bool nologonEnabled = false;
bool logonEnabled = false;
bool wow64Functions = false;
BOOL weareatBoot = FALSE;
BOOL am64Bit, exe64Bit;
PVOID OldValue = nullptr; //Redirection
WNDPROC g_pOldProc;
HANDLE keyHwnd, hMutex, hdlNtCreateFile, hdlNTOut, exeHandle, ds; // directory handle
HINSTANCE appHinstance;
HDROP hDropInfo = NULL; //shell drop handle
//struct FolderRepository
//{
// char FT[treeLevelLimit][branchLimit][maxPathFolder];
//char FB[1000];
//};
//NTDLLptr is a pointer to a function returning LONG or NTSTATUS
typedef NTSTATUS (__stdcall *NTDLLptr)(
OUT PHANDLE FileHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PLARGE_INTEGER AllocationSize,
IN ULONG FileAttributes,
IN ULONG ShareAccess,
IN ULONG CreateDisposition,
IN ULONG CreateOptions,
IN PVOID EaBuffer,
IN ULONG EaLength );
//for NTcreatefile fileObject, NTAPI is __stdcall
typedef VOID (__stdcall *PFN_RtlInitUnicodeString) (
IN OUT PUNICODE_STRING DestinationString,
IN PCWSTR SourceString );
typedef ULONG (__stdcall *PFN_RtlNtStatusToDosError) (
IN NTSTATUS Status );
//static my_RtlInitUnicodeString rtlInitUnicodeString; //Makes no difference
//PFN_RtlNtStatusToDosError RtlNtStatusToDosError;
NTDLLptr foundNTDLL = nullptr; //points to return of NTStatus
OBJECT_ATTRIBUTES fileObject;
IO_STATUS_BLOCK ioStatus;
NTSTATUS ntStatus = NULL;
UNICODE_STRING fn;
const char createFnString[13] = "NtCreateFile"; //one extra for null termination
const char initUnicodeFnString[21] = "RtlInitUnicodeString";
const char NtStatusToDosErrorString[22] = "RtlNtStatusToDosError";
const wchar_t TEMP_CLASS_NAME[14] = L"ResCheckClass";
//A pathname MUST be no more than 32,760 characters in length. (ULONG) Each pathname component MUST be no more than 255 characters in length (USHORT)
//wchar_t longPathName=(char)0; //same as '\0'
class APP_CLASS
{
public:
APP_CLASS();
// This is the static callback that we register
static INT_PTR CALLBACK s_DlgProc(HWND hdlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
// The static callback recovers the "this" pointer and then calls this member function.
INT_PTR DlgProc(HWND hdlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
};
APP_CLASS::APP_CLASS(void)
{
switch (resResult)
{
case 1:
if (wideScr)
{
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_4320PW), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
}
else
{
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_4320P), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
}
break;
case 2:
if (wideScr)
{
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_2160PW), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
}
else
{
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_2160P), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
}
break;
case 3:
if (wideScr)
{
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_1080PW), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
}
else
{
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_1080P), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
}
break;
case 4:
if (wideScr)
{
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_768PW), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
}
else
{
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_768P), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
}
break;
default:
DialogBoxParamW(appHinstance, MAKEINTRESOURCEW(IDD_SMALL), nullptr, APP_CLASS::s_DlgProc, reinterpret_cast<LPARAM>(this));
break;
}
}
//------------------------------------------------------------------------------------------------------------------
// Protos...
//------------------------------------------------------------------------------------------------------------------
//void printStack(void);
int DisplayError (HWND hwnd, LPCWSTR messageText, int errorcode, int yesNo);
void ErrorExit (LPCWSTR lpszFunction, DWORD NTStatusMessage);
void InitProc(HWND hwnd);
LRESULT CALLBACK RescheckWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK ValidateProc(HWND, UINT, WPARAM, LPARAM); //subclass
INT_PTR WINAPI AboutDlgProc(HWND aboutHwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int PopulateListBox(HWND hwnd, BOOL widecharNames, BOOL listFolders);
void TextinIDC_TEXT(HWND hwnd);
int DoSystemParametersInfoStuff(HWND hwnd, bool progLoad);
int SwitchResolution(HWND hwnd, INT_PTR(WINAPI* dProc)(HWND, UINT, WPARAM, LPARAM));
int GetBiggerDirectoriesPath(HWND hwnd, wchar_t *exePath);
bool Kleenup(HWND hwnd);
int ExistRegValue();
DWORD FindProcessId(HWND hwnd, const wchar_t *processName, HANDLE &hProcessName);
NTDLLptr DynamicLoader(bool progInit, wchar_t *fileObjVar);
bool CloseNTDLLObjs(BOOL atWMClose);
bool ProcessFolderRepository(HWND hwnd, bool falseReadtrueWrite, bool appendMode);
bool CheckAttribs(int jVar, wchar_t &tempDestOld);
void FRDeleteInit(HWND hwnd, HWND hList);
bool FRDelete(HWND hwnd);
bool FRDelsub(HWND hwnd);
void doFilesFolders(HWND hwnd);
void FRReorg(int jVar, int &brTotal);
void OldDeleteInit(HWND hwnd);
int RecurseRemovePath();
// Start of HyperLink URL
void ShellError(HWND aboutHwnd, HINSTANCE nError);
static LRESULT CALLBACK _HyperlinkParentProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK _HyperlinkProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
static void CreateHyperLink(HWND hwndControl);
DWORD dynamicComCtrl(LPCWSTR lpszDllName);
BOOL GetAccountSidW(LPWSTR SystemName, PSID *Sid);
int GetDrives(HWND hwnd);
void ThisInvalidParameterHandler(HWND hwnd, const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved);
BOOL RevertWOW64RedirectionIfNecessary(PVOID pOldValue);
BOOL DisableWOW64RedirectionIfNecessary(PVOID pOldValue);
BOOL ChangeWindowMsgFilterEx(HWND hwnd, UINT Msg);
//BOOL GetProcAddresses( HINSTANCE *hLibrary, LPSTR lpszLibrary, INT nCount, ... );
// End of HyperLink URL
int DisplayError (HWND hwnd, LPCWSTR messageText, int errorcode, int yesNo)
{ //The way this is set up is errorcode is not modifiable here. However if errCode is passed here is always byval and will always revert to zero.
//*hrtext (pointee) is value pointed to by hrtext. Can be replaced by hrtext[0]
//hrtext[0] = (wchar_t)LocalAlloc(LPTR, 256*sizeof(wchar_t)); This dynamic allocation NOT required- see below
//if (hrtext[0] == NULL) ErrorExit("LocalAlloc");
//hrtext[0] = NULL; or //*hrtext = NULL; //simple enough but not req'd
//http://www.cprogramming.com/tutorial/printf-format-strings.html
if (errorcode == 0)
{
_snwprintf_s(hrtext, _countof(hrtext), _TRUNCATE, L"%s.", messageText);
}
else //LT 0 my defined error, GT 0 error should be GET_LAST_ERROR
{
if (!Beep(200,150)) MessageBoxW(hwnd, L"Beep function failed!", hrWarn, MB_OK);
_snwprintf_s(hrtext, _countof(hrtext), _TRUNCATE, L"%s. Error Code: %d", messageText, errorcode);
}
//change countof sizeof otherwise possible buffer overflow: here index and rootFolderCS gets set to -16843010!
if (yesNo)
{
int msgboxID = MessageBoxW(hwnd, hrtext, hrWarn, MB_YESNO);
if (msgboxID == IDYES)
{
return 1;
}
else
{
return 0;
}//IDNO
}
else
{
MessageBoxW(hwnd, hrtext, hrWarn, MB_OK);
}
return 0;
//if ((HANDLE)*hrtext) LocalFree((HANDLE)*hrtext); // It is not safe to free memory allocated with GlobalAlloc. -MSDN
//wchar_t hrtext[256] allocates memory to the stack. It is not a dynamic allocation http://stackoverflow.com/questions/419022/char-x256-vs-char-malloc256sizeofchar
}
void ErrorExit (LPCWSTR lpszFunction, DWORD NTStatusMessage)
{
//courtesy https://msdn.microsoft.com/en-us/library/windows/desktop/ms680582(v=vs.85).aspx
// also see http://stackoverflow.com/questions/35177972/wide-char-version-of-get-last-error/35193301#35193301
DWORD dww = 0;
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
if (NTStatusMessage)
{
dww = NTStatusMessage;
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_FROM_HMODULE,
hdlNtCreateFile,
dww,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR) &lpMsgBuf,
0,
nullptr );
}
else
{
dww = GetLastError();
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
dww,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf,0, nullptr);
}
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlenW((LPCWSTR)lpMsgBuf) + lstrlenW((LPCWSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintfW((LPWSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(wchar_t), L"%s Failed With Error %lu: %s", lpszFunction, dww, (LPWSTR)lpMsgBuf);
wprintf(L"\a"); //audible bell
Beep(400,500);
MessageBoxW(nullptr, (LPCWSTR)lpDisplayBuf, L"Error", MB_OK);
LocalFree(lpDisplayBuf);
LocalFree(lpMsgBuf);
//ExitProcess(dw);
}
void InitProc(HWND hwnd)
{
errCode = 0;
//if (foundNTDLL) we can use the better function
if (!DynamicLoader (true, tempDest)) DisplayError (hwnd, L"An error occurred. The long path function has been removed. Using 'short' path functions..", errCode, 0);
#ifdef _WIN32_WINNT //#if is a directive: see header file
#if (NTDDI_VERSION < NTDDI_WINXPSP3)
{
if (DisplayError (hwnd, L"This program will not work in any Operating Systems older than XP(SP3). Click Yes to exit.", errCode, 1))
{
if (exeHandle != INVALID_HANDLE_VALUE) CloseHandle(exeHandle);
ReleaseMutex(hMutex);
if (currPath) free(currPath);
if (currPathW) free(currPathW);
exit (EXIT_FAILURE); //EndDialog will process the rest of the code in the fn.
}
}
#endif
#else
{
if (DisplayError (hwnd, L"Not Win32: This program may not work in this environment! Click Yes to exit.", errCode, 1));
{
if (exeHandle != INVALID_HANDLE_VALUE) CloseHandle(exeHandle);
ReleaseMutex(hMutex);
if (currPath) free(currPath);
if (currPathW) free(currPathW);
exit (EXIT_FAILURE);
}
}
#endif
#if defined(ENV64BIT)
{
if (sizeof(void*) != 8)
{
DisplayError (hwnd, L"ENV64BIT: Error: pointer should be 8 bytes. Exiting", errCode, 0);
if (exeHandle != INVALID_HANDLE_VALUE) CloseHandle(exeHandle);
ReleaseMutex(hMutex);
if (currPath) free(currPath);
if (currPathW) free(currPathW);
exit (EXIT_FAILURE);
}
am64Bit = true;
exe64Bit = true;
}
#elif defined (ENV32BIT)
{
if (sizeof(void*) != 4)
{
DisplayError (hwnd, L"ENV32BIT: Error: pointer should be 4 bytes. Exiting", errCode, 0);
if (exeHandle != INVALID_HANDLE_VALUE) CloseHandle(exeHandle);
ReleaseMutex (hMutex);
if (currPath) free(currPath);
if (currPathW) free(currPathW);
exit (EXIT_FAILURE);
}
if (FindProcessId (hwnd, L"BiggerDirectories.exe", exeHandle) != NULL)
{
am64Bit = false;
exe64Bit = false;
if (RevertWOW64RedirectionIfNecessary(OldValue))
{
wow64Functions = true;
typedef BOOL (__stdcall *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process;
fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandleW((L"kernel32.dll")),"IsWow64Process");
if(nullptr != fnIsWow64Process)
{
exe64Bit = fnIsWow64Process(GetCurrentProcess(),&exe64Bit) && exe64Bit;
}
}
}
else
{
DisplayError (hwnd, L"Our own process isn't active!? Must terminate", 1, 0);
ReleaseMutex (hMutex);
if (currPath) free(currPath);
if (currPathW) free(currPathW);
exit (EXIT_FAILURE); //EndDialog will process the rest of the code in the fn.
}
}
#else
{
//#error "user" gen error won't compile with current settings: "Must define either ENV32BIT or ENV64BIT". 128 bit?
DisplayError (hwnd, L"Not ENV32BIT or ENV64BIT. Exiting", errCode, 0);
if (exeHandle != INVALID_HANDLE_VALUE) CloseHandle(exeHandle);
ReleaseMutex (hMutex);
if (currPath) free(currPath);
if (currPathW) free(currPathW);
exit (EXIT_FAILURE);
}
#endif
if (FindProcessId (hwnd, L"explorer.exe", exeHandle) == NULL)
{
weareatBoot=TRUE;
nologonEnabled = false;
logonEnabled = false;
EnableWindow(GetDlgItem(hwnd, IDC_LOGON), logonEnabled);
EnableWindow(GetDlgItem(hwnd, IDC_NOLOGON), nologonEnabled);
}
else
{
if (!FindProcessId (hwnd, L"userinit.exe", exeHandle) == NULL)
{
DisplayError (hwnd, L"Userinit should have ended. Try rebooting before running this (or any other) program", errCode, 0);
}
BiggerDirectoriesVAR = (wchar_t *)calloc(maxPathFolder, sizeof(wchar_t));
if (!ExpandEnvironmentStringsW (L"%SystemRoot%", BiggerDirectoriesVAR, maxPathFolder)) ErrorExit (L"ExpandEnvironmentStringsW failed for some reason.", 0);
wcscat_s(BiggerDirectoriesVAR, maxPathFolder, L"\\Temp\\BiggerDirectories.exe");
if (GetFileAttributesW(BiggerDirectoriesVAR) != INVALID_FILE_ATTRIBUTES)
{
logonEnabled = false;
EnableWindow(GetDlgItem(hwnd, IDC_LOGON), logonEnabled);
}
else
{
logonEnabled = true;
EnableWindow(GetDlgItem(hwnd, IDC_LOGON), logonEnabled);
}
if (ExistRegValue() == 1)
{
setforDeletion = TRUE;
(logonEnabled)? nologonEnabled = false: nologonEnabled = true;
EnableWindow(GetDlgItem(hwnd, IDC_NOLOGON), nologonEnabled);
}
else
{
nologonEnabled = true;
EnableWindow(GetDlgItem(hwnd, IDC_NOLOGON), nologonEnabled);
}
free(BiggerDirectoriesVAR);
}
//Raw keyboard for input- need to subclass child controls for keystrokes to work
RAWINPUTDEVICE Rid[1];
Rid[0].usUsagePage = 0x01;
Rid[0].usUsage = 0x06;
Rid[0].dwFlags = 0; // adds HID keyboard and invludes legacy keyboard messages
Rid[0].hwndTarget = 0;
if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE) DisplayError (hwnd, L"Could not register Raw Input", errCode, 0);
LPCWSTR lpszDllName = L"C:\\Windows\\System32\\ComCtl32.dll";
DWORD dwVer = dynamicComCtrl(lpszDllName);
DWORD dwTarget = PACKVERSION(5,2);
if((dwVer < dwTarget) && !rootFolderCW) DisplayError (hwnd, L"Old version of ComCtl32.dll", errCode, 0);
//NULL is a macro that's guaranteed to expand to a null pointer constant.
//C strings are NUL-terminated, not NULL-terminated. (char)(0) is the NUL character, (void * )(0) is NULL, type void * , is called a null pointer constant
//If (NULL == 0) isn't true you're not using C. '\0' is the same as '0' see https://msdn.microsoft.com/en-us/library/h21280bw.aspx but '0' does not work!
//http://stackoverflow.com/questions/15610506/can-the-null-character-be-used-to-represent-the-zero-character NO
createFail = false;
branchLevelClickOld = 0;
branchLevelClick = 0;
branchLevelCum = 0;
branchTotalSaveFile = -1;
branchTotal = -1;
branchTotalCum = 0;
branchTotalCumOld = 0;
branchLevelIncCum = 0; //in case !foundNTDLL
resResult = 0;
resWarned = false;
memset(dacfolders, '\0', sizeof(dacfolders)); //'\0' is NULL L'\0' is for C++ but we are compiling in Unicode anyway
memset(dacfoldersW, L'\0', sizeof(dacfoldersW));
memset(folderTreeArray, L'\0', sizeof(folderTreeArray)); //required for remove function
memset(pathsToSave, L'\0', sizeof(pathsToSave)); //required for create
for (j = 0; j <= branchLimit; j++)
{
trackFTA [j][0] = 0; //Initial conditons before search on path
trackFTA [j][1] = 0;
}
SetDlgItemTextW(hwnd,IDC_STATIC_ZERO, L"Add");
SetDlgItemTextW(hwnd,IDC_STATIC_ONE, L"times.");
SetDlgItemInt(hwnd, IDC_NUMBER, 3, FALSE);//set repeat number
TextinIDC_TEXT (hwnd);
EnableWindow(GetDlgItem(hwnd, IDC_DOWN), false);
EnableWindow(GetDlgItem(hwnd, IDC_UP), false);
EnableWindow(GetDlgItem(hwnd, IDC_CREATE), false);
sendMessageErr = SendDlgItemMessageW(hwnd, IDC_LIST, LB_RESETCONTENT, 0, 0);
if (dblclkLevel)
{
SendDlgItemMessageW (hwnd, IDC_LIST, LB_ADDSTRING, (WPARAM)(0), (LPARAM)L".."); // add .. for return to Drives
EnableWindow(GetDlgItem(hwnd, IDC_NUMBER), true);
EnableWindow(GetDlgItem(hwnd, IDC_TEXT), true);
EnableWindow(GetDlgItem(hwnd, IDC_ADD), true);
EnableWindow(GetDlgItem(hwnd, IDC_REMOVE), true);
removeButtonEnabled = true;
DragAcceptFiles (hwnd, FALSE);
rootFolderCS = PopulateListBox(hwnd, false, true);
rootFolderCW = PopulateListBox(hwnd, true, true);
}
else
{
memset(driveInfo, L'\0', sizeof(driveInfo));
memset(dblclkPath, L'\0', sizeof(dblclkPath));
dblclkLevel = 0;
dblclkString[0] = L'\0';
wcscpy_s(driveIDBaseW, 8, L"\\\\?\\C:\\"); // 1 for the null terminator
wcscpy_s(driveIDBaseWNT, 8, L"\\??\\C:\\");
wcscpy_s(driveIDBaseAW, 4, L"C:\\");
strcpy_s(driveIDBase, 4, "C:\\");
EnableWindow(GetDlgItem(hwnd, IDC_TEXT), false);
EnableWindow(GetDlgItem(hwnd, IDC_NUMBER), false);
EnableWindow(GetDlgItem(hwnd, IDC_ADD), false);
EnableWindow(GetDlgItem(hwnd, IDC_REMOVE), false);
removeButtonEnabled = false;
DragAcceptFiles (hwnd, true);
//Drag Drop folders for root drive: WS_EX_ACCEPTFILES for WNDCLASS only
if (!GetDrives(hwnd)) DisplayError (hwnd, L"Could find any Drives", errCode, 0);
}
//Bad:
//malloc(sizeof(char *) * 5) // Will allocate 20 or 40 bytes depending on 32 63 bit system
//Good:
// malloc(sizeof(char) * 5) // Will allocate 5 bytes
//http://stackoverflow.com/questions/1912325/checking-for-null-before-calling-free
//https://groups.google.com/forum/#!topic/comp.os.ms-windows.programmer.win32/L7o1PeransU
//if (findPathW) free (findPathW); //can't see why this is needed
}
LRESULT CALLBACK RescheckWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProcW(hwnd, uMsg, wParam, lParam);
//temp windowfor res check.
}
LRESULT CALLBACK ValidateProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
wchar_t chChar;
switch (message)
{
case WM_CHAR:
chChar = (wchar_t) wParam;
if(wcschr(invalidPathName, chChar)) return 0;
break;
}
return CallWindowProcW (g_pOldProc, hwnd, message, wParam, lParam);
}
INT_PTR CALLBACK APP_CLASS::s_DlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
APP_CLASS *pThis; // our "this" pointer will go here
if (uMsg == WM_INITDIALOG)
{
// Recover the "this" pointer which was passed as the last parameter to the ...Dialog...Param function.
pThis = reinterpret_cast<APP_CLASS*>(lParam);
// Put the value in a safe place for future use
SetWindowLongPtrW(hwnd, DWLP_USER, reinterpret_cast<LONG_PTR>(pThis));
}
else
{
// Recover the "this" pointer from where our WM_INITDIALOG handler stashed it.
pThis = reinterpret_cast<APP_CLASS*>( GetWindowLongPtrW(hwnd, DWLP_USER));
}
if (pThis)
{
// Now that we have recovered our "this" pointer, let the member function finish the job.
return pThis->DlgProc(hwnd, uMsg, wParam, lParam);
}
// We don't know what our "this" pointer is, so just do the default thing. Hopefully, we didn't need to customize the behavior yet.
return FALSE; // returning FALSE means "do the default thing"
}
INT_PTR APP_CLASS::DlgProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
errCode = 0;
switch(Msg)
{
case WM_INITDIALOG:
{
hMutex = CreateMutexW( nullptr, TRUE, L"BiggerDirectories.exe" );
if (hMutex)
{
DWORD wait_success = WaitForSingleObject (hMutex, 30 );
if (wait_success == WAIT_OBJECT_0 || wait_success == WAIT_ABANDONED)
{
// Our thread got ownership of the mutex or the other thread closed without releasing its mutex.
if (pCmdLineActive)
{
secondTryDelete = true;
currPathW = (wchar_t *)calloc(pathLength, sizeof(wchar_t));
currPath = (char*)calloc(pathLength, sizeof(char));
if (currPathW == nullptr || currPath== nullptr )
{
errCode = -1;
DisplayError (hwnd, L"Could not allocate required memory to initialize String", errCode, 0);
_CrtDumpMemoryLeaks();
EndDialog(hwnd, 1);
}
InitProc (hwnd);
SendDlgItemMessage(hwnd, IDC_LIST, LB_RESETCONTENT, 0, 0);
if (currPathW) free(currPathW);
if (currPath) free(currPath);
FRDeleteInit (hwnd, nullptr);
if (rootDir[0] != L'\0') rootDir[0] = L'\0';
}
currPathW = (wchar_t *)calloc(pathLength, sizeof(wchar_t));
currPath = (char*)calloc(pathLength, sizeof(char));
if (currPathW == nullptr || currPath== nullptr )
{
errCode = -1;
DisplayError (hwnd, L"Could not allocate required memory to initialize String", errCode, 0);
_CrtDumpMemoryLeaks();
EndDialog(hwnd, 1);
}
InitProc (hwnd);
HWND TextValidate = GetDlgItem(hwnd, IDC_TEXT);
// Subclass the Edit control with ValidateProc
g_pOldProc = (WNDPROC)SetWindowLongW(TextValidate, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(ValidateProc));
switch (errCode)
{
case 1:
{
/* And exit */
_CrtDumpMemoryLeaks();
EndDialog(hwnd, 1);
//exit(EXIT_FAILURE); //Not recommended: http://stackoverflow.com/questions/7562335/what-is-the-correct-way-to-programmatically-quit-an-mfc-application
}
break;
case 2:
{
_CrtDumpMemoryLeaks();
EndDialog(hwnd, 1);
}
break;
case 3:
{
_CrtDumpMemoryLeaks();
EndDialog(hwnd, 1);
}
break;
default:
{}
break;
}
if (!ReleaseMutex (hMutex)) ErrorExit (L"ReleaseMutex: Handle error. ", 1);
}
else
{
if (WAIT_TIMEOUT && !pCmdLineActive)
{
DisplayError (hwnd, L"One instance is already running", errCode, 0);
CloseHandle (hMutex);
_CrtDumpMemoryLeaks();
ExitProcess(1);
}
}
}
else
{
DisplayError (hwnd, L"Could not create hMutex", errCode, 0);
CloseHandle (hMutex);
_CrtDumpMemoryLeaks();
ExitProcess(1);
}
if (IsWindowsVistaOrGreater())
{
if (!(ChangeWindowMsgFilterEx(hwnd, WM_DROPFILES) && ChangeWindowMsgFilterEx(hwnd, WM_COPYDATA) && ChangeWindowMsgFilterEx(hwnd, WM_COPYGLOBALDATA)))
{
DisplayError (hwnd, L"ChangeWindowMsgFilterEx: Could not allow message", errCode, 0);
}
}
if (currPathW) free(currPathW);
if (currPath) free(currPath);
}
break;
case WM_COMMAND: //RH command keys
switch(LOWORD(wParam))
{
case IDC_TEXT:
{
//validation done elsewhere //check out WM_GETDLGCODE
}
break;
case IDC_NUMBER:
{
//no greater than treeLevelLimit
BOOL bSuccess;
HWND hList = GetDlgItem(hwnd, IDC_LIST);
listTotal = SendMessageW(hList, LB_GETCOUNT, 0, 0);
int nTimes = GetDlgItemInt(hwnd, IDC_NUMBER, &bSuccess, FALSE);
if (bSuccess)
{
if (nTimes > maxDWORD - listTotal)
{
if (nTimes - listTotal > treeLevelLimit)
{
SetDlgItemInt(hwnd, IDC_NUMBER, (UINT)(treeLevelLimit -1), FALSE);
}
else
{
SetDlgItemInt(hwnd, IDC_NUMBER, (UINT)( nTimes - listTotal), FALSE);
}
}
}
}
break;
case IDC_ADD: //adds directories nested ntimes
{
//http://www.experts-exchange.com/Programming/Languages/.NET/Visual_CPP/Q_27207428.html
//On the first call of IDC_ADD change text & button enables.
int len;
wchar_t* buf;
int nTimes;
HWND hList = GetDlgItem(hwnd, IDC_LIST);
listTotal = SendMessageW(hList, LB_GETCOUNT, 0, 0);
currPathW = (wchar_t *)calloc(pathLength, sizeof(wchar_t));
if (currPathW == nullptr)
{
/* We were not so display a message */
errCode = -1;
DisplayError (hwnd, L"Could not allocate required memory", errCode, 0);
goto NoAddSuccess;
}
SetDlgItemTextW(hwnd,IDC_STATIC_TWO, L"This entry is repeated");
SetDlgItemTextW(hwnd,IDC_STATIC_THREE, L"times.");
BOOL bSuccess;
nTimes = GetDlgItemInt(hwnd, IDC_NUMBER, &bSuccess, FALSE);
if(bSuccess)
{
//Allocate memory (2* +1 for two words > long)
len = (GetWindowTextLength(GetDlgItem(hwnd, IDC_TEXT))); //wchar
if(len > 0)
{
wchar_t *buf1 = (wchar_t *)calloc(2 * len + 1, sizeof(wchar_t));
GetDlgItemTextW(hwnd, IDC_TEXT, buf1, 2 * len + 1);
bool allPeriods = true;
//validation for terminating space & period
for (i = len - 1; i >= 0; i--)
{
if (wcsncmp(&buf1[i], L". ", 1))
{
allPeriods = false;
}
}
if (allPeriods)
{
free(buf1);
goto NoAddSuccess;
}
else
{
for (i = len - 1; i >= 0; i--)
{
if (!(wcsncmp(&buf1[i], L" ", 1)) || !(wcsncmp(&buf1[i], L".", 1)))
{
wcscpy_s(&buf1[i], i, L"\0");
SetDlgItemTextW(hwnd, IDC_TEXT, (wchar_t*)(buf1));
}
else
{
break; //all good
}
}
}
free(buf1);
}
len = 2 * (GetWindowTextLength(GetDlgItem(hwnd, IDC_TEXT)) + 1); //wchar again
if(len > 0)
{
buf = (wchar_t*)GlobalAlloc(GPTR, len );
GetDlgItemTextW(hwnd, IDC_TEXT, buf, len);
// Now we add the string to the list box however many times user asked us to.
for(i = 0 ; i < nTimes; i++)
{
if ( i * len < pathLength)
{
sendMessageErr = SendDlgItemMessageW(hwnd, IDC_LIST, LB_ADDSTRING, 0, (LPARAM)buf);
sendMessageErr = SendDlgItemMessageW(hwnd, IDC_LIST, LB_SETITEMDATA, (WPARAM)sendMessageErr, (LPARAM)nTimes);
}
else
{
DisplayError (hwnd, L"32k Limit reached", errCode, 0);
break;
}
}
GlobalFree((HANDLE)buf);
sendMessageErr = SendDlgItemMessageW(hwnd, IDC_LIST, LB_SETSEL, (WPARAM)FALSE, (LPARAM)(-1));
SetDlgItemInt(hwnd, IDC_SHOWCOUNT, nTimes, FALSE);
}
else
{
errCode = 0;
DisplayError (hwnd, L"You didn't enter anything", errCode, 0);
goto NoAddSuccess;
}
}
else
{
errCode = 0;
DisplayError (hwnd, L"Couldn't translate that number", errCode, 0);
goto NoAddSuccess;
}
if (foundNTDLL)
{
//update branchTotal: always 0 for the first branch
//populate after the save file contents
if (branchTotal < branchLimit)
{
branchTotal +=1;
}
else
{
DisplayError (hwnd, L"Limit of number of directories reached. Cannot create anymore", errCode, 0);
goto NoAddSuccess;
}
(branchLevelClick) ? EnableWindow(GetDlgItem(hwnd, IDC_DOWN), true) : EnableWindow(GetDlgItem(hwnd, IDC_DOWN), false);
//next add is always at base
EnableWindow(GetDlgItem(hwnd, IDC_UP), true);
hList = GetDlgItem(hwnd, IDC_LIST);
listTotal = SendMessageW(hList, LB_GETCOUNT, 0, 0);
currPathW[0] = L'\0';
branchLevel = 0;
//check on bounds
for (i = rootFolderCS + rootFolderCW + branchLevelCum; i < listTotal; i++)
{
if (branchLevelClick + branchLevel < treeLevelLimit)
{
sendMessageErr = SendMessageW(hList, LB_GETTEXT, i, (LPARAM)currPathW);
wcscpy_s(folderTreeArray[branchTotal][branchLevelClick + branchLevel], maxPathFolder, (wchar_t *) currPathW); //branchLevelClickOld can be neg?
branchLevel += 1;
}
else
{
DisplayError (hwnd, L"Limit of number of nested directories reached. Cannot create anymore", errCode, 0);
goto NoAddSuccess;
}
}
//clear redundant branches
for (j = branchLevelClick + branchLevel; j <= treeLevelLimit; j++)
{
folderTreeArray[branchTotal][j][0] = L'\0';
}
//save branchLevelClickOld & branchLevel
trackFTA [branchTotal][0] = branchLevelClick;
trackFTA [branchTotal][1] = branchLevel; //the sum of these is total no of backslashes for validation
branchLevelClickOld = branchLevelClick;
for (j = 0; j <= branchLevelClick + branchLevel; j++)
{
//branchTotal's next iteration only
wcscpy_s(folderTreeArray[branchTotal + 1][j], maxPathFolder, folderTreeArray[branchTotal][j]); //populate the entire string
}
branchLevelCum += branchLevel; //number of items added to list
}
else
{
DisplayError (hwnd, L"NTDLL not found: Only a nested path on a single branch is made with CREATE.", errCode, 0);
EnableWindow(GetDlgItem(hwnd, IDC_UP), false);
EnableWindow(GetDlgItem(hwnd, IDC_DOWN), false);
}
removeButtonEnabled = false;
EnableWindow(GetDlgItem(hwnd, IDC_REMOVE), removeButtonEnabled);
NoAddSuccess:
free (currPathW);
EnableWindow(GetDlgItem(hwnd, IDC_CREATE), true);
}
break;
case IDC_UP: //adds directories nested ntimes
//rule is cannot go back up a tree once we have branched.
{
//check validity with branchLevelClickOld + branchLevel and grey out
SetWindowTextW(GetDlgItem(hwnd, IDC_REMOVE), L"Del Line\0");
branchLevelClick +=1;
branchLevelIncCum = 0;
HWND hList = GetDlgItem(hwnd, IDC_LIST);