summaryrefslogtreecommitdiff
path: root/plugins/MirandaNGHistoryToDB/HistoryToDBUpdater/Global.pas
blob: f3f68e7ea238fea4966ef840c654a14dde4eb238 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
{ ################################################################################ }
{ #                                                                              # }
{ #  Îáíîâëåíèå è óñòàíîâêà íàáîðà ïðîãðàìì IM-History - HistoryToDBUpdater v1.0 # }
{ #                                                                              # }
{ #  License: GPLv3                                                              # }
{ #                                                                              # }
{ #  Author: Grigorev Michael (icq: 161867489, email: sleuthhound@gmail.com)     # }
{ #                                                                              # }
{ ################################################################################ }

unit Global;

{$I jedi.inc}

interface

uses
  Windows, Forms, Classes, SysUtils, IniFiles, DCPcrypt2, DCPblockciphers, DCPsha1,
  DCPdes, DCPmd5, TypInfo, Messages, XMLIntf, XMLDoc, StrUtils, Types, TLHELP32, PsAPI, NTNative;

type
  TWinVersion = (wvUnknown,wv95,wv98,wvME,wvNT3,wvNT4,wvW2K,wvXP,wv2003,wvVista,wv7,wv2008,wv8);
  TCopyDataType = (cdtString = 0, cdtImage = 1, cdtRecord = 2);
  TDelim = set of Char;
  TArrayOfString = Array of String;
  TArrayOfCardinal = Array of Cardinal;
  TProcessInfo = packed record
    ProcessName: String;
    PID: DWord;
    ProcessFullCmd: String;
    ProcessPath: String;
    ProcessParamCmd: String;
  end;
  TProcessInfoArray = Array of TProcessInfo;

const
  ProgramsName = 'HistoryToDBUpdater';
  ProgramsVer : WideString = '2.5.0.0';
  DefaultDBAddres = 'db01.im-history.ru';
  DefaultDBName = 'imhistory';
  ININame = 'HistoryToDB.ini';
  ErrLogName = 'HistoryToDBUpdaterErr.log';
  DebugLogName = 'HistoryToDBUpdaterDebug.log';
  // Íà÷àëüíàÿ äàòà (01/01/1970) Unix Timestamp äëÿ ôóíêöèé êîíâåðòàöèè
  UnixStartDate: TDateTime = 25569.0;
  // Êëþ÷ü äëÿ ðàñøèôðîâêè ïàðàìåòðà DBPasswd èç êîíôèãà
  EncryptKey = 'jsU6s2msoxghsKsn7';
  // Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
  WM_LANGUAGECHANGED = WM_USER + 1;
  dirLangs = 'langs\';
  dirSQLUpdate = 'update\';
  defaultLangFile = 'English.xml';
  // End
  WM_MSGBOX = WM_USER + 2;
  uURL = 'http://im-history.ru/update/get.php?file=HistoryToDB-Update';
  {$IFDEF WIN32}
  PlatformType = 'x86';
  {$ELSE}
  PlatformType = 'x64';
  {$ENDIF}
var
  WriteErrLog: Boolean;
  EnableDebug, AlphaBlendEnable: Boolean;
  MaxErrLogSize, AlphaBlendEnableValue: Integer;
  DBType, DefaultLanguage, IMClientType: String;
  PluginPath, ProfilePath: WideString;
  Global_MainForm_Showing, Global_AboutForm_Showing: Boolean;
  Global_IMProcessPID: DWORD;
  // Ïðîêñè
  IMUseProxy, IMProxyAuth: Boolean;
  IMProxyAddress, IMProxyPort, IMProxyUser, IMProxyUserPagsswd: String;
  DBUserName, MyAccount: String;
  IMClientPlatformType: String;
  UpdateServer: String;
  // Øèôðîâàíèå
  Cipher: TDCP_3des;
  Digest: Array[0..19] of Byte;
  Hash: TDCP_sha1;
  // Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
  CoreLanguage: String;
  MainFormHandle: HWND;
  AboutFormHandle: HWND;
  LangDoc: IXMLDocument;

function BoolToIntStr(Bool: Boolean): String;
function IsNumber(const S: String): Boolean;
function DateTimeToUnix(ConvDate: TDateTime): Longint;
function UnixToDateTime(USec: Longint): TDateTime;
function PrepareString(const Source : PWideChar) : AnsiString;
function EncryptStr(const Str: String): String;
function DecryptStr(const Str: String): String;
function EncryptMD5(Str: String): String;
function MatchStrings(source, pattern: String): Boolean;
function ExtractFileNameEx(FileName: String; ShowExtension: Boolean): String;
function ReadCustomINI(INIPath, CustomSection, CustomParams, DefaultParamsStr: String): String;
function GetSystemDefaultUILanguage: UINT; stdcall; external kernel32 name 'GetSystemDefaultUILanguage';
function GetSysLang: AnsiString;
function Tok(Sep: String; var S: String): String;
function GetMyFileSize(const Path: String): Integer;
function SearchMainWindow(MainWindowName: pWideChar): Boolean;
function StrContactProtoToInt(Proto: AnsiString): Integer;
function IsProcessRun(ProcessName: String): Boolean; overload;
function IsProcessRun(ProcessName, WinCaption: String): Boolean; overload;
function GetProcessID(ExeFileName: String): Cardinal;
//function GetProcessIDMulti(ExeFileName: String): TArrayOfString;
function GetProcessIDMulti2(ExeFileName: String): TArrayOfCardinal;
function GetThreadsOfProcess(APID: Cardinal): TIntegerDynArray;
function KillTask(ExeFileName: String): Integer; overload;
function KillTask(ExeFileName, WinCaption: String): Integer; overload;
function ProcessTerminate(dwPID: Cardinal): Boolean;
function ProcCloseEnum(hwnd: THandle; data: Pointer):BOOL;stdcall;
function ProcQuitEnum(hwnd: THandle; data: Pointer):BOOL;stdcall;
function GetProcessFileName(PID: DWord; FullPath: Boolean=True): String;
function GetProcessCmdLine(dwProcessId : DWORD): String;
function SetProcessDebugPrivelege: Boolean;
function EndProcess(IMClientExeName: String; EndType: Integer; EndProcess: Boolean): TProcessInfoArray;
function GetUserTempPath: WideString;
//function ProcGetCaptionForHandleEnum(hwnd: THandle; data: Pointer):BOOL;stdcall;
function EnumThreadWndProc(hwnd: HWND; lParam: LPARAM): BOOL; stdcall;
function StringToParts(sString:String; tdDelim:TDelim): TArrayOfString;
function ExtractWord(const AString: string; const ADelimiter: Char; const ANumber: integer): string;
procedure EncryptInit;
procedure EncryptFree;
procedure WriteInLog(LogPath: String; TextString: String; LogType: Integer);
procedure LoadINI(INIPath: String; NotSettingsForm: Boolean);
procedure WriteCustomINI(INIPath, CustomSection, CustomParams, ParamsStr: String);
procedure MakeTransp(winHWND: HWND);
procedure OnSendMessageToAllComponent(Msg: String);
procedure IMDelay(Value: Cardinal);
procedure OnSendMessageToOneComponent(WinName, Msg: String);
function DetectWinVersion: TWinVersion;
function DetectWinVersionStr: String;
// Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
procedure MsgDie(Caption, Msg: WideString);
procedure MsgInf(Caption, Msg: WideString);
function GetLangStr(StrID: String): WideString;

implementation

function BoolToIntStr(Bool: Boolean): String;
begin
  if Bool then
    Result := '1'
  else
    Result := '0'
end;

function IsNumber(const S: string): Boolean;
begin
  Result := True;
  try
    StrToInt(S);
  except
    Result := False;
  end;
end;

// Ôóíêöèÿ êîíâåðòàöèè DateTime â Unix Timestamp
function DateTimeToUnix(ConvDate: TDateTime): Longint;
begin
  Result := Round((ConvDate - UnixStartDate) * 86400);
end;

// Ôóíêöèÿ êîíâåðòàöèè Unix Timestamp â DateTime
function UnixToDateTime(USec: Longint): TDateTime;
begin
  Result := (Usec / 86400) + UnixStartDate;
end;

// Ôóíêöèÿ äëÿ ýêðàíèðîâàíèÿ ñïåöñèìâîëîâ â ñòðîêå
function PrepareString(const Source : PWideChar) : AnsiString;
var
  SLen,i : Cardinal;
  WSTmp : WideString;
  WChar : WideChar;
begin
 Result := '';
 SLen := Length(WideString(Source));
 if (SLen>0) then
  begin
   for i:=1 to SLen do
    begin
     WChar:=WideString(Source)[i];
     case WChar of
      #$09 :{tab}  WSTmp:=WSTmp+'\t';
      #$0A :{line feed}  WSTmp:=WSTmp+'\n';
      #$0D :{carriage return}  WSTmp:=WSTmp+'\r';
      #$27 :{single quote mark aka apostrophe?} WSTmp:=WSTmp+WChar+WChar;
      #$22, {double quote mark aka inch sign?}
      #$5C, {backslash itself}
      #$60 :{another single quote mark} WSTmp:=WSTmp+'\'+WChar;
      else WSTmp := WSTmp + WChar;
     end;
    end;
   Result := AnsiString(WSTmp);
  end;
end;

// Èíèöèèðóåì êðèïòîâàíèå
procedure EncryptInit;
begin
  Hash:= TDCP_sha1.Create(nil);
  try
    Hash.Init;
    Hash.UpdateStr(EncryptKey);
    Hash.Final(Digest);
  finally
    Hash.Free;
  end;
  Cipher := TDCP_3des.Create(nil);
  Cipher.Init(Digest,Sizeof(Digest)*8,nil);
end;

// Îñâîáîæäàåì ðåñóðñû
procedure EncryptFree;
begin
  if Assigned(Cipher) then
  begin
    Cipher.Burn;
    Cipher.Free;
  end;
end;

// Çàøèôðîâûâàåì ñòðîêó
function EncryptStr(const Str: String): String;
begin
  Result := '';
  if Str <> '' then
  begin
    Cipher.Reset;
    Result := Cipher.EncryptString(Str);
  end;
end;

// Ðàñøèôðîâûâàåì ñòðîêó
function DecryptStr(const Str: String): String;
begin
  Result := '';
  if Str <> '' then
  begin
    Cipher.Reset;
    Result := Cipher.DecryptString(Str);
  end;
end;

// Ïîäñ÷åò MD5 ñòðîêè
function EncryptMD5(Str: String): String;
var
  Hash: TDCP_md5;
  Digest: Array[0..15] of Byte;
  I: Integer;
  P: String;
begin
  if Str <> '' then
  begin
    Hash:= TDCP_md5.Create(nil);
    try
      Hash.HashSize := 128;
      Hash.Init;
      Hash.UpdateStr(Str);
      Hash.Final(Digest);
      P := '';
      for I:= 0 to 15 do
        P:= P + IntToHex(Digest[I], 2);
    finally
      Hash.Free;
    end;
    Result := P;
  end
  else
    Result := 'MD5';
end;

// LogType = 0 - îøèáêè äîáàâëÿþòñÿ â ôàéë ErrLogName
// LogType = 1 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë DebugLogName
procedure WriteInLog(LogPath: String; TextString: String; LogType: Integer);
var
  Path: WideString;
  TF: TextFile;
begin
  if LogType = 0 then
  begin
    Path := LogPath + ErrLogName;
    if (GetMyFileSize(Path) > MaxErrLogSize*1024) then
      DeleteFile(Path);
  end
  else
    Path := LogPath + DebugLogName;
  {$I-}
  try
    Assign(TF,Path);
    if FileExists(Path) then
      Append(TF)
    else
      Rewrite(TF);
    Writeln(TF,TextString);
    CloseFile(TF);
  except
    on e :
      Exception do
      begin
        CloseFile(TF);
        Exit;
      end;
  end;
  {$I+}
end;

// Çàãðóæàåì íàñòðîéêè
procedure LoadINI(INIPath: String; NotSettingsForm: Boolean);
var
  Path: WideString;
  Temp: String;
  INI: TIniFile;
begin
  // Ïðîâåðÿåì íàëè÷èå êàòàëîãà
  if not DirectoryExists(INIPath) then
    CreateDir(INIPath);
  Path := INIPath + ININame;
  if FileExists(Path) then
  begin
    INI := TIniFile.Create(Path);
    try
      DBType := INI.ReadString('Main', 'DBType', 'Unknown');
      DBUserName := INI.ReadString('Main', 'DBUserName', 'username');
      DefaultLanguage := INI.ReadString('Main', 'DefaultLanguage', 'English');
      IMClientType := INI.ReadString('Main', 'IMClientType', 'Unknown');
      MyAccount := INI.ReadString('Main', 'MyAccount', DBUserName);

      Temp := INI.ReadString('Main', 'WriteErrLog', '0');
      if Temp = '1' then WriteErrLog := True
      else WriteErrLog := False;

      MaxErrLogSize := INI.ReadInteger('Main', 'MaxErrLogSize', 20);

      Temp := INI.ReadString('Main', 'EnableDebug', '0');
      if Temp = '1' then EnableDebug := True
      else EnableDebug := False;

      Temp := INI.ReadString('Main', 'AlphaBlend', '0');
      if Temp = '1' then AlphaBlendEnable := True
      else AlphaBlendEnable := False;
      AlphaBlendEnableValue := INI.ReadInteger('Main', 'AlphaBlendValue', 255);

      Temp := INI.ReadString('Proxy', 'UseProxy', '0');
      if Temp = '1' then IMUseProxy := True
      else IMUseProxy := False;

      IMProxyAddress := INI.ReadString('Proxy', 'ProxyAddress', '127.0.0.1');
      IMProxyPort := INI.ReadString('Proxy', 'ProxyPort', '3128');

      Temp := INI.ReadString('Proxy', 'ProxyAuth', '0');
      if Temp = '1' then IMProxyAuth := True
      else IMProxyAuth := False;

      IMProxyUser := INI.ReadString('Proxy', 'ProxyUser', '');
      IMProxyUserPagsswd := INI.ReadString('Proxy', 'ProxyUserPasswd', '');
      if IMProxyUserPagsswd <> '' then
        IMProxyUserPagsswd := DecryptStr(IMProxyUserPagsswd);

      IMClientPlatformType := INI.ReadString('Main', 'IMClientPlatformType', PlatformType);
      UpdateServer := INI.ReadString('Updater', 'UpdateServer', uURL);
    finally
      INI.Free;
    end;
  end
  else
  begin
    INI := TIniFile.Create(path);
    try
      // Çíà÷åíèÿ ïî-óìîë÷àíèþ
      DBType := 'Unknown';
      DefaultLanguage := 'English';
      IMClientType := 'Unknown';
      WriteErrLog := True;
      MaxErrLogSize := 20;
      EnableDebug := False;
      AlphaBlendEnable := False;
      AlphaBlendEnableValue := 255;
      IMUseProxy := False;
      IMProxyAddress := '127.0.0.1';
      IMProxyPort := '3128';
      IMProxyAuth := False;
      IMProxyUser := '';
      IMProxyUserPagsswd := '';
      // Ñîõðàíÿåì íàñòðîéêè
      INI.WriteString('Main', 'DBType', DBType);
      INI.WriteString('Main', 'DefaultLanguage', DefaultLanguage);
      INI.WriteString('Main', 'IMClientType', IMClientType);
      INI.WriteString('Main', 'WriteErrLog', BoolToIntStr(WriteErrLog));
      INI.WriteInteger('Main', 'MaxErrLogSize', MaxErrLogSize);
      INI.WriteString('Main', 'EnableDebug', BoolToIntStr(EnableDebug));
      INI.WriteString('Main', 'AlphaBlend', BoolToIntStr(AlphaBlendEnable));
      INI.WriteInteger('Main', 'AlphaBlendValue', AlphaBlendEnableValue);
      INI.WriteString('Proxy', 'UseProxy', BoolToIntStr(IMUseProxy));
      INI.WriteString('Proxy', 'ProxyAddress', IMProxyAddress);
      INI.WriteString('Proxy', 'ProxyPort', IMProxyPort);
      INI.WriteString('Proxy', 'ProxyAuth', BoolToIntStr(IMProxyAuth));
      INI.WriteString('Proxy', 'ProxyUser', IMProxyUser);
      INI.WriteString('Proxy', 'ProxyUserPasswd', IMProxyUserPagsswd);
      INI.WriteString('Updater', 'UpdateServer', uURL);
    finally
      INI.Free;
    end;
  end;
end;

{Ôóíêöèÿ îñóùåñòâëÿåò ñðàâíåíèå äâóõ ñòðîê. Ïåðâàÿ ñòðîêà
ìîæåò áûòü ëþáîé, íî îíà íå äîëæíà ñîäåðæàòü ñèìâîëîâ ñîîòâåòñòâèÿ (* è ?).
Ñòðîêà ïîèñêà (èñêîìûé îáðàç) ìîæåò ñîäåðæàòü àáñîëþòíî ëþáûå ñèìâîëû.
Äëÿ ïðèìåðà: MatchStrings('David Stidolph','*St*') âîçâðàòèò True.
Àâòîð îðèãèíàëüíîãî C-êîäà Sean Stanley
Àâòîð ïîðòàöèè íà Delphi David Stidolph}
function MatchStrings(source, pattern: String): Boolean;
var
  pSource: array[0..255] of Char;
  pPattern: array[0..255] of Char;

  function MatchPattern(element, pattern: PChar): Boolean;

  function IsPatternWild(pattern: PChar): Boolean;
  begin
    Result := StrScan(pattern, '*') <> nil;
    if not Result then
      Result := StrScan(pattern, '?') <> nil;
  end;

  begin
    if 0 = StrComp(pattern, '*') then
      Result := True
    else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then
      Result := False
    else if element^ = Chr(0) then
      Result := True
    else
    begin
      case pattern^ of
        '*': if MatchPattern(element, @pattern[1]) then
            Result := True
          else
            Result := MatchPattern(@element[1], pattern);
        '?': Result := MatchPattern(@element[1], @pattern[1]);
      else
        if element^ = pattern^ then
          Result := MatchPattern(@element[1], @pattern[1])
        else
          Result := False;
      end;
    end;
  end;
begin
  StrPCopy(pSource, source);
  StrPCopy(pPattern, pattern);
  Result := MatchPattern(pSource, pPattern);
end;

{ Ôóíêöèÿ äëÿ ïîëó÷åíèÿ èìåíè ôàéëà èç ïóòè áåç èëè ñ åãî ðàñøèðåíèåì.
  Âîçâðàùàåò èìÿ ôàéëà, áåç èëè ñ åãî ðàñøèðåíèåì.
  Âõîäíûå ïàðàìåòðû:
  FileName - èìÿ ôàéëà, êîòîðîå íàäî îáðàáîòàòü
  ShowExtension - åñëè TRUE, òî ôóíêöèÿ âîçâðàòèò êîðîòêîå èìÿ ôàéëà
  (áåç ïîëíîãî ïóòè äîñòóïà ê íåìó), ñ ðàñøèðåíèåì ýòîãî ôàéëà, èíà÷å, âîçâðàòèò
  êîðîòêîå èìÿ ôàéëà, áåç ðàñøèðåíèÿ ýòîãî ôàéëà. }
function ExtractFileNameEx(FileName: String; ShowExtension: Boolean): String;
var
  I: Integer;
  S, S1: string;
begin
  I := Length(FileName);
  if I <> 0 then
  begin
    while (FileName[i] <> '\') and (i > 0) do
      i := i - 1;
    S := Copy(FileName, i + 1, Length(FileName) - i);
    i := Length(S);
    if i = 0 then
    begin
      Result := '';
      Exit;
    end;
    while (S[i] <> '.') and (i > 0) do
      i := i - 1;
    S1 := Copy(S, 1, i - 1);
    if s1 = '' then
      s1 := s;
    if ShowExtension = True then
      Result := s
    else
      Result := s1;
  end
  else
    Result := '';
end;

{ Ïðîçðà÷íîñòü îêíà MessageBox }
procedure MakeTransp(winHWND: HWND);
var
  exStyle: Longint;
begin
  exStyle := GetWindowLong(winHWND, GWL_EXSTYLE);
  if (exStyle and WS_EX_LAYERED = 0) then
  begin
    exStyle := exStyle or WS_EX_LAYERED;
    SetwindowLong(winHWND, GWL_EXSTYLE, exStyle);
  end;
  SetLayeredWindowAttributes(winHWND, 0, AlphaBlendEnableValue, LWA_ALPHA);
end;

// Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
procedure MsgDie(Caption, Msg: WideString);
begin
  if AlphaBlendEnable then
    PostMessage(GetForegroundWindow, WM_USER + 2, 0, 0);
  MessageBoxW(GetForegroundWindow, PWideChar(Msg), PWideChar(Caption), MB_ICONERROR);
end;

// Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
procedure MsgInf(Caption, Msg: WideString);
begin
  if AlphaBlendEnable then
    PostMessage(GetForegroundWindow, WM_USER + 2, 0, 0);
  MessageBoxW(GetForegroundWindow, PWideChar(Msg), PWideChar(Caption), MB_ICONINFORMATION);
end;

// Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
function GetLangStr(StrID: String): WideString;
begin
  if (not Assigned(LangDoc)) or (not LangDoc.Active) then
  begin
    Result := '';
    Exit;
  end;
  if LangDoc.ChildNodes['strings'].ChildNodes.FindNode(StrID) <> nil then
    Result := LangDoc.ChildNodes['strings'].ChildNodes[StrID].Text
  else
    Result := 'String not found.';
end;

function GetSysLang: AnsiString;
var
  WinLanguage: Array [0..50] of Char;
begin
  //Result := Lo(GetSystemDefaultUILanguage);
  VerLanguageName(GetSystemDefaultLangID, WinLanguage, 50);
  Result := StrPas(WinLanguage);
end;

{ Ôóíêöèÿ ðàçáèâàåò ñòðîêó S íà ñëîâà, ðàçäåëåííûå ñèìâîëàìè-ðàçäåëèòåëÿìè,
óêàçàííûìè â ñòðîêå Sep. Ôóíêöèÿ âîçâðàùàåò ïåðâîå íàéäåííîå ñëîâî, ïðè
ýòîì èç ñòðîêè S óäàëÿåòñÿ íà÷àëüíàÿ ÷àñòü äî ñëåäóþùåãî ñëîâà }
function Tok(Sep: String; var S: String): String;

  function isoneof(c, s: string): Boolean;
  var
    iTmp: integer;
  begin
    Result := False;
    for iTmp := 1 to Length(s) do
    begin
      if c = Copy(s, iTmp, 1) then
      begin
        Result := True;
        Exit;
      end;
    end;
  end;

var
  c, t: String;
begin
  if s = '' then
  begin
    Result := s;
    Exit;
  end;
  c := Copy(s, 1, 1);
  while isoneof(c, sep) do
  begin
    s := Copy(s, 2, Length(s) - 1);
    c := Copy(s, 1, 1);
  end;
  t := '';
  while (not isoneof(c, sep)) and (s <> '') do
  begin
    t := t + c;
    s := Copy(s, 2, length(s) - 1);
    c := Copy(s, 1, 1);
  end;
  Result := t;
end;

{ Ïðîöåäóðà çàïèñè çíà÷åíèÿ ïàðàìåòðà â ôàéë íàñòðîåê }
procedure WriteCustomINI(INIPath, CustomSection, CustomParams, ParamsStr: String);
var
  Path: String;
  IsFileClosed: Boolean;
  sFile: DWORD;
  INI: TIniFile;
begin
  Path := INIPath + ININame;
  if FileExists(Path) then
  begin
    // Æäåì ïîêà ôàéë îñâîáîäèò àíòèâèðü èëè åùå êàêàÿ-íèáóäü ãàäîñòü
    IsFileClosed := False;
    repeat
      sFile := CreateFile(PChar(Path),GENERIC_READ or GENERIC_WRITE,0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
      if (sFile <> INVALID_HANDLE_VALUE) then
      begin
        CloseHandle(sFile);
        IsFileClosed := True;
      end;
    until IsFileClosed;
    // End
    INI := TIniFile.Create(Path);
    try
      INI.WriteString(CustomSection, CustomParams, ParamsStr);
    finally
      INI.Free;
    end;
  end
  else
    MsgDie(ProgramsName, GetLangStr('SettingsErrSave'));
end;

{ Ôóíêöèÿ ÷òåíèÿ çíà÷åíèÿ ïàðàìåòðà èç ôàéëà íàñòðîåê }
function ReadCustomINI(INIPath, CustomSection, CustomParams, DefaultParamsStr: String): String;
var
  Path: String;
  INI: TIniFile;
begin
  Path := INIPath + ININame;
  INI := TIniFile.Create(Path);
  if FileExists(Path) then
  begin
    try
      Result := INI.ReadString(CustomSection, CustomParams, DefaultParamsStr);
    finally
      INI.Free;
    end;
  end
  else
    MsgDie(ProgramsName, GetLangStr('SettingsErrRead'));
end;

// Åñëè ôàéë íå ñóùåñòâóåò, òî âìåñòî ðàçìåðà ôàéëà ôóíêöèÿ âåðí¸ò -1
function GetMyFileSize(const Path: String): Integer;
var
  FD: TWin32FindData;
  FH: THandle;
begin
  FH := FindFirstFile(PChar(Path), FD);
  Result := 0;
  if FH = INVALID_HANDLE_VALUE then
    Exit;
  Result := FD.nFileSizeLow;
  if ((FD.nFileSizeLow and $80000000) <> 0) or
     (FD.nFileSizeHigh <> 0) then
    Result := -1;
  //FindClose(FH);
end;

{ Ïîèñê îêíà ïðîãðàììû }
function SearchMainWindow(MainWindowName: pWideChar): Boolean;
var
  HToDB: HWND;
begin
  // Èùåì îêíî
  HToDB := FindWindow(nil, MainWindowName);
  if HToDB <> 0 then
    Result := True
  else
    Result := False
end;

{ Ïðîöåäóðà äëÿ îòïðàâêè ñîîáùåíèé ïðîãðàììå }
{ Ñòàíäàðòíûå êîìàíäû:
  001  - Ïåðå÷èòàòü íàñòðîéêè èç ôàéëà HistoryToDB.ini
  002  - Ñèíõðîíèçàöèÿ èñòîðèè
  003  - Çàêðûòü âñå êîìïîíåíòû ïëàãèíà
  0040 - Ïîêàçàòü âñå îêíà ïëàãèíà (Ðåæèì AntiBoss)
  0041 - Ñêðûòü âñå îêíà ïëàãèíà (Ðåæèì AntiBoss)
  0050 - Çàïóñòèòü ïåðåðàñ÷åò MD5-õåøåé
  0051 - Çàïóñòèòü ïåðåðàñ÷åò MD5-õåøåé è óäàëåíèÿ äóáëèêàòîâ
  0060 - Çàïóùåí èìïîðò èñòîðèè
  0061 - Èìïîðò èñòîðèè çàâåðøåí
  007  - Îáíîâèòü êîíòàêò-ëèñò â ÁÄ
  008  - Ïîêàçàòü èñòîðèþ êîíòàêòà/÷àòà
         Ôîðìàò êîìàíäû:
           äëÿ èñòîðèè êîíòàêòà:
             008|0|UserID|UserName|ProtocolType
           äëÿ èñòîðèè ÷àòà:
             008|2|ChatName
  009 - Ýêñòðåííî çàêðûòü âñå êîìïîíåíòû ïëàãèíà.
}
procedure OnSendMessageToAllComponent(Msg: String);
var
  HToDB: HWND;
  copyDataStruct : TCopyDataStruct;
  EncryptMsg, WinName: String;
begin
  EncryptMsg := EncryptStr(Msg);
  WinName := 'HistoryToDBViewer for ' + IMClientType;
  // Èùåì îêíî HistoryToDBViewer è ïîñûëàåì åìó êîìàíäó
  HToDB := FindWindow(nil, pChar(WinName));
  if HToDB <> 0 then
  begin
    copyDataStruct.dwData := Integer(cdtString);
    copyDataStruct.cbData := 2*Length(EncryptMsg);
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, Integer(@copyDataStruct));
  end;
  WinName := 'HistoryToDBSync for ' + IMClientType;
  // Èùåì îêíî HistoryToDBSync è ïîñûëàåì åìó êîìàíäó
  HToDB := FindWindow(nil, pChar(WinName));
  if HToDB <> 0 then
  begin
    copyDataStruct.dwData := Integer(cdtString);
    copyDataStruct.cbData := 2*Length(EncryptMsg);
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, Integer(@copyDataStruct));
  end;
  WinName := 'HistoryToDBImport for ' + IMClientType;
  // Èùåì îêíî HistoryToDBImport è ïîñûëàåì åìó êîìàíäó
  HToDB := FindWindow(nil, pChar(WinName));
  if HToDB <> 0 then
  begin
    copyDataStruct.dwData := Integer(cdtString);
    copyDataStruct.cbData := 2*Length(EncryptMsg);
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, Integer(@copyDataStruct));
  end;
end;

procedure OnSendMessageToOneComponent(WinName, Msg: String);
var
  HToDB: HWND;
  copyDataStruct : TCopyDataStruct;
  EncryptMsg: String;
begin
  EncryptMsg := EncryptStr(Msg);
  // Èùåì îêíî HistoryToDBViewer è ïîñûëàåì åìó êîìàíäó
  HToDB := FindWindow(nil, pChar(WinName));
  if HToDB <> 0 then
  begin
    copyDataStruct.dwData := Integer(cdtString);
    copyDataStruct.cbData := 2*Length(EncryptMsg);
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, Integer(@copyDataStruct));
  end;
end;

function StrContactProtoToInt(Proto: AnsiString): Integer;
var
  ProtoType: Integer;
begin
  { Ïðîòîêîëû
    0 - ICQ
    1 - Google Talk
    2 - MRA
    3 - Jabber
    4 - QIP.Ru
    5 - Facebook
    6 - VKontacte
    7 - Twitter
    8 - Social (LiveJournal)
    9 - AIM
    10 - IRC
    11 - MSN
    12 - YAHOO
    13 - GADU
    14 - SKYPE
    15 - Unknown
  }
  if MatchStrings(LowerCase(Proto), 'icq*') then
    ProtoType := 0
  else if MatchStrings(LowerCase(Proto), 'google talk*') then
    ProtoType := 1
  else if MatchStrings(LowerCase(Proto), 'mra*') then
    ProtoType := 2
  else if MatchStrings(LowerCase(Proto), 'jabber*') then
    ProtoType := 3
  else if (LowerCase(Proto) = 'qip.ru') then
    ProtoType := 4
  else if MatchStrings(LowerCase(Proto), 'facebook*') then
    ProtoType := 5
  else if MatchStrings(LowerCase(Proto), 'vkontakte*') then
    ProtoType := 6
  else if MatchStrings(Proto, 'ÂÊîíòàêòå*') then
    ProtoType := 6
  else if MatchStrings(Proto, 'âêîíòàêòå*') then
    ProtoType := 6
  else if MatchStrings(LowerCase(Proto), 'twitter*') then
    ProtoType := 7
  else if MatchStrings(LowerCase(Proto), 'livejournal*') then
    ProtoType := 8
  else if MatchStrings(LowerCase(Proto), 'aim*') then
    ProtoType := 9
  else if MatchStrings(LowerCase(Proto), 'irc*') then
    ProtoType := 10
  else if MatchStrings(LowerCase(Proto), 'msn*') then
    ProtoType := 11
  else if MatchStrings(LowerCase(Proto), 'yahoo*') then
    ProtoType := 12
  else if MatchStrings(LowerCase(Proto), 'gadu*') then
    ProtoType := 13
  else if MatchStrings(LowerCase(Proto), 'skype*') then
    ProtoType := 14
  else
    ProtoType := 15;
  Result := ProtoType;
end;

{ Çàäåðæêà íå ãðóçÿùàÿ ïðîöåññîð }
procedure IMDelay(Value: Cardinal);
var
  F, N: Cardinal;
begin
  N := 0;
  while N <= (Value div 10) do
  begin
    SleepEx(1, True);
    Application.ProcessMessages;
    Inc(N);
  end;
  F := GetTickCount;
  repeat
    Application.ProcessMessages;
    N := GetTickCount;
  until (N - F >= (Value mod 10)) or (N < F);
end;

{ Çàêðûòèå ïðîãðàììû ÷åðåç WM_CLOSE ïî å¸ PID }
function ProcCloseEnum(hwnd: THandle; data: Pointer):BOOL;stdcall;
var
  Pid: DWORD;
begin
  Result := True;
  GetWindowThreadProcessId(hwnd, pid);
  if Pid = DWORD(data) then
  begin
    PostMessage(hwnd, WM_CLOSE, 0, 0);
  end;
end;

{ Çàêðûòèå ïðîãðàììû ÷åðåç WM_QUIT ïî å¸ PID }
function ProcQuitEnum(hwnd: THandle; data: Pointer):BOOL;stdcall;
var
  Pid: DWORD;
begin
  Result := True;
  GetWindowThreadProcessId(hwnd, pid);
  if Pid = DWORD(data) then
  begin
    PostMessage(hwnd, WM_QUIT, 0, 0);
  end;
end;

{function ProcGetCaptionForHandleEnum(hwnd: THandle; data: Pointer):BOOL;stdcall;
var
  Pid: DWORD;
  WinCaption: Array [0 .. 255] of Char;
begin
  Result := True;
  GetWindowThreadProcessId(hwnd, pid);
  if Pid = DWORD(data) then
  begin
    //PostMessage(hwnd, WM_QUIT, 0, 0);
    GetWindowText(hwnd, WinCaption, SizeOf(WinCaption));
    if WinCaption <> '' then
      MsgInf('ProcGetCaptionForHandleEnum', WinCaption);
  end;
end;}

{ Ôóíêöèÿ îòïðàâëÿåò WM_QUIT ïðîöåññó
  è âîçâðàùàåò TArrayOfString ñî ñïèñêîì ïîëíûõ ïóòåé + ïàðàìåòðû çàïóñêà
  ýòèõ ïðîöåññîâ
  EndType = 0 - WM_CLOSE
  EndType = 1 - WM_QUIT
   }
function EndProcess(IMClientExeName: String; EndType: Integer; EndProcess: Boolean): TProcessInfoArray;
var
  I: Integer;
  ProcessPIDListArray: TArrayOfCardinal;
  MyFullCMD, MyCMD, ProcessCmdLine: String;
begin
  SetLength(Result, 0);
  SetLength(ProcessPIDListArray, 0);
  ProcessPIDListArray := GetProcessIDMulti2(IMClientExeName);
  for I := 0 to High(ProcessPIDListArray) do
  begin
    SetLength(Result, Length(Result)+1);
    Result[Length(Result)-1].ProcessName := IMClientExeName;
    Result[Length(Result)-1].PID := ProcessPIDListArray[I];
    ProcessCmdLine := GetProcessCmdLine(ProcessPIDListArray[I]);
    if ProcessCmdLine = '' then
    begin

      if (IMClientExeName = 'qip.exe') and (DetectWinVersionStr = 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files\QIP 2012\qip.exe"'
      else if (IMClientExeName = 'qip.exe') and (DetectWinVersionStr <> 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files (x86)\QIP 2012\qip.exe"'

      else if (IMClientExeName = 'miranda32.exe') and (IMClientType = 'Miranda') and (DetectWinVersionStr = 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files\Miranda IM\miranda32.exe"'
      else if (IMClientExeName = 'miranda32.exe') and (IMClientType = 'Miranda') and (DetectWinVersionStr <> 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files (x86)\Miranda IM\miranda32.exe"'
      else if (IMClientExeName = 'miranda64.exe') and (IMClientType = 'Miranda') and (DetectWinVersionStr = 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files\Miranda IM\miranda32.exe"'
      else if (IMClientExeName = 'miranda64.exe') and (IMClientType = 'Miranda') and (DetectWinVersionStr <> 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files\Miranda IM\miranda32.exe"'

      else if (IMClientExeName = 'miranda32.exe') and (IMClientType = 'MirandaNG') and (DetectWinVersionStr = 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files\Miranda NG\miranda32.exe"'
      else if (IMClientExeName = 'miranda32.exe') and (IMClientType = 'MirandaNG') and (DetectWinVersionStr <> 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files (x86)\Miranda NG\miranda32.exe"'
      else if (IMClientExeName = 'miranda64.exe') and (IMClientType = 'MirandaNG') and (DetectWinVersionStr = 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files\Miranda NG\miranda32.exe"'
      else if (IMClientExeName = 'miranda64.exe') and (IMClientType = 'MirandaNG') and (DetectWinVersionStr <> 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files\Miranda NG\miranda32.exe"'

      else if (IMClientExeName = 'skype.exe') and (DetectWinVersionStr = 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files (x86)\Skype\Phone\skype.exe"'
      else if (IMClientExeName = 'skype.exe') and (DetectWinVersionStr <> 'Windows 7') then
        ProcessCmdLine := '"C:\Program Files\Skype\Phone\skype.exe"'
      else
        ProcessCmdLine := IMClientExeName;
    end;
    Result[Length(Result)-1].ProcessFullCmd := ProcessCmdLine;
    //MsgInf('EndProcess', 'ProcessName: ' + Result[Length(Result)-1].ProcessName + #13 + 'PID: ' + IntToStr(Result[Length(Result)-1].PID) + #13 + 'ProcessFullCmd: ' + Result[Length(Result)-1].ProcessFullCmd);
    //Result[Length(Result)-1] := GetProcessFileName(StrToInt(ProcessListArray[I]), True);
    // Åñëè â ïîëíîì CMD âèäà
    // "C:/Program Files/PostgreSQL/9.1/bin/postgres.exe" "--forklog" "244" "248"
    // èëè
    // "C:\Program Files\Microsoft Firewall Client 2004\FwcAgent.exe"
    if Result[Length(Result)-1].ProcessFullCmd[1] = '"' then
    begin
      MyFullCMD := Result[Length(Result)-1].ProcessFullCmd;
      Delete(MyFullCMD, 1, 1);
      MyCMD := Copy(MyFullCMD, 1, Pos('"', MyFullCMD)-1);
      Delete(MyFullCMD, 1, Pos('"', MyFullCMD)+1);
      Result[Length(Result)-1].ProcessPath := MyCMD;
      Result[Length(Result)-1].ProcessParamCmd := MyFullCMD;
    end
    else
    begin
      MyFullCMD := Result[Length(Result)-1].ProcessFullCmd;
      // Åñëè â ïîëíîì CMD âèäà
      // C:\WINDOWS\system32\svchost -k DcomLaunch
      if Pos(' ', MyFullCMD) > 0 then
      begin
        MyCMD := Copy(MyFullCMD, 1, Pos(' ', MyFullCMD)-1);
        Delete(MyFullCMD, 1, Pos(' ', MyFullCMD));
        Result[Length(Result)-1].ProcessPath := MyCMD;
        Result[Length(Result)-1].ProcessParamCmd := MyFullCMD;
      end
      // Åñëè â ïîëíîì CMD âèäà
      // C:\WINDOWS\system32\lsass.exe
      else
      begin
        Result[Length(Result)-1].ProcessPath := MyFullCMD;
        Result[Length(Result)-1].ProcessParamCmd := '';
      end;
    end;
    // Çàâåðøåíèå ïðîöåññà
    if EndProcess then
    begin
      if EndType = 0 then //WM_CLOSE
        EnumWindows(@ProcCloseEnum, ProcessPIDListArray[I])
      else //WM_QUIT
        EnumWindows(@ProcQuitEnum, ProcessPIDListArray[I]);
    end;
  end;
end;

function EnumThreadWndProc(hwnd: HWND; lParam: LPARAM): BOOL; stdcall;
var
  WindowClassName: String;
  WindowClassNameLength: Integer;
  WinCaption: Array [0 .. 255] of Char;
  ThreadProcessWinCaption: String;
  PID: DWORD;
begin
  Result := True;
  ThreadProcessWinCaption := String(LPARAM);
  GetWindowThreadProcessId(hwnd, pid);
  SetLength(WindowClassName, MAX_PATH);
  WindowClassNameLength := GetClassName(hwnd, PChar(WindowClassName), MAX_PATH);
  GetWindowText(hwnd, WinCaption, SizeOf(WinCaption));
  if MatchStrings(LeftStr(WindowClassName, WindowClassNameLength), 'TMain*') and (WinCaption = ThreadProcessWinCaption) then
  begin
    Global_IMProcessPID := PID;
    //MsgInf('EnumThreadWndProc', 'PID ïðîöåññà ðîäèòåëÿ: ' + IntToStr(PID) + #10#13 + 'Êëàññ: ' + LeftStr(WindowClassName, WindowClassNameLength) + #10#13 + 'Çàãîëîâîê îêíà: ' + WinCaption);
  end;
  // Ïîëó÷èì äî÷åðíèå îêíà.
  //EnumChildWindows(hwnd, @EnumThreadWndProc, lParam);
end;

{ Ïîëó÷åíèå ID âñåõ ïîòîêîâ óêàçàííîãî ïðîöåññà }
function GetThreadsOfProcess(APID: Cardinal): TIntegerDynArray;
var
 lSnap: DWord;
 lThread: TThreadEntry32;
begin
  Result := nil;
  if APID <> INVALID_HANDLE_VALUE then
  begin
    lSnap := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
    if (lSnap <> INVALID_HANDLE_VALUE) then
    begin
      lThread.dwSize := SizeOf(TThreadEntry32);
      if Thread32First(lSnap, lThread) then
      repeat
        if lThread.th32OwnerProcessID = APID then
        begin
          SetLength(Result, Length(Result) + 1);
          Result[High(Result)] := lThread.th32ThreadID;
        end;
      until not Thread32Next(lSnap, lThread);
      CloseHandle(lSnap);
    end;
  end;
end;

{ Ïðîâåðêà ïðîöåññà íà íàëè÷èå â ïàìÿòè ïî åãî èìåíè }
function IsProcessRun(ProcessName: String): Boolean; overload;
var
  Snapshot: THandle;
  Proc: TProcessEntry32;
begin
  Result := False;
  Snapshot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if Snapshot = INVALID_HANDLE_VALUE then
    Exit;
  Proc.dwSize := SizeOf(TProcessEntry32);
  if Process32First(Snapshot, Proc) then
  repeat
    if Proc.szExeFile = ProcessName then
    begin
      Result := True;
      Break;
    end;
  until not Process32Next(Snapshot, Proc);
  CloseHandle(Snapshot);
end;

function IsProcessRun(ProcessName, WinCaption: String): Boolean; overload;
var
  Snapshot: THandle;
  Proc: TProcessEntry32;
  lThreads: TIntegerDynArray;
  J: Integer;
begin
  Result := False;
  Snapshot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if Snapshot = INVALID_HANDLE_VALUE then
    Exit;
  Proc.dwSize := SizeOf(TProcessEntry32);
  if Process32First(Snapshot, Proc) then
  repeat
    if ((UpperCase(ExtractFileName(Proc.szExeFile)) = UpperCase(ProcessName))
     or (UpperCase(Proc.szExeFile) = UpperCase(ProcessName))) then
     begin
      // Ïîëó÷åíèå Çàãîëîâêîâ îêîí ïðîöåññà
      //EnumWindows(@ProcGetCaptionForHandleEnum, FProcessEntry32.th32ProcessID);
      // Ïîëó÷åíèå ClassName è Çàãîëîâêîâ îêîí âñåõ ïîòîêîâ ïðîöåññà
      Global_IMProcessPID := 0;
      lThreads := GetThreadsOfProcess(Proc.th32ProcessID);
      for J := Low(lThreads) to High(lThreads) do
        EnumThreadWindows(lThreads[J], @EnumThreadWndProc, LPARAM(WinCaption));
      if Global_IMProcessPID = Proc.th32ProcessID then
        //MsgInf('IsProcessRun', 'Íàéäåí íóæíûé ïðîöåññ');
        Result := True;
      // Ends
     end;
  until not Process32Next(Snapshot, Proc);
  CloseHandle(Snapshot);
end;

{ Çàâåðøåíèå ïðîöåññà ïî èìåíè }
function KillTask(ExeFileName: String): Integer;
const
  PROCESS_TERMINATE=$0001;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
begin
  Result := 0;
  FSnapshotHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
  while Integer(ContinueLoop) <> 0 do
  begin
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName))
     or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then
      Result := Integer(TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0),
                        FProcessEntry32.th32ProcessID), 0));
    ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  end;
  CloseHandle(FSnapshotHandle);
end;

{ Çàâåðøåíèå ïðîöåññà ïî èìåíè è çàãîëîâêó îêíà }
function KillTask(ExeFileName, WinCaption: String): Integer; overload;
const
  PROCESS_TERMINATE=$0001;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
  lThreads: TIntegerDynArray;
  J: Integer;
begin
  Result := 0;
  FSnapshotHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
  while Integer(ContinueLoop) <> 0 do
  begin
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName))
     or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then
     begin
      // Ïîëó÷åíèå Çàãîëîâêîâ îêîí ïðîöåññà
      //EnumWindows(@ProcGetCaptionForHandleEnum, FProcessEntry32.th32ProcessID);
      // Ïîëó÷åíèå ClassName è Çàãîëîâêîâ îêîí âñåõ ïîòîêîâ ïðîöåññà
      Global_IMProcessPID := 0;
      lThreads := GetThreadsOfProcess(FProcessEntry32.th32ProcessID);
      for J := Low(lThreads) to High(lThreads) do
        EnumThreadWindows(lThreads[J], @EnumThreadWndProc, LPARAM(WinCaption));
      if Global_IMProcessPID = FProcessEntry32.th32ProcessID then
        //MsgInf('KillTask', 'Íàéäåí íóæíûé ïðîöåññ');
        Result := Integer(TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), FProcessEntry32.th32ProcessID), 0));
      // Ends
     end;
    ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  end;
  CloseHandle(FSnapshotHandle);
end;

{ Ïîëó÷åíèå PID ïðîãðàììû â ïàìÿòè }
function GetProcessID(ExeFileName: String): Cardinal;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
begin
  Result := 0;
  FSnapshotHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
  repeat
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName))
       or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then
    begin
       Result := FProcessEntry32.th32ProcessID;
       Break;
    end;
    ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  until not ContinueLoop;
  CloseHandle(FSnapshotHandle);
end;

{ Ïîëó÷åíèå PID äëÿ íåñêîëüêèõ ïðîöåññîâ ñ îäèíàêîâûì èìåíåì }
{function GetProcessIDMulti(ExeFileName: String): TArrayOfString;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
begin
  SetLength(Result, 0);
  //Result := 0;
  FSnapshotHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
  repeat
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName))
       or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then
    begin
       SetLength(Result, Length(Result)+1);
       Result[Length(Result)-1] := IntToStr(FProcessEntry32.th32ProcessID);
    end;
    ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  until not ContinueLoop;
  CloseHandle(FSnapshotHandle);
end;}

{ Ïîëó÷åíèå PID äëÿ íåñêîëüêèõ ïðîöåññîâ ñ îäèíàêîâûì èìåíåì }
function GetProcessIDMulti2(ExeFileName: String): TArrayOfCardinal;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
begin
  SetLength(Result, 0);
  //Result := 0;
  FSnapshotHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
  repeat
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName))
       or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then
    begin
       SetLength(Result, Length(Result)+1);
       Result[Length(Result)-1] := FProcessEntry32.th32ProcessID;
    end;
    ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  until not ContinueLoop;
  CloseHandle(FSnapshotHandle);
end;

{ Ïîëó÷àåì ïîëíûé ïóòü äî ïðèëîæåíèÿ ïî åãî PID }
function GetProcessFileName(PID: DWord; FullPath: Boolean=True): String;
var
  Handle: THandle;
begin
  Result := '';
  Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID);
  try
    if Handle <> 0 then
    begin
      SetLength(Result, MAX_PATH);
      if FullPath then
      begin
        if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
          SetLength(Result, StrLen(PChar(Result)))
        else
          Result := '';
      end
      else
      begin
        if GetModuleBaseNameA(Handle, 0, PAnsiChar(Result), MAX_PATH) > 0 then
          SetLength(Result, StrLen(PChar(Result)))
        else
          Result := '';
      end;
    end;
  finally
    CloseHandle(Handle);
  end;
end;

{ Ïîëó÷àåì êîìàíäó çàïóñêà ïðîãðàììû ñ ïîëíûì ïóòåì ïî å¸ PID }
function GetProcessCmdLine(dwProcessId : DWORD): String;
const
  STATUS_SUCCESS             = $00000000;
  SE_DEBUG_NAME              = 'SeDebugPrivilege';
  ProcessWow64Information    = 26;
var
  ProcessHandle        : THandle;
  ProcessBasicInfo     : PROCESS_BASIC_INFORMATION;
  ReturnLength         : DWORD;
  lpNumberOfBytesRead  : ULONG_PTR;
  TokenHandle          : THandle;
  lpLuid               : TOKEN_PRIVILEGES;
  OldlpLuid            : TOKEN_PRIVILEGES;
  Rtl : RTL_USER_PROCESS_PARAMETERS;
  Peb : _PEB;
  IsProcessx64 : Boolean;
  {$IFDEF CPUX64}
  PEBBaseAddress32 : Pointer;
  Peb32 : _PEB32;
  Rtl32 : RTL_USER_PROCESS_PARAMETERS32;
  {$ENDIF}
  Ws: WideString;
begin
  Result:='';
  if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TokenHandle) then
  begin
    try
      if not LookupPrivilegeValue(nil, SE_DEBUG_NAME, lpLuid.Privileges[0].Luid) then
        RaiseLastOSError
      else
      begin
        lpLuid.PrivilegeCount := 1;
        lpLuid.Privileges[0].Attributes  := SE_PRIVILEGE_ENABLED;
        ReturnLength := 0;
        OldlpLuid    := lpLuid;
        // Âêëþ÷àåì ñåáå SeDebugPrivilege
        if not AdjustTokenPrivileges(TokenHandle, False, lpLuid, SizeOf(OldlpLuid), OldlpLuid, ReturnLength) then RaiseLastOSError;
      end;

      ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, dwProcessId);
      if ProcessHandle = 0 then RaiseLastOSError
      else
      try
        IsProcessx64 := ProcessIsX64(ProcessHandle);

        {$IFNDEF CPUX64}
        if IsProcessx64 then
          raise Exception.Create('Only 32 bits processes are supported');
        {$ENDIF}

        {$IFDEF CPUX64}
        if IsProcessx64 then
        begin
        {$ENDIF}
          // Ïîëó÷àåì äîñòóï ê PROCESS_BASIC_INFORMATION ïî àäðåñó PEB
          if (NtQueryInformationProcess(ProcessHandle,0{=>ProcessBasicInformation},@ProcessBasicInfo, SizeOf(ProcessBasicInfo), @ReturnLength)=STATUS_SUCCESS) and (ReturnLength=SizeOf(ProcessBasicInfo)) then
          begin
            // ×èòàåì PEB ñòðóêòóðó
            if not ReadProcessMemory(ProcessHandle, ProcessBasicInfo.PEBBaseAddress, @Peb, sizeof(Peb), lpNumberOfBytesRead) then
              RaiseLastOSError
            else
            begin
              // ×èòàåì RTL_USER_PROCESS_PARAMETERS ñòðóêòóðó
              if not ReadProcessMemory(ProcessHandle, Peb.ProcessParameters, @Rtl, SizeOf(Rtl), lpNumberOfBytesRead) then
               RaiseLastOSError
              else
              begin
                SetLength(ws,(Rtl.CommandLine.Length div 2));
                if not ReadProcessMemory(ProcessHandle,Rtl.CommandLine.Buffer,PWideChar(ws),Rtl.CommandLine.Length,lpNumberOfBytesRead) then
                  RaiseLastOSError
                else
                  Result := String(ws);
              end;
            end;
          end
          else
          RaiseLastOSError;
        {$IFDEF CPUX64}
        end
        else
        begin
          // Ïîëó÷àåì PEB àäðåñ
          if  NtQueryInformationProcess(ProcessHandle, ProcessWow64Information, @PEBBaseAddress32, SizeOf(PEBBaseAddress32), nil)=STATUS_SUCCESS then
          begin
            // ×èòàåì PEB ñòðóêòóðó
            if not ReadProcessMemory(ProcessHandle, PEBBaseAddress32, @Peb32, sizeof(Peb32), lpNumberOfBytesRead) then
              RaiseLastOSError
            else
            begin
              // ×èòàåì RTL_USER_PROCESS_PARAMETERS ñòðóêòóðó
              if not ReadProcessMemory(ProcessHandle, Pointer(Peb32.ProcessParameters), @Rtl32, SizeOf(Rtl32), lpNumberOfBytesRead) then
               RaiseLastOSError
              else
              begin
                SetLength(ws,(Rtl32.CommandLine.Length div 2));
                if not ReadProcessMemory(ProcessHandle, Pointer(Rtl32.CommandLine.Buffer), PWideChar(ws), Rtl32.CommandLine.Length, lpNumberOfBytesRead) then
                  RaiseLastOSError
                else
                  Result := String(Ws);
              end;
            end;
          end
          else
          RaiseLastOSError;
        end;
       {$ENDIF}
      finally
        CloseHandle(ProcessHandle);
      end;
    finally
      CloseHandle(TokenHandle);
    end;
  end
  else
  RaiseLastOSError;
