-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnitUtil.pas
1336 lines (1245 loc) · 39.8 KB
/
UnitUtil.pas
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
unit UnitUtil;
{ ************************************************************************* }
{ 单元描述: 公共杂项函数单元 }
{ 版 本: 1.0 }
{ 修改日期: 2005-06-16 }
{ ************************************************************************* }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
StdCtrls, ShellApi, ShlObj, ActiveX, Registry, Dialogs;
// 字符串相关
function IsInt(const S: string): Boolean;
function IsFloat(const S: string): Boolean;
function IsEmail(const S: string): Boolean;
function PathWithSlash(const Path: string): string;
function PathWithoutSlash(const Path: string): string;
function FileExtWithDot(const FileExt: string): string;
function FileExtWithoutDot(const FileExt: string): string;
function AddNumberComma(Number: Int64): string;
function ExtractFileMainName(const FileName: string): string;
function ExtractUrlFilePath(const Url: string): string;
function ExtractUrlFileName(const Url: string): string;
function ValidateFileName(const FileName: string): string;
function GetSizeString(Bytes: Int64; const Postfix: string = ' KB'): string;
function GetPercentString(Position, Max: Int64;
const Postfix: string = ' %'): string;
function RestrictStrWidth(const S: WideString; Canvas: TCanvas; Width: Integer)
: WideString;
function RestrictFileNameWidth(const FileName: string;
MaxBytes: Integer): string;
function LikeString(Value, Pattern: WideString;
CaseInsensitive: Boolean): Boolean;
procedure SplitString(S: string; Delimiter: Char; List: TStrings);
function StartWith(const Source: string; const Left: string): Boolean;
function EndWith(const Source: string; const Right: string): Boolean;
// 系统相关
function GetComputerName: string;
function GetWinUserName: string;
function GetWindowsDir: string;
function GetWinTempDir: string;
function GetWinTempFile(const PrefixStr: string = ''): string;
function GetFullFileName(const FileName: string): string;
function GetShortFileName(const FileName: string): string;
function GetLongFileName(const FileName: string): string;
function GetSpecialFolder(FolderID: Integer): string;
function GetWorkAreaRect: TRect;
function SelectDir(ParentHWnd: HWND; const Caption: string;
const Root: WideString; var Path: string): Boolean;
function ExecuteFile(const FileName, Params, DefaultDir: string;
ShowCmd: Integer): HWND;
function OpenURL(const Url: string): Boolean;
function OpenEmail(const Email: string): Boolean;
procedure SetStayOnTop(Form: TCustomForm; StayOnTop: Boolean);
procedure HideAppFromTaskBar;
function CheckLangChinesePR: Boolean;
function ShutdownWindows: Boolean;
// 文件相关
function GetFileSize(const FileName: string): Int64;
function GetFileDate(const FileName: string): TDateTime;
function SetFileDate(const FileName: string; CreationTime, LastWriteTime,
LastAccessTime: TFileTime): Boolean;
function CopyFileToFolder(FileName, BackupFolder: string): Boolean;
function AutoRenameFileName(const FullName: string): string;
function GetTempFileAtPath(const Path: string;
const PrefixStr: string = ''): string;
// 注册表相关
procedure SetAutoRunOnStartup(AutoRun, CurrentUser: Boolean;
AppTitle: string = ''; AppPara: string = '');
procedure AssociateFile(const FileExt, FileKey, SoftName, FileDescription
: string; Flush: Boolean = False);
procedure SaveAppPath(const CompanyName, SoftName, Version: string);
function ReadAppPath(const CompanyName, SoftName, Version: string;
var Path: string): Boolean;
// 日期时间相关
function FileTimeToLocalSystemTime(FTime: TFileTime): TSystemTime;
function LocalSystemTimeToFileTime(STime: TSystemTime): TFileTime;
function GetDatePart(DateTime: TDateTime): TDate;
function GetTimePart(DateTime: TDateTime): TTime;
// 其它函数
procedure BeginWait;
procedure EndWait;
function Iif(Value: Boolean; Value1, Value2: Variant): Variant;
function Min(V1, V2: Integer): Integer;
function Max(V1, V2: Integer): Integer;
procedure Swap(var V1, V2: Integer);
function RestrictRectInScr(Rect: TRect; AllVisible: Boolean): TRect;
function GetAppSubPath(const SubFolder: string = ''): string;
function MsgBox(const Msg: string;
Flags: Integer = MB_OK + MB_ICONINFORMATION): Integer;
implementation
// -----------------------------------------------------------------------------
// 描述: 判断字符串 S 是不是一个整型数字
// -----------------------------------------------------------------------------
function IsInt(const S: string): Boolean;
var
E, R: Integer;
begin
Val(S, R, E);
Result := E = 0;
E := R; // avoid hints
end;
// -----------------------------------------------------------------------------
// 描述: 判断字符串 S 是不是一个浮点型数字
// -----------------------------------------------------------------------------
function IsFloat(const S: string): Boolean;
var
V: Extended;
begin
Result := TextToFloat(PChar(S), V, fvExtended);
end;
// -----------------------------------------------------------------------------
// 描述: 判断字符串 S 是不是一个 Email 地址
// -----------------------------------------------------------------------------
function IsEmail(const S: string): Boolean;
begin
Result := True;
if Pos('@', S) = 0 then
Result := False;
if Pos('.', S) = 0 then
Result := False;
end;
// -----------------------------------------------------------------------------
// 描述: 补全路径字符串后面的 "\"
// -----------------------------------------------------------------------------
function PathWithSlash(const Path: string): string;
begin
Result := Trim(Path);
if Length(Result) > 0 then
Result := IncludeTrailingPathDelimiter(Result);
end;
// -----------------------------------------------------------------------------
// 描述: 去掉路径字符串后面的 "\"
// -----------------------------------------------------------------------------
function PathWithoutSlash(const Path: string): string;
begin
Result := Trim(Path);
if Length(Result) > 0 then
Result := ExcludeTrailingPathDelimiter(Result);
end;
// -----------------------------------------------------------------------------
// 描述: 补全文件扩展名前面的 "."
// -----------------------------------------------------------------------------
function FileExtWithDot(const FileExt: string): string;
begin
Result := FileExt;
if Length(Result) > 0 then
if Copy(Result, 1, 1) <> '.' then
Result := '.' + Result;
end;
// -----------------------------------------------------------------------------
// 描述: 去掉文件扩展名前面的 "."
// -----------------------------------------------------------------------------
function FileExtWithoutDot(const FileExt: string): string;
begin
Result := FileExt;
if Length(Result) > 0 then
if Copy(Result, 1, 1) = '.' then
Delete(Result, 1, 1);
end;
// -----------------------------------------------------------------------------
// 描述: 给数字加上分隔逗号
// 示例: 1234567 -> 1,234,567
// -----------------------------------------------------------------------------
function AddNumberComma(Number: Int64): string;
var
Temp: Double;
begin
Temp := Number;
Result := Format('%.0n', [Temp]);
end;
// -----------------------------------------------------------------------------
// 描述: 取得文件名的主文件名
// 示例: "C:\test.dat" -> "test"
// -----------------------------------------------------------------------------
function ExtractFileMainName(const FileName: string): string;
var
Ext: string;
begin
Ext := ExtractFileExt(FileName);
Result := ExtractFileName(FileName);
Result := Copy(Result, 1, Length(Result) - Length(Ext));
end;
// -----------------------------------------------------------------------------
// 描述: 返回URL中的文件路径
// 示例:
// ExtractUrlFileName('http://www.download.com/file.zip');
// 此调用将返回 'http://www.download.com/'.
// -----------------------------------------------------------------------------
function ExtractUrlFilePath(const Url: string): string;
var
I: Integer;
begin
I := LastDelimiter('/\:', Url);
Result := Copy(Url, 1, I);
end;
// -----------------------------------------------------------------------------
// 描述: 返回URL中的文件名
// 示例:
// ExtractUrlFileName('http://www.download.com/file.zip');
// 此调用将返回 'file.zip'.
// -----------------------------------------------------------------------------
function ExtractUrlFileName(const Url: string): string;
var
I: Integer;
begin
I := LastDelimiter('/\:', Url);
Result := Copy(Url, I + 1, MaxInt);
end;
// -----------------------------------------------------------------------------
// 描述: 去掉文件名中不合法的字符
// 示例: "tes*t.dat?" -> "test.dat"
// -----------------------------------------------------------------------------
function ValidateFileName(const FileName: string): string;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(FileName) do
begin
if not(FileName[I] in ['\', '/', ':', '*', '?', '"', '<', '>', '|']) and
not(Ord(FileName[I]) < 32) then
Result := Result + FileName[I];
end;
end;
// -----------------------------------------------------------------------------
// 描述: 取得一个用来描述字节数的字符串
// 参数:
// Bytes - 字节数
// Postfix - 单位后缀,缺省为 " KB"
// -----------------------------------------------------------------------------
function GetSizeString(Bytes: Int64; const Postfix: string): string;
var
Temp: Double;
begin
if Bytes > 0 then
begin
Temp := Bytes div 1024;
if Bytes mod 1024 <> 0 then
Temp := Temp + 1;
end
else
Temp := 0;
Result := Format('%s%s', [Format('%.0n', [Temp]), Postfix]);
end;
// -----------------------------------------------------------------------------
// 描述: 取得一个用来描述百分比的字符串
// 参数:
// Position, Max - 当前值 和 最大值
// Postfix - 后缀字符串,缺省为 " %"
// -----------------------------------------------------------------------------
function GetPercentString(Position, Max: Int64; const Postfix: string): string;
begin
if Max > 0 then
Result := IntToStr(Trunc((Position / Max) * 100)) + Postfix
else
Result := '100' + Postfix;
end;
// -----------------------------------------------------------------------------
// 描述: 缩短字符串的长度以适应显示宽度
// 参数:
// S - 待缩短的字符串.
// Canvas - 字符串所在的Canvas.
// Width - 最大象素宽度
// 返回:
// 缩短之后的字符串
// -----------------------------------------------------------------------------
function RestrictStrWidth(const S: WideString; Canvas: TCanvas; Width: Integer)
: WideString;
var
Src: WideString;
begin
Src := S;
Result := S;
while (Canvas.TextWidth(Result) > Width) and (Length(Result) > 0) do
begin
if Length(Src) > 1 then
begin
Delete(Src, Length(Src), 1);
Result := Src + '...';
end
else
Delete(Result, Length(Result), 1);
end;
end;
// -----------------------------------------------------------------------------
// 描述: 缩短文件名的长度以适应最大字节数限制
// 参数:
// FileName - 待缩短的文件名(可以包含路径)
// MaxBytes - 最大字节数
// 返回:
// 缩短之后的文件名字符串
// -----------------------------------------------------------------------------
function RestrictFileNameWidth(const FileName: string;
MaxBytes: Integer): string;
function GetBytes(const S: WideString): Integer;
var
AnsiStr: string;
begin
AnsiStr := S;
Result := Length(AnsiStr);
end;
var
MainName, NewMainName: WideString;
Ext: string;
ExtLen: Integer;
begin
if Length(FileName) <= MaxBytes then
begin
Result := FileName;
end
else
begin
Ext := ExtractFileExt(FileName);
MainName := Copy(FileName, 1, Length(FileName) - Length(Ext));
ExtLen := Length(Ext);
NewMainName := MainName;
while (GetBytes(NewMainName) + ExtLen > MaxBytes) and
(Length(NewMainName) > 0) do
begin
if Length(MainName) > 1 then
begin
Delete(MainName, Length(MainName), 1);
NewMainName := MainName + '...';
end
else
Delete(NewMainName, Length(NewMainName), 1);
end;
Result := NewMainName + Ext;
if Length(Result) > MaxBytes then
Result := Copy(Result, 1, MaxBytes);
end;
end;
// -----------------------------------------------------------------------------
// 描述:计算通配符表达式,支持通配符'*' 和 '?'
// 参数:
// Value - 母串
// Pattern - 子串
// CaseInsensitive - 是否忽略大小写
// 返回:
// True - 匹配
// False - 不匹配
// 示例:
// LikeString('abcdefg', 'abc*', True);
// -----------------------------------------------------------------------------
function LikeString(Value, Pattern: WideString;
CaseInsensitive: Boolean): Boolean;
const
MultiWildChar = '*';
SingleWildChar = '?';
function MatchPattern(ValueStart, PatternStart: Integer): Boolean;
begin
if (Pattern[PatternStart] = MultiWildChar) and
(Pattern[PatternStart + 1] = #0) then
Result := True
else if (Value[ValueStart] = #0) and (Pattern[PatternStart] <> #0) then
Result := False
else if (Value[ValueStart] = #0) then
Result := True
else
begin
case Pattern[PatternStart] of
MultiWildChar:
begin
if MatchPattern(ValueStart, PatternStart + 1) then
Result := True
else
Result := MatchPattern(ValueStart + 1, PatternStart);
end;
SingleWildChar:
Result := MatchPattern(ValueStart + 1, PatternStart + 1);
else
begin
if not CaseInsensitive and (Value[ValueStart] = Pattern[PatternStart])
or CaseInsensitive and
(UpperCase(Value[ValueStart]) = UpperCase(Pattern[PatternStart]))
then
Result := MatchPattern(ValueStart + 1, PatternStart + 1)
else
Result := False;
end;
end;
end;
end;
begin
if Value = '' then
Value := #0;
if Pattern = '' then
Pattern := #0;
Result := MatchPattern(1, 1);
end;
// -----------------------------------------------------------------------------
// 描述: 分割字符串
// -----------------------------------------------------------------------------
procedure SplitString(S: string; Delimiter: Char; List: TStrings);
var
I: Integer;
begin
List.Clear;
while Length(S) > 0 do
begin
I := Pos(Delimiter, S);
if I > 0 then
begin
List.Add(Copy(S, 1, I - 1));
Delete(S, 1, I);
end
else
begin
List.Add(S);
Break;
end;
end;
end;
// -----------------------------------------------------------------------------
// 描述: 判断字符串 Source 是不是以 Left 开始
// -----------------------------------------------------------------------------
function StartWith(const Source: string; const Left: string): Boolean;
var
Start: string;
Len: Integer;
begin
Len := Length(Left);
if (Source = '') or (Left = '') or (Length(Source) < Len) then
begin
Result := False;
end
else
begin
Start := Copy(Source, 1, Len);
Result := Start = Left;
end;
end;
// -----------------------------------------------------------------------------
// 描述: 判断字符串 Source 是不是以 Right 结束
// -----------------------------------------------------------------------------
function EndWith(const Source: string; const Right: string): Boolean;
var
EndStr: string;
RightLen: Integer;
SourceLen: Integer;
begin
RightLen := Length(Right);
SourceLen := Length(Source);
if (Source = '') or (Right = '') or (SourceLen < RightLen) then
begin
Result := False;
end
else
begin
EndStr := Copy(Source, SourceLen - RightLen + 1, RightLen);
Result := EndStr = Right;
end;
end;
// -----------------------------------------------------------------------------
// 描述: 取得计算机名
// -----------------------------------------------------------------------------
function GetComputerName: string;
const
MaxSize = 256;
var
Buffer: array [0 .. MaxSize - 1] of Char;
Size: Cardinal;
begin
Size := MaxSize;
Windows.GetComputerName(PChar(@Buffer[0]), Size);
Result := Buffer;
end;
// -----------------------------------------------------------------------------
// 描述: 取得当前系统用户名
// -----------------------------------------------------------------------------
function GetWinUserName: string;
const
Size = 255;
var
Buffer: array [0 .. Size] of Char;
Len: DWord;
begin
Len := Size;
GetUserName(Buffer, Len);
Result := Buffer;
end;
// -----------------------------------------------------------------------------
// 描述: 取得 Windows 目录
// -----------------------------------------------------------------------------
function GetWindowsDir: string;
var
Buffer: array [0 .. MAX_PATH] of Char;
begin
GetWindowsDirectory(Buffer, MAX_PATH);
Result := PathWithSlash(Buffer);
end;
// -----------------------------------------------------------------------------
// 描述: 取得系统临时文件目录
// -----------------------------------------------------------------------------
function GetWinTempDir: string;
const
Size = 1024;
var
Buffer: array [0 .. Size] of Char;
LongName: string;
begin
GetTempPath(Size, Buffer);
Result := PathWithSlash(Buffer);
LongName := GetLongFileName(Result);
if Length(LongName) >= Length(Result) then
Result := LongName;
end;
// -----------------------------------------------------------------------------
// 描述: 取得一个临时文件名(路径为系统临时目录)
// 参数:
// PrefixStr - 文件名前缀,前三个字符有效
// -----------------------------------------------------------------------------
function GetWinTempFile(const PrefixStr: string): string;
var
FileName: array [0 .. MAX_PATH] of Char;
LongName: string;
begin
Windows.GetTempFileName(PChar(GetWinTempDir), PChar(PrefixStr), 0, FileName);
Result := FileName;
LongName := GetLongFileName(Result);
if Length(LongName) >= Length(Result) then
Result := LongName;
end;
// -----------------------------------------------------------------------------
// 描述: 文件的全名(包含路径)
// 示例:
// "test.dat" -> "C:\test.dat"
// "C:\a\..\test.dat" -> "C:\test.dat"
// -----------------------------------------------------------------------------
function GetFullFileName(const FileName: string): string;
const
Size = 1024;
var
Buffer: array [0 .. Size] of Char;
FileNamePtr: PChar;
Len: DWord;
begin
Len := Size;
GetFullPathName(PChar(FileName), Len, Buffer, FileNamePtr);
Result := Buffer;
end;
// -----------------------------------------------------------------------------
// 描述: 长文件名 -> 短文件名(8.3)
// 备注: FileName 可以是路径,也可以是文件名。
// 示例:
// "C:\Program Files" -> "C:\PROGRA~1"
// -----------------------------------------------------------------------------
function GetShortFileName(const FileName: string): string;
const
Size = 1024;
var
Buffer: array [0 .. Size] of Char;
begin
GetShortPathName(PChar(FileName), Buffer, Size);
Result := Buffer;
end;
// -----------------------------------------------------------------------------
// 描述: 短文件名(8.3) -> 长文件名
// 备注: FileName 可以是路径,也可以是文件名。
// 示例:
// "C:\PROGRA~1\COMMON~1\" -> "C:\Program Files\Common Files\"
// -----------------------------------------------------------------------------
function GetLongFileName(const FileName: string): string;
var
Name, S: string;
SearchRec: TSearchRec;
begin
S := ExcludeTrailingPathDelimiter(FileName);
if (Length(S) < 3) or (ExtractFilePath(S) = S) then
begin
Result := FileName;
Exit;
end;
if FindFirst(S, faAnyFile, SearchRec) = 0 then
Name := SearchRec.Name
else
Name := ExtractFileName(S);
FindClose(SearchRec);
Result := GetLongFileName(ExtractFilePath(S)) + Name;
if Length(S) <> Length(FileName) then
Result := Result + '\';
end;
// -----------------------------------------------------------------------------
// 描述: 取得特殊文件夹路径
// 参数:
// FolderID -
// CSIDL_DESKTOP
// CSIDL_PROGRAMS
// CSIDL_RECENT
// CSIDL_SENDTO
// CSIDL_STARTMENU
// CSIDL_STARTUP
// CSIDL_TEMPLATES
// CSIDL_APPDATA
// 返回:
// 若成功,返回带最后斜线(\)的路径;
// 若失败,返回空字符串。
// -----------------------------------------------------------------------------
function GetSpecialFolder(FolderID: Integer): string;
var
PidL: PItemIDList;
Handle: THandle;
LinkDir: string;
begin
Result := '';
Handle := Application.Handle;
if Succeeded(SHGetSpecialFolderLocation(Handle, FolderID, PidL)) then
begin
SetLength(LinkDir, MAX_PATH);
SHGetPathFromIDList(PidL, PChar(LinkDir));
SetLength(LinkDir, StrLen(PChar(LinkDir)));
Result := LinkDir + '\';
if FolderID = CSIDL_APPDATA then
Result := Result + 'Microsoft\Internet Explorer\Quick Launch\';
end;
end;
// -----------------------------------------------------------------------------
// 描述: 取得桌面上除任务栏以外的区域
// -----------------------------------------------------------------------------
function GetWorkAreaRect: TRect;
begin
SystemParametersInfo(SPI_GETWORKAREA, 0, @Result, 0);
end;
// -----------------------------------------------------------------------------
// 描述: 浏览文件夹,可定位文件夹
// 参数:
// ParentHWnd - 父窗口的句柄
// Caption - 浏览对话框的提示标题
// Root - 根目录
// Path - 存放用户最终选择的目录
// 返回:
// True - 用户点了确定
// False - 用户点了取消
// -----------------------------------------------------------------------------
function SelectDir(ParentHWnd: HWND; const Caption: string;
const Root: WideString; var Path: string): Boolean;
const
{$WRITEABLECONST ON}
InitPath: string = '';
{$WRITEABLECONST OFF}
var
WindowList: Pointer;
BrowseInfo: TBrowseInfo;
Buffer: PChar;
RootItemIDList, ItemIDList: PItemIDList;
ShellMalloc: IMalloc;
IDesktopFolder: IShellFolder;
Eaten, Flags: LongWord;
function BrowseCallbackProc(HWND: HWND; uMsg: UINT; lParam: Cardinal;
lpData: Cardinal): Integer; stdcall;
var
R: TRect;
begin
if uMsg = BFFM_INITIALIZED then
begin
GetWindowRect(HWND, R);
MoveWindow(HWND, (Screen.Width - (R.Right - R.Left)) div 2,
(Screen.Height - (R.Bottom - R.Top)) div 2, R.Right - R.Left,
R.Bottom - R.Top, True);
Result := SendMessage(HWND, BFFM_SETSELECTION, Ord(True),
Longint(PChar(InitPath)))
end
else
Result := 1;
end;
begin
Result := False;
InitPath := Path;
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then
begin
Buffer := ShellMalloc.Alloc(MAX_PATH);
try
RootItemIDList := nil;
if Root <> '' then
begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(Application.Handle, nil, POleStr(Root),
Eaten, RootItemIDList, Flags);
end;
with BrowseInfo do
begin
hwndOwner := ParentHWnd;
pidlRoot := RootItemIDList;
pszDisplayName := Buffer;
lpszTitle := PChar(Caption);
ulFlags := BIF_RETURNONLYFSDIRS;
lpfn := @BrowseCallbackProc;
lParam := BFFM_INITIALIZED;
end;
WindowList := DisableTaskWindows(0);
try
ItemIDList := ShBrowseForFolder(BrowseInfo);
finally
EnableTaskWindows(WindowList);
end;
Result := ItemIDList <> nil;
if Result then
begin
SHGetPathFromIDList(ItemIDList, Buffer);
ShellMalloc.Free(ItemIDList);
Path := Buffer;
end;
finally
ShellMalloc.Free(Buffer);
end;
end;
end;
// -----------------------------------------------------------------------------
// 描述: 用系统 Shell 调用来打开一个文件
// -----------------------------------------------------------------------------
function ExecuteFile(const FileName, Params, DefaultDir: string;
ShowCmd: Integer): HWND;
begin
Result := ShellExecute(Application.Handle, nil, PChar(FileName),
PChar(Params), PChar(DefaultDir), ShowCmd);
end;
// -----------------------------------------------------------------------------
// 描述: 打开一个 URL
// 示例:
// OpenURL('http://www.abc.com');
// OpenURL('www.abc.com');
// OpenURL('file:///c:\');
// -----------------------------------------------------------------------------
function OpenURL(const Url: string): Boolean;
begin
Result := ShellExecute(Application.Handle, 'Open', PChar(Trim(Url)), '', '',
SW_SHOW) > 32;
end;
// -----------------------------------------------------------------------------
// 描述: 打开一个 Email 发送客户端
// -----------------------------------------------------------------------------
function OpenEmail(const Email: string): Boolean;
const
SPrefix = 'mailto:';
var
S: string;
begin
S := Trim(Email);
if Pos(SPrefix, S) <> 1 then
S := SPrefix + S;
Result := OpenURL(S);
end;
// -----------------------------------------------------------------------------
// 描述: 让窗口保持在最上层
// -----------------------------------------------------------------------------
procedure SetStayOnTop(Form: TCustomForm; StayOnTop: Boolean);
begin
if StayOnTop Then
SetWindowPos(Form.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or
SWP_NOSIZE)
else
SetWindowPos(Form.Handle, HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOMOVE Or SWP_NOSIZE);
end;
// -----------------------------------------------------------------------------
// 描述: 隐藏应用程序在任务栏上的选择按钮
// -----------------------------------------------------------------------------
procedure HideAppFromTaskBar;
var
ExtendedStyle: Integer;
begin
ExtendedStyle := GetWindowLong(Application.Handle, GWL_EXSTYLE);
SetWindowLong(Application.Handle, GWL_EXSTYLE, ExtendedStyle or
WS_EX_TOOLWINDOW and not WS_EX_APPWINDOW);
end;
// -----------------------------------------------------------------------------
// 描述: 检查当前系统语言是否简体中文
// -----------------------------------------------------------------------------
function CheckLangChinesePR: Boolean;
const
// LCID Consts
LangChinesePR = (SUBLANG_CHINESE_SIMPLIFIED shl 10) or LANG_CHINESE;
begin
Result := SysLocale.DefaultLCID = LangChinesePR;
end;
// -----------------------------------------------------------------------------
// 描述: 关机
// -----------------------------------------------------------------------------
function ShutdownWindows: Boolean;
const
SE_SHUTDOWN_NAME = 'SeShutdownPrivilege';
var
hToken: THandle;
tkp: TTokenPrivileges;
tkpo: TTokenPrivileges;
Zero: DWord;
begin
Result := True;
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
Zero := 0;
if not OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or
TOKEN_QUERY, hToken) then
begin
Result := False;
Exit;
end;
if not LookupPrivilegeValue(nil, SE_SHUTDOWN_NAME, tkp.Privileges[0].Luid)
then
begin
Result := False;
Exit;
end;
tkp.PrivilegeCount := 1;
tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, False, tkp, SizeOf(TTokenPrivileges),
tkpo, Zero);
if Boolean(GetLastError()) then
begin
Result := False;
Exit;
end
else
ExitWindowsEx(EWX_SHUTDOWN or EWX_POWEROFF, 0);
end
else
ExitWindowsEx(EWX_SHUTDOWN or EWX_POWEROFF, 0);
end;
// -----------------------------------------------------------------------------
// 描述: 取得文件大小
// -----------------------------------------------------------------------------
function GetFileSize(const FileName: string): Int64;
var
FileStream: TFileStream;
begin
Result := -1;
if not FileExists(FileName) then
Exit;
try
FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
Result := FileStream.Size;
finally
FileStream.Free;
end;
except
Result := 0;
end;
end;
// -----------------------------------------------------------------------------
// 描述: 取得文件的修改时间
// -----------------------------------------------------------------------------
function GetFileDate(const FileName: string): TDateTime;
var
FileHandle: Integer;
begin
FileHandle := FileOpen(FileName, fmOpenWrite or fmShareDenyNone);
try
if FileHandle > 0 then
Result := FileDateToDateTime(FileGetDate(FileHandle))
else
Result := 0;
finally
FileClose(FileHandle);
end;
end;
// -----------------------------------------------------------------------------
// 描述: 设置文件的时间
// -----------------------------------------------------------------------------
function SetFileDate(const FileName: string; CreationTime, LastWriteTime,
LastAccessTime: TFileTime): Boolean;
var
FileHandle: Integer;
begin
FileHandle := FileOpen(FileName, fmOpenWrite or fmShareDenyNone);
try
if FileHandle > 0 then
begin
SetFileTime(FileHandle, @CreationTime, @LastAccessTime, @LastWriteTime);
Result := True;
end
else
Result := False;
finally
FileClose(FileHandle);
end;
end;
// -----------------------------------------------------------------------------
// 描述: 复制文件到一个文件夹
// -----------------------------------------------------------------------------
function CopyFileToFolder(FileName, BackupFolder: string): Boolean;
var
MainFileName: string;
begin
BackupFolder := PathWithSlash(BackupFolder);
MainFileName := ExtractFileName(FileName);
ForceDirectories(BackupFolder);
Result := CopyFile(PChar(FileName),
PChar(BackupFolder + MainFileName), False);
end;
// -----------------------------------------------------------------------------
// 描述: 自动调整文件名,防止文件名重复
// 参数:
// FullName - 文件的全路径名
// 示例:
// NewName := AutoRenameFileName('C:\Downloads\test.dat');
// 如果 "C:\Downloads\" 下已经存在test.dat,则函数返回 "C:\Downloads\test(1).dat".
// -----------------------------------------------------------------------------
function AutoRenameFileName(const FullName: string): string;
const
SLeftSym = '(';
SRightSym = ')';
// 若S='test(1)',则返回'(1)'; 若S='test(a)',则返回''。
function GetNumberSection(const S: string): string;
var
I: Integer;
begin
Result := '';
if Length(S) < 3 then
Exit;
if S[Length(S)] = SRightSym then
begin
for I := Length(S) - 2 downto 1 do
if S[I] = SLeftSym then
begin
Result := Copy(S, I, MaxInt);
Break;
end;
end;
if Length(Result) > 0 then
begin
if not IsInt(Copy(Result, 2, Length(Result) - 2)) then
Result := '';
end;
end;
var
Number: Integer;
Name, Ext, NumSec: string;
begin
Ext := ExtractFileExt(FullName);