end;

{ Âêëþ÷àåì ñåáå SeDebugPrivilege }
function SetProcessDebugPrivelege: Boolean;
var
  hToken: THandle;
  tp: TTokenPrivileges;
  rl: Cardinal;
begin
  Result := False;
  if not OpenProcessToken(GetCurrentProcess,TOKEN_ADJUST_PRIVILEGES,hToken) then
    Exit;
  try
    if not LookupPrivilegeValue(nil,'SeDebugPrivilege', tp.Privileges[0].Luid) then
      Exit;
    tp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
    tp.PrivilegeCount := 1;
    Result := AdjustTokenPrivileges(hToken,false,tp,0,nil,rl) and (GetLastError=0);
  finally
    CloseHandle(hToken);
  end
end;

// Çàâåðøåíèå ëþáûõ ïðîöåññîâ â òîì ÷èñëå ñèñòåìíûõ.
// Âêëþ÷åíèå, ïðèìèíåíèå è îòêëþ÷åíèÿ ïðèâèëåãèè.
// Äëÿ ïðèìåðà âîçüìåì ïðèâèëåãèþ îòëàäêè ïðèëîæåíèé 'SeDebugPrivilege'
// íåîáõîäèìóþ äëÿ çàâåðøåíèÿ ËÞÁÛÕ ïðîöåññîâ â ñèñòåìå (çàâåðøåíèå ïðîöåñîâ
// ñîçäàííûõ òåêóùèì ïîëüçîâàòåëåì ïðèâèëåãèÿ íå íóæíà.
// Íàçâàíèå äîáàâëåíèå/óäàëåíèå ïðèâèëãèè íåìíîãî íåïðàâèëüíûå.  Ïðèâèëåãèÿ èëè
// åñòü â òîêåíå ïðîöåññà èëè åå íåò. Åñëè ïðèâèëåãèÿ åñòü, òî îíà ìîæåò áûòü â
// äâóõ ñîñòîÿíèÿõ - èëè âêëþ÷åíàÿ èëè îòêëþ÷åíàÿ. È â ýòîì ïðèìåðå ìû òîëüêî
// âêëþ÷àåì èëè âûêëþ÷àåì íåîáõîäèìóþ ïðèâèëåãèþ, à íå äîáàâëÿåì åå.
function ProcessTerminate(dwPID: Cardinal): Boolean;
var
 hToken:THandle;
 SeDebugNameValue:Int64;
 tkp:TOKEN_PRIVILEGES;
 ReturnLength:Cardinal;
 hProcess:THandle;
begin
  Result := False;
  // Âêëþ÷àåì ïðèâèëåãèþ SeDebugPrivilege
  // Äëÿ íà÷àëà ïîëó÷àåì òîêåí íàøåãî ïðîöåññà
  if not OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken ) then
    Exit;
  // Ïîëó÷àåì LUID ïðèâèëåãèè
  if not LookupPrivilegeValue(nil, 'SeDebugPrivilege', SeDebugNameValue) then
  begin
    CloseHandle(hToken);
    Exit;
  end;
  tkp.PrivilegeCount := 1;
  tkp.Privileges[0].Luid := SeDebugNameValue;
  tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
  // Äîáàâëÿåì ïðèâèëåãèþ ê íàøåìó ïðîöåññó
  AdjustTokenPrivileges(hToken, False, tkp, SizeOf(tkp), tkp, ReturnLength);
  if GetLastError() <> ERROR_SUCCESS then
    Exit;
  // Çàâåðøàåì ïðîöåññ. Åñëè ó íàñ åñòü SeDebugPrivilege, òî ìû ìîæåì
  // çàâåðøèòü è ñèñòåìíûé ïðîöåññ
  // Ïîëó÷àåì äåñêðèïòîð ïðîöåññà äëÿ åãî çàâåðøåíèÿ
  hProcess := OpenProcess(PROCESS_TERMINATE, FALSE, dwPID);
  if hProcess = 0 then
    Exit;
  // Çàâåðøàåì ïðîöåññ
  if not TerminateProcess(hProcess, DWORD(-1)) then
    Exit;
  CloseHandle( hProcess );
  // Îòêëþ÷àåì ïðèâèëåãèþ
  tkp.Privileges[0].Attributes := 0;
  AdjustTokenPrivileges(hToken, FALSE, tkp, SizeOf(tkp), tkp, ReturnLength);
  if GetLastError() <> ERROR_SUCCESS then
    Exit;
  Result := True;
end;

function StringToParts(sString: String; tdDelim: TDelim): TArrayOfString;
var
  iCounter,iBegin:Integer;
begin
  if length(sString)>0 then
  begin
    include(tdDelim, #0);
    iBegin:=1;
    SetLength(Result, 0);
    for iCounter:=1 to Length(sString)+1 do
    begin
      if(sString[iCounter] in tdDelim) then
      begin
        SetLength(Result, Length(Result)+1);
        Result[Length(Result)-1] := Copy(sString, iBegin, iCounter-iBegin);
        iBegin := iCounter+1;
      end;
    end;
  end;
end;

{ Edit1.Text := ExtractWord(ExtractWord('admin:login:password', ':', 3)); //'password' }
function ExtractWord(const AString: string; const ADelimiter: Char; const ANumber: integer): string;
var
  i, j, k: integer;
begin
  i := 1;
  k := 1;
  while k <> ANumber do
  begin
    if AString[i] = ADelimiter then
    begin
      Inc(k);
    end;
    Inc(i);
  end;
  j := i + 1;
  while (j <= Length(AString)) and (AString[j] <> ADelimiter) do
    Inc(j);
  Result := Copy(AString, i, j - i);
end;

{ Ôóíêöèÿ âîçâðàùàåò ïóòü äî ïîëüçîâàòåëüñêîé âðåìåííîé ïàïêè }
function GetUserTempPath: WideString;
var
  UserPath: WideString;
begin
  Result := '';
  SetLength(UserPath, MAX_PATH);
  GetTempPath(MAX_PATH, PChar(UserPath));
  GetLongPathName(PChar(UserPath), PChar(UserPath), MAX_PATH);
  SetLength(UserPath, StrLen(PChar(UserPath)));
  Result := UserPath;
end;

{
DwMajorVersion:DWORD - ñòàðøàÿ öèôðà âåðñèè Windows

  Windows 95      - 4
   Windows 98      - 4
   Windows Me      - 4
   Windows NT 3.51 - 3
   Windows NT 4.0  - 4
   Windows 2000    - 5
   Windows XP      - 5

DwMinorVersion: DWORD - ìëàäøàÿ öèôðà âåðñèè

  Windows 95      - 0
   Windows 98      - 10
   Windows Me      - 90
   Windows NT 3.51 - 51
   Windows NT 4.0  - 0
   Windows 2000    - 0
   Windows XP      - 1


DwBuildNumber: DWORD
 Win NT 4 - íîìåð áèëäà
 Win 9x   - ñòàðøèé áàéò - ñòàðøàÿ è ìëàäøàÿ öèôðû âåðñèè / ìëàäøèé - íîìåð
áèëäà

dwPlatformId: DWORD

 VER_PLATFORM_WIN32s            Win32s on Windows 3.1.
 VER_PLATFORM_WIN32_WINDOWS     Win32 on Windows 9x
 VER_PLATFORM_WIN32_NT          Win32 on Windows NT, 2000


SzCSDVersion:DWORD
  NT - ñîäåðæèò PÑhar ñ èíôî î óñòàíîâëåííîì ServicePack
  9x - äîï. èíôî, ìîæåò è íå áûòü
}
function DetectWinVersion: TWinVersion;
var
  OSVersionInfo : TOSVersionInfo;
begin
  Result := wvUnknown;                      // Íåèçâåñòíàÿ âåðñèÿ ÎÑ
  OSVersionInfo.dwOSVersionInfoSize := sizeof(TOSVersionInfo);
  if GetVersionEx(OSVersionInfo)
    then
      begin
        case OSVersionInfo.DwMajorVersion of
          3:  Result := wvNT3;              // Windows NT 3
          4:  case OSVersionInfo.DwMinorVersion of
                0: if OSVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_NT
                   then Result := wvNT4     // Windows NT 4
                   else Result := wv95;     // Windows 95
                10: Result := wv98;         // Windows 98
                90: Result := wvME;         // Windows ME
              end;
          5:  case OSVersionInfo.DwMinorVersion of
                0: Result := wvW2K;         // Windows 2000
                1: Result := wvXP;          // Windows XP
                2: Result := wv2003;        // Windows 2003
                3: Result := wvVista;       // Windows Vista
              end;
          6:  case OSVersionInfo.DwMinorVersion of
                0: Result := wv2008;        // Windows 2008
                1: Result := wv7;           // Windows 7
              end;
          7:  case OSVersionInfo.DwMinorVersion of
                1: Result := wv8;           // Windows 8
              end;
        end;
      end;
end;

function DetectWinVersionStr: String;
const
  VersStr : Array[TWinVersion] of String = (
    'Unknown OS',
    'Windows 95',
    'Windows 98',
    'Windows ME',
    'Windows NT 3',
    'Windows NT 4',
    'Windows 2000',
    'Windows XP',
    'Windows Server 2003',
    'Windows Vista',
    'Windows 7',
    'Windows Server 2008',
    'Windows 8');
begin
  Result := VersStr[DetectWinVersion];
end;

begin
end.