arctan(x) 反正切
cos(x) 傳回餘弦函數值
exp(x) e的x次冪
frac(x) 取小數部分
int(x) 取整
ln(x) 自然對數
sin(x) 傳回正弦函數值
sqr(x) x*x
sqrt(x) 平方根
其它
pred(x) pred('D')='C', pred(true)=1;
succ(x) succ('Y')='Z', succ(pred(x))=x
ord(x) 求x在字符集中的序號,如ord('A')=65
chr(x) chr(65)='A'
round(x) 四捨五入
trunc(x) trunc(4.8)=4,trunc('-3.6')=-3
upcase(x) upcase('a')='A'
hi(I) hi($2A30)=$2A
lo(I) lo($2A30)=$30
random(n) 產生[0,n)間的隨機整數
sizeof(name) 求出某類型或變量在內存中佔用的字節數
swap(num) swap($3621)=$2136
================================
Arithmetic routines 數學運算
================================
Abs 絕對值
---------------------------------------------------------
Unit System
函數原型 function Abs(X);
說明 X爲整數or實數.
範例
var
r: Real;
i: Integer;
begin
r := Abs(-2.3); { 2.3 }
i := Abs(-157); { 157 }
end;
----------------------------------------------------------
ArcTan 三角函數
----------------------------------------------------------
範例
Cos
var R: Extended;
begin
R := Cos(Pi);
end;
----------------------------------------------------------
Sin
----------------------------------------------------------
範例
var
R: Extended;
S: string;
begin
R := Sin(Pi);
Str(R:5:3, S);
Canvas.TextOut(10, 10, 'The Sin of Pi is ' + S);
end;
----------------------------------------------------------
Unit System
函數原型 function ArcTan(X: Extended): Extended;
函數原型 function Cos(X: Extended): Extended;
函數原型 function Sin(X: Extended): Extended;
----------------------------------------------------------
說明 X爲徑度.
Tan(x) === Sin(x) / Cos(x)
ArcSin(x) = ArcTan (x/sqrt (1-sqr (x)))
ArcCos(x) = ArcTan (sqrt (1-sqr (x)) /x)
左邊這三個不是函數,而是右邊運算求得.
範例
var
R: Extended;
begin
R := ArcTan(Pi);
end;
範例 var
R: Extended;
S: string;
begin
R := Sin(Pi);
Str(R:5:3, S);
Canvas.TextOut(10, 10, 'The Sin of Pi is ' + S);
end;
----------------------------------------------------------
Frac 求一個實數的小數部份
----------------------------------------------------------
Unit System
函數原型 function Frac(X: Real): Real;
說明 X爲實數.
範例 var
R: Real;
begin
R := Frac(123.456); { 0.456 }
R := Frac(-123.456); { -0.456 }
end;
------------------------------------------
Int 求一個實數的整數部份
------------------------------------------
Unit System
函數原型 function Int(X: Real): Real;
說明 X爲實數.
範例 var
R: Real;
begin
R := Int(123.456); { 123.0 }
R := Int(-123.456); { -123.0 }
end;
------------------------------------------
Pi 就是數學的Pi
------------------------------------------
Unit System
函數原型 function Pi: Extended;
說明 它是一個函數,但我們就把它當作是預設的變數來用吧!
Pi= 3.1415926535897932385
------------------------------------------
Sqr X的平方
-----------------------------------------
範例
var
S, Temp: string;
begin
Str(Sqr(5.0):3:1, Temp);
S := '5 squared is ' + Temp + #13#10;
Str(Sqrt(2.0):5:4, Temp);
S := S + 'The square root of 2 is ' + Temp;
MessageDlg(S, mtInformation, [mbOk], 0);
end;
-----------------------------------------
Sqrt X的平方根
------------------------------------------
Unit System
函數原型 function Sqr(X: Extended): Extended;
函數原型 function Sqrt(X: Extended): Extended;
範例 var
S, Temp: string;
begin
Str(Sqr(5.0):3:1, Temp);
S := '5 squared is ' + Temp + #13#10;
Str(Sqrt(2.0):5:4, Temp);
S := S + 'The square root of 2 is ' + Temp;
MessageDlg(S, mtInformation, [mbOk], 0);
end;
------------------------------------------
Ln 自然對數
------------------------------------------
範例
var
e : real;
S : string;
begin
e := Exp(1.0);
Str(ln(e):3:2, S);
S := 'e = ' + FloatToStr(e) + '; ln(e) = ' + S;
Canvas.TextOut(10, 10, S);
end;
----------------------------------------
Exp 指數
------------------------------------------
Unit System
函數原型 function Ln(X: Real): Real;
函數原型 function Exp(X: Real): Real;
範例 var
e : real;
S : string;
begin
e := Exp(1.0);
Str(ln(e):3:2, S);
S := 'ln(e) = ' + S;
Canvas.TextOut(10, 10, S);
end;
------------------------------------------
Date and time routines 日期及時間函數
------------------------------------------
Date 傳回目前的日期
Unit SysUtils
函數原型 function Date: TDateTime;
範例 procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := 'Today is ' + DateToStr(Date);
end;
------------------------------------------
DateTimeToStr 日期時間轉換成內定型字串(1996/12/20 09:12:20 PM)
------------------------------------------
Unit SysUtils
函數原型 function DateTimeToStr(DateTime: TDateTime): string;
範例 procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := DateTimeToStr(Now);
end;
--------------------------------------------------------
DateTimeToString 日期時間轉換成自定型字串
-------------------------------------------------------
Unit SysUtils
函數原型 procedure DateTimeToString(var Result: string; const Format:
string; DateTime: TDateTime);
範例 procedure TForm1.FormCreate(Sender: TObject);
var
s:string;
begin
DateTimeToString(s,'dddd,mmmm d,yyyy "at" hh:mm
AM/PM',Now);
Label1.Caption :=s;
end;
結果 星期五,十二月 20,1996 at 09:20 PM
-----------------------------------------------------------------------------
**** Format格式叄考下面.FormatDateTime.
--------------------------------------------------------
DateToStr 日期轉換成內定型字串.(1996/12/20)
--------------------------------------------------------
Unit SysUtils
函數原型 function DateToStr(Date: TDateTime): string;
範例
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := 'Today is ' + DateToStr(Date);
end;
# Date, DateToStr Example
--------------------------------------------------------
DayOfWeek 求叄數日期是星期幾.
--------------------------------------------------------
Unit SysUtils
函數原型 function DayOfWeek(Date: TDateTime): Integer;
說明 傳回值是一整數,1~7.
星期日爲1.
範例
procedure TForm1.Button1Click(Sender: TObject);
var
ADate: TDateTime;
days: array[1..7] of string;
begin
days[1] := 'Sunday';
days[2] := 'Monday';
days[3] := 'Tuesday';
days[4] := 'Wednesday';
days[5] := 'Thursday';
days[6] := 'Friday';
days[7] := 'Saturday';
ADate := StrToDate(Edit1.Text);
ShowMessage(Edit1.Text + ' is a ' + days[DayOfWeek(ADate)];
end;
# StrToDate, DayOfWeek Example
--------------------------------------------------------
DecodeDate 將TDateTime型態的日期變數,轉爲Word型態.
--------------------------------------------------------
範例
procedure TForm1.Button1Click(Sender: TObject);
var
Present: TDateTime;
Year, Month, Day, Hour, Min, Sec, MSec: Word;
begin
Present:= Now;
DecodeDate(Present, Year, Month, Day);
Label1.Caption := 'Today is Day ' + IntToStr(Day) + ' of Month '
+ IntToStr(Month) + ' of Year ' + IntToStr(Year);
DecodeTime(Present, Hour, Min, Sec, MSec);
Label2.Caption := 'The time is Minute ' + IntToStr(Min) + ' of Hour '
+ IntToStr(Hour);
end;
# DecodeDate, DecodeTime Example
--------------------------------------------------------
DecodeTime 將TDateTime型態的時間變數,轉爲Word型態.
--------------------------------------------------------
Unit SysUtils
函數原型 procedure DecodeDate(Date: TDateTime; var Year, Month,Day: Word);
函數原型 procedure DecodeTime(Time: TDateTime; var Hour, Min, Sec,MSec: Word);
範例 procedure TForm1.Button1Click(Sender: TObject);
var
Present: TDateTime;
Year, Month, Day, Hour, Min, Sec, MSec: Word;
begin
Present:= Now;
DecodeDate(Present, Year, Month, Day);
Label1.Caption := 'Today is Day ' + IntToStr(Day) + ' of
Month ' + IntToStr(Month) + ' of Year ' + IntToStr(Year);
DecodeTime(Present, Hour, Min, Sec, MSec);
Label2.Caption := 'The time is Minute ' +IntToStr(Min) + ' of
Hour ' + IntToStr(Hour);
end;
--------------------------------------------------------
EncodeDate 將Word型態的日期變數,轉爲TDateTime型態.
--------------------------------------------------------
範例
procedure TForm1.Button1Click(Sender: TObject);
var
MyDate: TDateTime;
begin
MyDate := EncodeDate(StrToInt(Edit1.Text), StrToInt(Edit2.Text), StrToInt(Edit3.Text));
Label1.Caption := DateToStr(MyDate);
end;
-------------------------------------------------------
EncodeTime 將Word型態的時間變數,轉爲TDateTime型態.
--------------------------------------------------------
Unit SysUtils
函數原型 function EncodeDate(Year, Month, Day: Word): TDateTime;
函數原型 function EncodeTime(Hour, Min, Sec, MSec: Word):
TDateTime;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
MyDate: TDateTime;
MyTime: TDateTime;
begin
MyDate := EncodeDate(83, 12, 31);
Label1.Caption := DateToStr(MyDate);
MyTime := EncodeTime(0, 45, 45, 7);
Label2.Caption := TimeToStr(MyTime);
end;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
MyTime: TDateTime;
begin
MyTime := EncodeTime(0, 45, 45, 7);
Label1.Caption := TimeToStr(MyTime);
end;
--------------------------------------------------------
FormatDateTime 將日期時間依Format的格式轉換給一字串.
--------------------------------------------------------
Unit SysUtils
函數原型 function FormatDateTime(const Format: string; DateTime:
TDateTime): string;
**** 類似DateTimeToString.
Format格式
c 內定值ShortDateFormat的格式.(1996/12/20 09:20:15 PM).
d 日期,前面不補0.(1-31)
dd 日期,前面補0.(01-31)
ddd 星期.(星期日).
Dddd 中文2.01版,同上.
ddddd 日期.(1996/12/20)
dddddd 日期.(1996年12月20日)
m 月份,前面不補0.(1-12)
mm 月份,前面補0.(01-12)
mmm 中文顯示.(十二月)
mmmm 中文2.01版,同上.
Yy 年度.(00-99)
yyyy 年度.(0000-9999)
h 小時.(0-23)
hh 小時.(00-23)
n 分鐘.(0-59)
nn 分鐘.(00-59)
s 秒鐘.(0-59)
ss 秒鐘.(00-59)
t 時間.(09:20 PM)
tt 時間.(09:20:15 PM)
am/pm 單獨顯示am or pm.(若大寫,則顯示大寫)
a/p 單獨顯示a or p.
範例
The following example assigns 'The meeting is on Wednesday, February 15, 1995 at 10:30 AM' to the string variable S.
S := FormatDateTime('"The meeting is on " dddd, mmmm d, yyyy, " at " hh:mm AM/PM',
StrToDateTime('2/15/95 10:30am'));//???
--------------------------------------------------------
Now 傳回目前的日期時間.
--------------------------------------------------------
Unit SysUtils
函數原型 function Now: TDateTime;
範例
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := DateTimeToStr(Now);
end;
# Now, DateTimeToStr Example
--------------------------------------------------------
StrToDate 將字串轉爲TDateTime型態的日期.
--------------------------------------------------------
Unit SysUtils
函數原型 function StrToDate(const S: string): TDateTime;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
ADate: TDateTime;
begin
ADate := StrToDate(Edit1.Text);
Label1.Caption := DateToStr(ADate);
end;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
ADate: TDateTime;
days: array[1..7] of string;
begin
days[1] := 'Sunday';
days[2] := 'Monday';
days[3] := 'Tuesday';
days[4] := 'Wednesday';
days[5] := 'Thursday';
days[6] := 'Friday';
days[7] := 'Saturday';
ADate := StrToDate(Edit1.Text);
ShowMessage(Edit1.Text + ' is a ' + days[DayOfWeek(ADate)];
end;
# StrToDate, DayOfWeek Example
--------------------------------------------------------
StrToDateTime 將字串轉爲TDateTime型態的日期時間.
--------------------------------------------------------
Unit SysUtils
函數原型 function StrToDateTime(const S: string): TDateTime;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
ADateAndTime: TDateTime;
begin
ADateAndTime := StrToDateTime(Edit1.Text);
Table1.FieldByName('TimeStamp').AsDateTime := ADateAndTime;
end;
--------------------------------------------------------
StrToTime 將字串轉爲TDateTime型態的時間.
--------------------------------------------------------
Unit SysUtils
函數原型 function StrToTime(const S: string): TDateTime;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
ATime: TDateTime;
begin
ATime := StrToTime(Edit1.Text);
if ATime < 0.50 then
ShowMessage('Good Morning')
else
ShowMessage('Good Afternoon');
end;
--------------------------------------------------------
Time 傳回目前的時間.
--------------------------------------------------------
Unit SysUtils
函數原型 function Time: TDateTime;
範例
procedure TForm1.Timer1Timer(Sender: TObject);
var
DateTime : TDateTime;
str : string;
begin
DateTime := Time; // store the current date and time
str := TimeToStr(DateTime); // convert the time into a string
Caption := str; // display the time on the form's caption
{ Note This could have been done with the following line of code:
Caption := TimeToStr(Time); }
end;
# Time, TimeToStr Example
--------------------------------------------------------
TimeToStr 時間轉換成內定型字串.(09:20:15 PM)
--------------------------------------------------------
Unit SysUtils
函數原型 function TimeToStr(Time: TDateTime): string;
GetMem procedure 配置記憶體程序
New 配置指位器P的記憶體空間,
大小爲P所指型態的大小.
--------------------------------------------------------
Dispose 釋放New所配置的記憶體.
--------------------------------------------------------
Unit System
函數原型 procedure New(var P: Pointer);
函數原型 procedure Dispose(var P: Pointer);
範例 type
PListEntry = ^TListEntry;
TListEntry = record
Next: PListEntry;
Text: string;
Count: Integer;
end;
var
List, P: PListEntry;
begin
...
New(P);
P^.Next := List;
P^.Text := 'Hello world';
P^.Count := 1;
List := P;
...
Dispose(P);
…
end;
範例
type
Str18 = string[18];
var
P: ^Str18;
begin
New(P);
P^ := 'Now you see it...';
Dispose(P); { Now you don't... }
end;
--------------------------------------------------------
GetMem 配置指位器P的記憶體空間,大小可自行設定.
--------------------------------------------------------
範例
var
F: file;
Size: Integer;
Buffer: PChar;
begin
AssignFile(F, 'test.txt');
Reset(F, 1);
try
Size := FileSize(F);
GetMem(Buffer, Size);
try
BlockRead(F, Buffer^, Size);
ProcessFile(Buffer, Size);
finally
FreeMem(Buffer);
end;
finally
CloseFile(F);
end;
end;
--------------------------------------------------------
FreeMem 釋放GetMem所配置的記憶體.
--------------------------------------------------------
Unit System
函數原型 procedure GetMem(var P: Pointer; Size: Integer);
函數原型 procedure FreeMem(var P: Pointer[; Size: Integer]);
範例 var
F: file;
Size: Integer;
Buffer: PChar;
begin
AssignFile(F, 'test.txt');
Reset(F, 1);
try
Size := FileSize(F);
GetMem(Buffer, Size);
try
BlockRead(F, Buffer^, Size);
ProcessFile(Buffer, Size);
finally
FreeMem(Buffer);
end;
finally
CloseFile(F);
end;
end;
====================================
File-management routines 檔案管理常式
====================================
--------------------------------------------------------
ChangeFileExt 變更檔案的副檔名
--------------------------------------------------------
Unit SysUtils
函數原型 function ChangeFileExt(const FileName, Extension: string):
string;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
P1:String;
P2:String;
begin
P1:='abc.txt';
P2:='.ini';
S := ChangeFileExt(P1,P2);
Label1.Caption:=S;
end;
結果 S== 'abc.ini'
P1:='abc'
P2:='.ini'
S== 'abc.ini'
P1:='c:/windows/abc.txt'
P2:='.ini'
S=='c:/windows/abc.ini'
P1:='abc.txt'
P2:='ini'
S=='abcini'
**注意:P2的第一位元必須有一點'.ini'
範例
procedure TForm1.ConvertIcon2BitmapClick(Sender: TObject);
var
s : string;
Icon: TIcon;
begin
OpenDialog1.DefaultExt := '.ICO';
OpenDialog1.Filter := 'icons (*.ico)|*.ICO';
OpenDialog1.Options := [ofOverwritePrompt, ofFileMustExist, ofHideReadOnly ];
if OpenDialog1.Execute then
begin
Icon := TIcon.Create;
try
Icon.Loadfromfile(OpenDialog1.FileName);
s:= ChangeFileExt(OpenDialog1.FileName,'.BMP');
Image1.Width := Icon.Width;
Image1.Height := Icon.Height;
Image1.Canvas.Draw(0,0,Icon);
Image1.Picture.SaveToFile(s);
ShowMessage(OpenDialog1.FileName + ' Saved to ' + s);
finally
Icon.Free;
end;
end;
end;
# SaveToFile, Create, Height, Width, Canvas, ChangeFileExt example
--------------------------------------------------------
ExpandFileName 將檔案名稱加在目前所在之路徑全名之後
--------------------------------------------------------
Unit SysUtils
函數原型 function ExpandFileName(const FileName: string): string;
說明 設目前目錄爲 c:/windows 檔案名稱爲 abc.txt
則結果爲 c:/windows/abc.txt
**** 此函數並不是求abc.txt的所在路徑.
範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
begin
S:=ExpandFileName('abc.txt');
Label1.Caption:=S;
end;
範例
procedure TForm1.Button1Click(Sender: TObject)
begin
ListBox1.Items.Add(ExpandFileName(Edit1.Text));
end;
------------------------------------------------------------------
DirectoryExists 目錄是否存在------------------------------------------------------------------
Unit
FileCtrl
uses FileCtrl;
procedure TForm1.Button1Click(Sender: TObject);
begin
if not DirectoryExists('c:/temp') then
if not CreateDir('C:/temp') then
raise Exception.Create('Cannot create c:/temp');
end;
--------------------------------------------------------
ForceDirectories 目錄
---------------------------------------------------------
Unit FileCtrl
函數原型 function ForceDirectories(Dir: string): Boolean;
procedure TForm1.Button1Click(Sender: TObject);
var
Dir: string;
begin
Dir := 'C:/APPS/SALES/LOCAL';
if DirectoryExists(Dir) then
Label1.Caption := Dir + ' was created'
end;
--------------------------------------------------------
ExpandUNCFileName 同上(只是得到網路上的路徑)
--------------------------------------------------------
Unit SysUtils
函數原型 function ExpandUNCFileName(const FileName: string):string;
ExtractFileDir 分析字串中的路徑
Unit SysUtils
函數原型 function ExtractFileDir(const FileName: string): string;
說明 設S字串爲 c:/windows/abc.txt
則結果爲 c:/windows
**** 功能在於由任何部份傳來的叄數,加以分析它的路徑
範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
P1:String;
begin
P1:='c:/windows/abc.txt';
S:=ExtractFileDir(P1);
Label1.Caption:=S;
end;
S=='c:/windows'
P1:='abc.txt'
S=='
P1:='c:abc.txt'
S=='c:'
P1:='c:/abc.txt'
S=='c:/'
--------------------------------------------------------
ExtractFileDrive 分析字串中的磁碟機名稱
--------------------------------------------------------
Unit SysUtils
函數原型 function ExtractFileDrive(const FileName: string): string;
**** 功能同上,只是傳回磁碟機名稱.
範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
P1:String;
begin
P1:='c:/windows/abc.txt';
S:=ExtractFileDrive(P1);
Label1.Caption:=S;
end;
S:='c:'
P1:='abc.txt'
S=='
--------------------------------------------------------
ExtractFileExt 分析字串中的檔案名稱的副檔名
--------------------------------------------------------
Unit SysUtils
函數原型 function ExtractFileExt(const FileName: string): string;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
P1:String;
begin
P1:='c:/windows/abc.txt';
S:=ExtractFileExt(P1);
Label1.Caption:=S;
end;
S=='.txt'
P1:='c:/windows/abc'
S=='
範例 MyFilesExtension := ExtractFileExt(MyFileName);
--------------------------------------------------------
ExtractFileName 分析字串中的檔案名稱(只傳回檔案名稱)
--------------------------------------------------------
Unit SysUtils
函數原型 function ExtractFileName(const FileName: string): string;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
P1:String;
begin
P1:='c:/windows/abc.txt';
S:=ExtractFileName(P1);
Label1.Caption:=S;
end;
S=='abc.txt'
範例
procedure TForm1.Button1Click(Sender: TObject);
var
BackupName: string;
FileHandle: Integer;
StringLen: Integer;
X: Integer;
Y: Integer;
begin
if SaveDialog1.Execute then
begin
if FileExists(SaveDialog1.FileName) then
begin
BackupName := ExtractFileName(SaveDialog1.FileName);
BackupName := ChangeFileExt(BackupName, '.BAK');
if not RenameFile(SaveDialog1.FileName, BackupName) then
raise Exception.Create('Unable to create backup file.');
end;
FileHandle := FileCreate(SaveDialog1.FileName);
{ Write out the number of rows and columns in the grid. }
FileWrite(FileHandle,
StringGrid1.ColCount, SizeOf(StringGrid1.ColCount));
FileWrite(FileHandle,
StringGrid1.RowCount, SizeOf(StringGrid1.RowCount));
for X := 0 to StringGrid1.ColCount ? 1 do
begin
for Y := 0 to StringGrid1.RowCount ? 1 do
begin
{ Write out the length of each string, followed by the string itself. }
StringLen := Length(StringGrid1.Cells[X,Y]);
FileWrite(FileHandle, StringLen, SizeOf(StringLen));
FileWrite(FileHandle,
StringGrid1.Cells[X,Y], Length(StringGrid1.Cells[X,Y]);
end;
end;
FileClose(FileHandle);
end;
end;
##FileExists, RenameFile, FileCreate, FileWrite, FileClose, ExtractFileName Example
--------------------------------------------------------
ExtractFilePath 分析字串中的路徑
--------------------------------------------------------
Unit SysUtils
函數原型 function ExtractFilePath(const FileName: string): string;
說明 設S字串爲 c:/windows/abc.txt
則結果爲 c:/windows範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
P1:String;
begin
P1:='c:/windows/abc.txt';
S:=ExtractFilePath(P1);
Label1.Caption:=S;
end;
範例
begin
with Session do
begin
ConfigMode := cmSession;
try
AddStandardAlias('TEMPDB', ExtractFilePath(ParamStr(0)), 'PARADOX');
finally
ConfigMode := cmAll;
end;
end;
##ConfigMode, AddStandardAlias, ExtractFilePath example
--------------------------------------------------------
FileSearch 尋找檔案在磁碟機中的正確路徑
--------------------------------------------------------
Unit SysUtils
函數原型 function FileSearch(const Name, DirList: string): string;
範例 var
s:string;
begin
s:= FileSearch('abc.txt', 'c:/window/');
Label1.Caption:=s;
end;
說明 找到傳回c:/window/abc.txt 找不到傳回空字串.
範例
procedure TForm1.Button1Click(Sender: TObject);
var
buffer: array [0..255] of char;
FileToFind: string;
begin
GetWindowsDirectory(buffer, SizeOf(buffer));
FileToFind := FileSearch(Edit1.Text, GetCurrentDir + ';' + buffer);
if FileToFind = ' then
ShowMessage('Couldn't find ' + Edit1.Text + '.')
else
ShowMessage('Found ' + FileToFind + '.');
end;
##FileSearch, ShowMessage Example
--------------------------------------------------------
FileAge 傳回檔案的日期及時間(DOS型態).
--------------------------------------------------------
Unit SysUtils
函數原型 function FileAge(const FileName: string): Integer;
說明 就是檔案總管中檔案內容裹面的修改日期.
範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
FileDate1:Integer;
DateTime1:TDateTime;
begin
FileDate1 := FileAge('c:/delphi_d/delphi_help1.txt');
DateTime1 := FileDateToDateTime(FileDate1);
S := DateTimeToStr(DateTime1);
Label1.Caption:=S;
end;
--------------------------------------------------------
FileDateToDateTime 將DOS型態的日期時間轉換爲TDateTime型態.
--------------------------------------------------------
Unit SysUtils
函數原型 function FileDateToDateTime(FileDate: Integer):TDateTime;
-----------------------------------------------------------------------------
DateTimeToFileDate 將TDateTime型態的日期時間轉換爲 DOS型態.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function DateTimeToFileDate(DateTime: TDateTime):Integer;
FileGetDate 傳回檔案的日期及時間(DOS型態).
Unit SysUtils
函數原型 function FileGetDate(Handle: Integer): Integer;
說明 就是檔案總管中檔案內容裹面的修改日期.
範例 procedure TForm1.Button1Click(Sender: TObject);
var
FileHandle:Integer;
S: String;
FileDate1:Integer;
DateTime1:TDateTime;
begin
FileHandle :=FileOpen('c:/delphi_d/delphi_help2.txt',
fmOpenReadWrite);
if FileHandle > 0 then
Begin
FileDate1 := FileGetDate(FileHandle);
DateTime1 := FileDateToDateTime(FileDate1);
S := DateTimeToStr(DateTime1);
FileClose(FileHandle);
End
else
S := 'Open File Error';
Label1.Caption:=S;
end;
-----------------------------------------------------------------------------
FileSetDate 設定檔案的日期及時間(DOS型態).
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileSetDate(Handle: Integer; Age: Integer): Integer;
說明 傳回值爲0表示成功.
-----------------------------------------------------------------------------
DeleteFile 刪除檔案
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function DeleteFile(const FileName: string): Boolean;
範例 一 DeleteFile('DELETE.ME');
範例 二 if FileExists(FileName) then
if MessageDlg('Do you really want to delete ' +
ExtractFileName(FileName) + '?'), []) = IDYes then
DeleteFile(FileName);
##FileExists, DeleteFile Example
-----------------------------------------------------------------------------
RenameFile 更改檔名
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function RenameFile(const OldName, NewName: string):Boolean;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
BackupName: string;
FileHandle: Integer;
StringLen: Integer;
X: Integer;
Y: Integer;
begin
if SaveDialog1.Execute then
begin
if FileExists(SaveDialog1.FileName) then
begin
BackupName := ExtractFileName(SaveDialog1.FileName);
BackupName := ChangeFileExt(BackupName, '.BAK');
if not RenameFile(SaveDialog1.FileName, BackupName) then
raise Exception.Create('Unable to create backup file.');
end;
FileHandle := FileCreate(SaveDialog1.FileName);
{ Write out the number of rows and columns in the grid. }
FileWrite(FileHandle,
StringGrid1.ColCount, SizeOf(StringGrid1.ColCount));
FileWrite(FileHandle,
StringGrid1.RowCount, SizeOf(StringGrid1.RowCount));
for X := 0 to StringGrid1.ColCount ? 1 do
begin
for Y := 0 to StringGrid1.RowCount ? 1 do
begin
{ Write out the length of each string, followed by the string itself. }
StringLen := Length(StringGrid1.Cells[X,Y]);
FileWrite(FileHandle, StringLen, SizeOf(StringLen));
FileWrite(FileHandle,
StringGrid1.Cells[X,Y], Length(StringGrid1.Cells[X,Y]);
end;
end;
FileClose(FileHandle);
end;
end;
-----------------------------------------------------------------------------
DiskFree 磁碟機剩餘空間(Bytes)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function DiskFree(Drive: Byte): Integer;
範例 var
S: string;
begin
S := IntToStr(DiskFree(0) div 1024) + ' Kbytes free.';
Label1.Caption:=S;
end;
說明 Drive
0=目前磁碟機,1=A磁碟機,2=B磁碟機...傳回值若爲-1,表示磁碟機偵測錯誤.
範例
var
S: string;
AmtFree: Int64;
Total: Int64;
begin
AmtFree := DiskFree(0);
Total := DiskSize(0);
S := IntToStr(AmtFree div Total) + 'percent of the space on drive 0 is free: ' (AmtFree div 1024) + ' Kbytes free. ';
Canvas.TextOut(10, 10, S);
end;
##DiskFree, DiskSize Example
-----------------------------------------------------------------------------
DiskSize 磁碟機空間大小(Bytes)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function DiskSize(Drive: Byte): Integer;
範例 var
S: string;
begin
S := IntToStr(DiskSize(0) div 1024) + ' Kbytes free.';
Label1.Caption:=S;
end;
說明 Drive
0=目前磁碟機,1=A磁碟機,2=B磁碟機....傳回值若爲-1,表示磁碟機偵測錯誤.
##DiskFree, DiskSize Example
-----------------------------------------------------------------------------
FileExists 判斷檔案是否存在.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileExists(const FileName: string): Boolean;
類似 FileExists, RenameFile, FileCreate, FileWrite, FileClose, ExtractFileName Example
範例
procedure TForm1.Button1Click(Sender: TObject);
var
BackupName: string;
FileHandle: Integer;
StringLen: Integer;
X: Integer;
Y: Integer;
begin
if SaveDialog1.Execute then
begin
if FileExists(SaveDialog1.FileName) then
begin
BackupName := ExtractFileName(SaveDialog1.FileName);
BackupName := ChangeFileExt(BackupName, '.BAK');
if not RenameFile(SaveDialog1.FileName, BackupName) then
raise Exception.Create('Unable to create backup file.');
end;
FileHandle := FileCreate(SaveDialog1.FileName);
{ Write out the number of rows and columns in the grid. }
FileWrite(FileHandle,
StringGrid1.ColCount, SizeOf(StringGrid1.ColCount));
FileWrite(FileHandle,
StringGrid1.RowCount, SizeOf(StringGrid1.RowCount));
for X := 0 to StringGrid1.ColCount ? 1 do
begin
for Y := 0 to StringGrid1.RowCount ? 1 do
begin
{ Write out the length of each string, followed by the string itself. }
StringLen := Length(StringGrid1.Cells[X,Y]);
FileWrite(FileHandle, StringLen, SizeOf(StringLen));
FileWrite(FileHandle,
StringGrid1.Cells[X,Y], Length(StringGrid1.Cells[X,Y]);
end;
end;
FileClose(FileHandle);
end;
end;
##FileExists, DeleteFile Example
##FileExists, RenameFile, FileCreate, FileWrite, FileClose, ExtractFileName Example
-----------------------------------------------------------------------------
FileOpen 開檔.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileOpen(const FileName: string; Mode:
Integer):Integer;
**** 開檔失敗傳回-1.
說明 以下有關檔案讀取都屬低階,如Dos Int 21h中有關檔案的部
分.
fmOpenRead = $0000;
fmOpenWrite = $0001;
fmOpenReadWrite = $0002;
fmShareCompat = $0000;
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyRead = $0030;
fmShareDenyNone = $0040;
fmOpenRead Open for read access only.
FmOpenWrite Open for write access only.
FmOpenReadWrite Open for read and write access.
fmShareCompat Compatible with the way FCBs are
opened.
fmShareExclusive Read and write access is denied.
fmShareDenyWrite Write access is denied.
fmShareDenyRead Read access is denied.
fmShareDenyNone Allows full access for others.
範例
procedure OpenForShare(const FileName: String);
var
FileHandle : Integer;
begin
FileHandle := FileOpen(FileName, fmOpenWrite or fmShareDenyNone);
if FileHandle > 0 then
{valid file handle}
else
{Open error: FileHandle = negative DOS error code}
end;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
iFileHandle: Integer;
iFileLength: Integer;
iBytesRead: Integer;
Buffer: PChar;
i: Integer
begin
if OpenDialog1.Execute then
begin
try
iFileHandle := FileOpen(OpenDialog1.FileName, fmOpenRead);
iFileLength := FileSeek(iFileHandle,0,2);
FileSeek(iFileHandle,0,0);
Buffer := PChar(AllocMem(iFileLength + 1));
iBytesRead = FileRead(iFileHandle, Buffer, iFileLength);
FileClose(iFileHandle);
for i := 0 to iBytesRead-1 do
begin
StringGrid1.RowCount := StringGrid1.RowCount + 1;
StringGrid1.Cells[1,i+1] := Buffer[i];
StringGrid1.Cells[2,i+1] := IntToStr(Integer(Buffer[i]));
end;
finally
FreeMem(Buffer);
end;
end;
end;
##FileOpen, FileSeek, FileRead Example
-----------------------------------------------------------------------------
FileCreate 建檔
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileCreate(const FileName: string): Integer;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
BackupName: string;
FileHandle: Integer;
StringLen: Integer;
X: Integer;
Y: Integer;
begin
if SaveDialog1.Execute then
begin
if FileExists(SaveDialog1.FileName) then
begin
BackupName := ExtractFileName(SaveDialog1.FileName);
BackupName := ChangeFileExt(BackupName, '.BAK');
if not RenameFile(SaveDialog1.FileName, BackupName) then
raise Exception.Create('Unable to create backup file.');
end;
FileHandle := FileCreate(SaveDialog1.FileName);
{ Write out the number of rows and columns in the grid. }
FileWrite(FileHandle,
StringGrid1.ColCount, SizeOf(StringGrid1.ColCount));
FileWrite(FileHandle,
StringGrid1.RowCount, SizeOf(StringGrid1.RowCount));
for X := 0 to StringGrid1.ColCount ? 1 do
begin
for Y := 0 to StringGrid1.RowCount ? 1 do
begin
{ Write out the length of each string, followed by the string itself. }
StringLen := Length(StringGrid1.Cells[X,Y]);
FileWrite(FileHandle, StringLen, SizeOf(StringLen));
FileWrite(FileHandle,
StringGrid1.Cells[X,Y], Length(StringGrid1.Cells[X,Y]);
end;
end;
FileClose(FileHandle);
end;
end;
##FileExists, RenameFile, FileCreate, FileWrite, FileClose, ExtractFileName Example
-----------------------------------------------------------------------------
FileClose 關檔
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 procedure FileClose(Handle: Integer);
範例
procedure TForm1.Button1Click(Sender: TObject);
var
BackupName: string;
FileHandle: Integer;
StringLen: Integer;
X: Integer;
Y: Integer;
begin
if SaveDialog1.Execute then
begin
if FileExists(SaveDialog1.FileName) then
begin
BackupName := ExtractFileName(SaveDialog1.FileName);
BackupName := ChangeFileExt(BackupName, '.BAK');
if not RenameFile(SaveDialog1.FileName, BackupName) then
raise Exception.Create('Unable to create backup file.');
end;
FileHandle := FileCreate(SaveDialog1.FileName);
{ Write out the number of rows and columns in the grid. }
FileWrite(FileHandle,
StringGrid1.ColCount, SizeOf(StringGrid1.ColCount));
FileWrite(FileHandle,
StringGrid1.RowCount, SizeOf(StringGrid1.RowCount));
for X := 0 to StringGrid1.ColCount ? 1 do
begin
for Y := 0 to StringGrid1.RowCount ? 1 do
begin
{ Write out the length of each string, followed by the string itself. }
StringLen := Length(StringGrid1.Cells[X,Y]);
FileWrite(FileHandle, StringLen, SizeOf(StringLen));
FileWrite(FileHandle,
StringGrid1.Cells[X,Y], Length(StringGrid1.Cells[X,Y]);
end;
end;
FileClose(FileHandle);
end;
end;
##FileExists, RenameFile, FileCreate, FileWrite, FileClose, ExtractFileName Example
============================================
**** 它是以Handle爲叄數.
============================================
FileRead 讀取檔案
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileRead(Handle: Integer; var Buffer; Count: Integer):Integer;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
iFileHandle: Integer;
iFileLength: Integer;
iBytesRead: Integer;
Buffer: PChar;
i: Integer
begin
if OpenDialog1.Execute then
begin
try
iFileHandle := FileOpen(OpenDialog1.FileName, fmOpenRead);
iFileLength := FileSeek(iFileHandle,0,2);
FileSeek(iFileHandle,0,0);
Buffer := PChar(AllocMem(iFileLength + 1));
iBytesRead = FileRead(iFileHandle, Buffer, iFileLength);
FileClose(iFileHandle);
for i := 0 to iBytesRead-1 do
begin
StringGrid1.RowCount := StringGrid1.RowCount + 1;
StringGrid1.Cells[1,i+1] := Buffer[i];
StringGrid1.Cells[2,i+1] := IntToStr(Integer(Buffer[i]));
end;
finally
FreeMem(Buffer);
end;
end;
end;
##FileOpen, FileSeek, FileRead Example
-----------------------------------------------------------------------------
FileWrite 寫入檔案
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileWrite(Handle: Integer; const Buffer; Count: Integer): Integer;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
BackupName: string;
FileHandle: Integer;
StringLen: Integer;
X: Integer;
Y: Integer;
begin
if SaveDialog1.Execute then
begin
if FileExists(SaveDialog1.FileName) then
begin
BackupName := ExtractFileName(SaveDialog1.FileName);
BackupName := ChangeFileExt(BackupName, '.BAK');
if not RenameFile(SaveDialog1.FileName, BackupName) then
raise Exception.Create('Unable to create backup file.');
end;
FileHandle := FileCreate(SaveDialog1.FileName);
{ Write out the number of rows and columns in the grid. }
FileWrite(FileHandle,
StringGrid1.ColCount, SizeOf(StringGrid1.ColCount));
FileWrite(FileHandle,
StringGrid1.RowCount, SizeOf(StringGrid1.RowCount));
for X := 0 to StringGrid1.ColCount do
begin
for Y := 0 to StringGrid1.RowCount do
begin
{ Write out the length of each string, followed by the string itself. }
StringLen := Length(StringGrid1.Cells[X,Y]);
FileWrite(FileHandle, StringLen, SizeOf(StringLen));
FileWrite(FileHandle,
StringGrid1.Cells[X,Y], Length(StringGrid1.Cells[X,Y]);//?????????/
end;
end;
FileClose(FileHandle);
end;
end;
##FileExists, RenameFile, FileCreate, FileWrite, FileClose, ExtractFileName Example
-----------------------------------------------------------------------------
FileSeek 移動檔案指標位置
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileSeek(Handle, Offset, Origin: Integer): Integer;
說明 Origin=0讀/寫指標由檔案開頭算起.
Origin=1讀/寫指標由目前位置算起.
Origin=2讀/寫指標移動到檔案結束處.
**** 功能與Dos Int 21h 插斷 42h 的功能相同.
失敗傳回-1.
範例 procedure TForm1.Button1Click(Sender: TObject);
var
FileHandle : Integer;
FileName : String;
Buffer : PChar;
S : String;
ReadBytes : Integer;
begin
FileName:='c:/delphi_test/abc.ttt';
S:='1234567890';
if FileExists(FileName) then
FileHandle := FileOpen(FileName, fmOpenReadWrite)
else
FileHandle := FileCreate(FileName);
if FileHandle < 0 then
Begin
MessageDlg('開檔失敗', mtInformation, [mbOk], 0);
Exit;
End;
GetMem(Buffer, 100);
try
StrPCopy(Buffer, S);
FileWrite(FileHandle,Buffer^,10);
FileSeek(FileHandle,4,0);
ReadBytes:=FileRead(FileHandle, Buffer^, 100);
Buffer[ReadBytes]:=#0;
Label1.Caption:=IntToStr(ReadBytes)+' '+
StrPas(Buffer);
finally
FreeMem(Buffer);
end;
FileClose(FileHandle);
end;
結果 存檔後abc.ttt共有1234567890等十個Bytes.
從第五位元開始讀取,共讀取六個位元.
567890
(位移是從0開始算起)
procedure TForm1.Button1Click(Sender: TObject);
var
iFileHandle: Integer;
iFileLength: Integer;
iBytesRead: Integer;
Buffer: PChar;
i: Integer
begin
if OpenDialog1.Execute then
begin
try
iFileHandle := FileOpen(OpenDialog1.FileName, fmOpenRead);
iFileLength := FileSeek(iFileHandle,0,2);
FileSeek(iFileHandle,0,0);
Buffer := PChar(AllocMem(iFileLength + 1));
iBytesRead = FileRead(iFileHandle, Buffer, iFileLength);
FileClose(iFileHandle);
for i := 0 to iBytesRead-1 do
begin
StringGrid1.RowCount := StringGrid1.RowCount + 1;
StringGrid1.Cells[1,i+1] := Buffer[i];
StringGrid1.Cells[2,i+1] := IntToStr(Integer(Buffer[i]));
end;
finally
FreeMem(Buffer);
end;
end;
end;
##FileOpen, FileSeek, FileRead Example
-----------------------------------------------------------------------------
FileGetAttr 檔案屬性
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileGetAttr(const FileName: string): Integer;
說明 faReadOnly = $00000001;
faHidden = $00000002;
faSysFile = $00000004;
faVolumeID = $00000008;
faDirectory = $00000010;
faArchive = $00000020;
faAnyFile = $0000003F;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
begin
S:=IntToStr(FileGetAttr('c:/delphi_d/delphi_help1.txt'));
Label1.Caption := S;
end;
-----------------------------------------------------------------------------
FileSetAttr 設定檔案屬性
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FileSetAttr(const FileName: string; Attr: Integer):
Integer;
說明 設定成功傳回0
-----------------------------------------------------------------------------
FindClose 結束FindFirst/FindNext
-----------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
sr: TSearchRec;
FileAttrs: Integer;
begin
StringGrid1.RowCount := 1;
if CheckBox1.Checked then
FileAttrs := faReadOnly
else
FileAttrs := 0;
if CheckBox2.Checked then
FileAttrs := FileAttrs + faHidden;
if CheckBox3.Checked then
FileAttrs := FileAttrs + faSysFile;
if CheckBox4.Checked then
FileAttrs := FileAttrs + faVolumeID;
if CheckBox5.Checked then
FileAttrs := FileAttrs + faDirectory;
if CheckBox6.Checked then
FileAttrs := FileAttrs + faArchive;
if CheckBox7.Checked then
FileAttrs := FileAttrs + faAnyFile;
if FindFirst(Edit1.Text, FileAttrs, sr) = 0 then
begin
with StringGrid1 do
begin
if (sr.Attr and FileAttrs) = sr.Attr then
begin
Cells[1,RowCount-1] := sr.Name;
Cells[2,RowCount-1] := IntToStr(sr.Size);
end;
while FindNext(sr) = 0 do
begin
if (sr.Attr and FileAttrs) = sr.Attr then
begin
RowCount := RowCount + 1;
Cells[1, RowCount-1] := sr.Name;
Cells[2, RowCount-1] := IntToStr(sr.Size);
end;
end;
FindClose(sr);
end;
end;
end;
##FindFirst, FindNext, FindClose Example
-----------------------------------------------------------------------------
FindFirst 尋找第一個符合的檔案.
-----------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
sr: TSearchRec;
FileAttrs: Integer;
begin
StringGrid1.RowCount := 1;
if CheckBox1.Checked then
FileAttrs := faReadOnly
else
FileAttrs := 0;
if CheckBox2.Checked then
FileAttrs := FileAttrs + faHidden;
if CheckBox3.Checked then
FileAttrs := FileAttrs + faSysFile;
if CheckBox4.Checked then
FileAttrs := FileAttrs + faVolumeID;
if CheckBox5.Checked then
FileAttrs := FileAttrs + faDirectory;
if CheckBox6.Checked then
FileAttrs := FileAttrs + faArchive;
if CheckBox7.Checked then
FileAttrs := FileAttrs + faAnyFile;
if FindFirst(Edit1.Text, FileAttrs, sr) = 0 then
begin
with StringGrid1 do
begin
if (sr.Attr and FileAttrs) = sr.Attr then
begin
Cells[1,RowCount-1] := sr.Name;
Cells[2,RowCount-1] := IntToStr(sr.Size);
end;
while FindNext(sr) = 0 do
begin
if (sr.Attr and FileAttrs) = sr.Attr then
begin
RowCount := RowCount + 1;
Cells[1, RowCount-1] := sr.Name;
Cells[2, RowCount-1] := IntToStr(sr.Size);
end;
end;
FindClose(sr);
end;
end;
end;
##FindFirst, FindNext, FindClose Example
-----------------------------------------------------------------------------
FindNext 尋找下一個符合的檔案.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 procedure FindClose(var F: TSearchRec);
函數原型 function FindFirst(const Path: string; Attr: Integer;
var F: TSearchRec): Integer;
函數原型 function FindNext(var F: TSearchRec): Integer;
說明 成功傳回0
範例 var
SRec: TSearchRec;
procedure TForm1.SearchClick(Sender: TObject);
begin
FindFirst('c:/delphi/bin/*.*', faAnyFile, SRec);
Label1.Caption := SRec.Name + ' is ' + IntToStr(SRec.Size) +
' bytes in size';
end;
procedure TForm1.AgainClick(Sender: TObject);
begin
FindNext(SRec);
Label1.Caption := SRec.Name + ' is ' + IntToStr(SRec.Size) +
' bytes in size';
end;
procedure TForm1.FormClose(Sender: TObject);
begin
FindClose(SRec);
end
TSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: TFileName;
xcludeAttr: Integer;
FindHandle: THandle;
FindData: TWin32FindData;
end;
============================================
Floating-point conversion routines 浮點數轉換函式
============================================
FloatToDecimal 將浮點數轉換爲十進位數.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 procedure FloatToDecimal(var Result: TFloatRec; const Value;
ValueType: TFloatValue; Precision, Decimals: Integer);
-----------------------------------------------------------------------------
FloatToStrF 將浮點數轉換爲格式化字串.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FloatToStrF(Value: Extended; Format: TFloatFormat;
Precision,Digits: Integer): string;
-----------------------------------------------------------------------------
FloatToStr 將浮點數轉換爲字串.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FloatToStr(Value: Extended): string;
-----------------------------------------------------------------------------
FloatToText 將浮點數轉換爲格式化十進位.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FloatToText(Buffer: PChar; const Value; ValueType:
TFloatValue;Format: TFloatFormat; Precision, Digits:
Integer): Integer;
-----------------------------------------------------------------------------
FloatToTextFmt 將浮點數轉換爲格式化十進位.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FloatToTextFmt(Buffer: PChar; const Value;
ValueType: TFloatValue; Format: PChar): Integer;
-----------------------------------------------------------------------------
FormatFloat 將浮點數轉換爲格式化字串.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function FormatFloat(const Format: string; Value: Extended):
string;
-----------------------------------------------------------------------------
StrToFloat 將字串轉換爲浮點數.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrToFloat(const S: string): Extended;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
Value:Double;
S:String;
begin
S:=' 1234.56 ';
Value:=StrToFloat(S);
Label1.Caption:=Format('轉換爲 [%9.3f]',[Value]);
end;
注意 若S字串含有非數字字元,會產生錯誤訊號.
-----------------------------------------------------------------------------
TextToFloat 將 null-terminated 字串轉換爲浮點數.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function TextToFloat(Buffer: PChar; var Value; ValueType:
TFloatValue): Boolean;
===========================================
Flow-control routines 流程控制常式
===========================================
Break 從 for, while, or repeat 終止跳出.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Break;
範例 var
S: string;
begin
while True do
begin
ReadLn(S);
try
if S = ' then Break;
WriteLn(S);
finally
{ do something for all cases }
end;
end;
end;
-----------------------------------------------------------------------------
Continue 從 for, while, or repeat 繼續執行.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Continue;
範例 var
F: File;
i: integer;
begin
for i := 0 to (FileListBox1.Items.Count - 1) do
begin
try
if FileListBox1.Selected[i] then
begin
if not FileExists(FileListBox1.Items.Strings[i]) then
begin
MessageDlg('File: ' +FileListBox1.Items.Strings[i]
+ ' not found', mtError, [mbOk], 0);
Continue;
end;
AssignFile(F, FileListBox1.Items.Strings[i]);
Reset(F, 1);
ListBox1.Items.Add(IntToStr(FileSize(F)));
CloseFile(F);
end;
finally
{ do something here }
end;
end;
end;
範例
var
F: File;
i: Integer;
begin
for i := 0 to (FileListBox1.Items.Count - 1) do begin
try
if FileListBox1.Selected[i] then
begin
if not FileExists(FileListBox1.Items.Strings[i]) then begin
MessageDlg('File: ' + FileListBox1.Items.Strings[i] +
' not found', mtError, [mbOk], 0);
Continue;
end;
AssignFile(F, FileListBox1.Items.Strings[i]);
Reset(F, 1);
ListBox1.Items.Add(IntToStr(FileSize(F)));
CloseFile(F);
end;
finally
{ do something here }
end;
end;
end;
## Continue, Items, Selected Example
-----------------------------------------------------------------------------
Exit 直接離開一個程序.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Exit;
-----------------------------------------------------------------------------
Halt 結束程式返回作業系統.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Halt [ ( Exitcode: Integer) ];
範例 begin
if 1 = 1 then
begin
if 2 = 2 then
begin
if 3 = 3 then
begin
Halt(1); { Halt right here! }
end;
end;
end;
Canvas.TextOut(10, 10, 'This will not be executed');
end;
-----------------------------------------------------------------------------
RunError 停止程式執行且執行run-time error.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure RunError [ ( Errorcode: Byte ) ];
範例 begin
{$IFDEF Debug}
if P = nil then
RunError(204);
{$ENDIF}
end;
=====================================
I/O routines I/O常式
=====================================
AssignFile 指定檔案給一個檔案變數.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure AssignFile(var F; FileName: string);
說明 **一個檔案不可重複執行AssignFile兩次以上.
Example
var
F: TextFile;
S: string;
begin
if OpenDialog1.Execute then { Display Open dialog box }
begin
AssignFile(F, OpenDialog1.FileName); { File selected in dialog box }
Reset(F);
Readln(F, S); { Read the first line out of the file }
Edit1.Text := S; { Put string in a TEdit control }
CloseFile(F);
end;
end;
## AssignFile, OpenDialog, Readln, CloseFile Example
-----------------------------------------------------------------------------
CloseFile 關閉檔案.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure CloseFile(var F);
#### AssignFile, OpenDialog, Readln, CloseFile Example
-----------------------------------------------------------------------------
IOResult 傳回最近一次執行I/O函數,是否有錯誤.
-----------------------------------------------------------------------------
Unit System
函數原型 function IOResult: Integer;
範例 var
F: file of Byte;
S: String;
begin
S:= 'c:/ka/aaa.txt';
AssignFile(F, S);
{$I-}
Reset(F);
{$I+}
if IOResult = 0 then
Label1.Caption:='File size in bytes: ' +
IntToStr(FileSize(F);
else
Label1.Caption:='開檔失敗';
end;
說明 傳回0表示沒有錯誤.
EXAMPLE
var
F: file of Byte;
begin
if OpenDialog1.Execute then begin
AssignFile(F, OpenDialog1.FileName);
{$I-}
Reset(F);
{$I+}
if IOResult = 0 then
MessageDlg('File size in bytes: ' + IntToStr(FileSize(F)),
mtInformation, [mbOk], 0)
else
MessageDlg('File access error', mtWarning, [mbOk], 0);
end;
end;
-----------------------------------------------------------------------------
Reset 開起一個可供讀取的檔案.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Reset(var F [: File; RecSize: Word ] );
-----------------------------------------------------------------------------
Rewrite 建立一個可供寫入的新檔案.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Rewrite(var F: File [; Recsize: Word ] );
範例 procedure TForm1.Button1Click(Sender: TObject);
var
F: TextFile;
I1,I2,I3:Integer;
S1,S2,S3:String;
begin
I1:=1234;
I2:=5678;
I3:=90;
S1:='abcd';
S2:='efgh';
S3:='ij';
AssignFile(F,'c:/ka/aaa.txt');
Rewrite(F);
Write(F,I1);
Write(F,I2);
Write(F,I3);
Write(F,S1);
Write(F,S2);
Write(F,S3);
Write(F,I1,I2,I3);
Write(F,S1,S2,S3);
Writeln(F,I1);
Writeln(F,I2);
Writeln(F,I3);
Writeln(F,S1);
Writeln(F,S2);
Writeln(F,S3);
Writeln(F,I1,I2,I3);
Writeln(F,S1,S2,S3);
Reset(F);
Readln(F, S1);
Readln(F, I1);
Label1.Caption:=S1+' '+IntToStr(I1);
CloseFile(F);
end;
結果 1234567890abcdefghij1234567890abcdefghij1234..
5678..
90..
abcd..
efgh..
ij..
1234567890..
abcdefghij..
abcdefghij..
以上是存檔結果,兩點代表#13#10,兩個位元.
以Writeln存檔者,多出換行符號#13#10.
且如果以Writeln(F,I1,I2,I3)會當成同一串列,
變數間沒有間隔符號,造成Read時得不到預期的效果.
讀取結果
S1=1234567890abcdefghij1234567890abcdefghij1234
長度44且不含#13#10兩個位元.
I1=5678
** Write(F,I1:10:2,I2:8:2);
具有格式化的功能,如同Str.
範例 procedure TForm1.Button1Click(Sender: TObject);
var
F: file of Byte;
I1,I2,I3:Byte;
begin
I1:=16;
I2:=32;
I3:=48;
AssignFile(F,'c:/ka/aaa.txt');
Rewrite(F);
Write(F,I1);
Write(F,I2);
Write(F,I3);
Write(F,I1,I2,I3);
I1:=0;
Reset(F);
Read(F, I1);
Label1.Caption:=IntToStr(I1);
CloseFile(F);
end;
結果 file of Byte 及 file of record
只能以Write及Read,來寫入及讀取,
不可以Writeln及Readln.
範例 procedure TForm1.Button1Click(Sender: TObject);
type
ppRec = record
pp_No:String[5];
pp_Name:String[10];
pp_Age:Integer;
pp_Sum:Double;
end;
var
Rec : ppRec;
Rec2: ppRec;
F: file of ppRec;
begin
With Rec do
Begin
pp_No:='0001';
pp_Name:='abc';
pp_Age:=12;
pp_Sum:=600;
End;
AssignFile(F,'c:/ka/aaa.txt');
Rewrite(F);
Write(F,Rec);
Rec.pp_No:='0002';
Rec.pp_Sum:=58.2;
Write(F,Rec);
Rec.pp_No:='0003';
Rec.pp_Sum:=258.242;
Write(F,Rec);
seek(F,1);
Read(F,Rec2);
seek(F,1);
Truncate(F); {刪除,只剩第0筆}
Canvas.TextOut(5,10,Rec2.pp_No);
Canvas.TextOut(5,30,Rec2.pp_Name);
Canvas.TextOut(5,50,Format('%d',[Rec2.pp_Age]));
Canvas.TextOut(5,70,Format('%f',[Rec2.pp_Sum]));
CloseFile(F);
end;
結果 pp_No存入6 Bytes
pp_Name存入11 Bytes
pp_Age存入4 Bytes(Integer 4 Bytes)
pp_Sum存入8 Bytes(Double 8 Bytes)
整個Record以16的倍數存檔.
EXAMPLE
var F: TextFile;
begin
AssignFile(F, 'NEWFILE.$$$');
Rewrite(F);
Writeln(F, 'Just created file with this text in it...');
CloseFile(F);
end;
-----------------------------------------------------------------------------
Seek 移動檔案指標.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Seek(var F; N: Longint);
說明 Seek從0開始.
Example
var
f: file of Byte;
size : Longint;
S: string;
y: Integer;
begin
if OpenDialog1.Execute then
begin
AssignFile(f, OpenDialog1.FileName);
Reset(f);
size := FileSize(f);
S := 'File size in bytes: ' + IntToStr(size);
y := 10;
Canvas.TextOut(5, y, S);
y := y + Canvas.TextHeight(S) + 5;
S := 'Seeking halfway into file...';
Canvas.TextOut(5, y, S);
y := y + Canvas.TextHeight(S) + 5;
Seek(f,size div 2);
S := 'Position is now ' + IntToStr(FilePos(f));
Canvas.TextOut(5, y, S);
CloseFile(f);
end;
end;
## FileSize, Seek, FilePos Example
-----------------------------------------------------------------------------
Truncate 將目前檔案指標位置之後的檔案內容全部刪除.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Truncate(var F);
範例
var
f: file of Integer;
i,j: Integer;
begin
AssignFile(f,'TEST.INT');
Rewrite(f);
for i := 1 to 6 do
Write(f,i);
Writeln('File before truncation:');
Reset(f);
while not Eof(f) do
begin
Read(f,i);
Writeln(i);
end;
Reset(f);
for i := 1 to 3 do
Read(f,j); { Read ahead 3 records }
Truncate(f); { Cut file off here }
Writeln;
Writeln('File after truncation:');
Reset(f);
while not Eof(f) do
begin
Read(f,i);
Writeln(i);
end;
CloseFile(f);
Erase(f);
end;
-----------------------------------------------------------------------------
FilePos 傳回目前檔案的位置.
-----------------------------------------------------------------------------
Unit System
函數原型 function FilePos(var F): Longint
說明 F 不可爲 Text File
檔頭 :FilePos(F):=0;
檔尾 :Eof(F):=True;
範例 var
f: file of Byte;
S: string;
begin
S:= 'c:/ka/abc.txt';
AssignFile(f, S);
Reset(f);
Seek(f,1);
Label1.Caption := '現在位置 : ' + IntToStr(FilePos(f));
end;
Example
var
f: file of Byte;
size : Longint;
S: string;
y: Integer;
begin
if OpenDialog1.Execute then
begin
AssignFile(f, OpenDialog1.FileName);
Reset(f);
size := FileSize(f);
S := 'File size in bytes: ' + IntToStr(size);
y := 10;
Canvas.TextOut(5, y, S);
y := y + Canvas.TextHeight(S) + 5;
S := 'Seeking halfway into file...';
Canvas.TextOut(5, y, S);
y := y + Canvas.TextHeight(S) + 5;
Seek(f,size div 2);
S := 'Position is now ' + IntToStr(FilePos(f));
Canvas.TextOut(5, y, S);
CloseFile(f);
end;
end;
##FileSize, Seek, FilePos Example
-----------------------------------------------------------------------------
FileSize 檔案長度.
-----------------------------------------------------------------------------
Unit System
函數原型 function FileSize(var F): Integer;
說明 F 不可爲 Text File
如果F爲record file,則傳回record數,
否則傳回Byte數.
## FileSize, Seek, FilePos Example
-----------------------------------------------------------------------------
Eof 測試檔案是否結束.
-----------------------------------------------------------------------------
Unit System
函數原型 function Eof(var F): Boolean;
函數原型 function Eof [ (var F: Text) ]: Boolean;
範例 var
F1, F2: TextFile;
Ch: Char;
begin
if OpenDialog1.Execute then
begin
AssignFile(F1, OpenDialog1.Filename);
Reset(F1);
if SaveDialog1.Execute then
begin
AssignFile(F2, OpenDialog1.Filename);
Rewrite(F2);
while not Eof(F1) do
begin
Read(F1, Ch);
Write(F2, Ch);
end;
CloseFile(F2);
end;
CloseFile(F1);
end;
end;
Example
var
F1, F2: TextFile;
Ch: Char;
begin
if OpenDialog1.Execute then begin
AssignFile(F1, OpenDialog1.Filename);
Reset(F1);
if SaveDialog1.Execute then begin
AssignFile(F2, SaveDialog1.Filename);
Rewrite(F2);
while not Eof(F1) do
begin
Read(F1, Ch);
Write(F2, Ch);
end;
CloseFile(F2);
end;
CloseFile(F1);
end;
end;
-----------------------------------------------------------------------------
OpenPictureDialog OpenDialog 開啓檔案.
-----------------------------------------------------------------------------
//SavePictureDialog1.DefaultExt := GraphicExtension(TBitmap);
//SavePictureDialog1.Filter := GraphicFilter(TBitmap);
procedure TForm1.Button1Click(Sender: TObject);
var
Done: Boolean;
begin
OpenPictureDialog1.DefaultExt := GraphicExtension(TIcon);
OpenPictureDialog1.FileName := GraphicFileMask(TIcon);
OpenPictureDialog1.Filter := GraphicFilter(TIcon);
OpenPictureDialog1.Options := [ofFileMustExist, ofHideReadOnly, ofNoChangeDir ];
while not Done do
begin
if OpenPictureDialog1.Execute then
begin
if not (ofExtensionDifferent in OpenPictureDialog1.Options) then
begin
Application.Icon.LoadFromFile(OpenPictureDialog1.FileName);
Done := True;
end
else
OpenPictureDialog1.Options := OpenPictureDialog1.Options - ofExtensionDifferent;
end
else { User cancelled }
Done := True;
end;
end;
## Eof, Read, Write Example
-----------------------------------------------------------------------------
Erase 刪除檔案.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Erase(var F);
說明 要先關檔後纔可以執行.
範例 procedure TForm1.Button1Click(Sender: TObject);
var
F: Textfile;
begin
OpenDialog1.Title := 'Delete File';
if OpenDialog1.Execute then
begin
AssignFile(F, OpenDialog1.FileName);
try
Reset(F);
if MessageDlg('Erase ' + OpenDialog1.FileName +
'?',mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
CloseFile(F);
Erase(F);
end;
except
on EInOutError do
MessageDlg('File I/O error.', mtError, [mbOk], 0);
end;
end;
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
var
F: Textfile;
begin
OpenDialog1.Title := 'Delete File';
if OpenDialog1.Execute then begin
AssignFile(F, OpenDialog1.FileName);
try
Reset(F);
if MessageDlg('Erase ' + OpenDialog1.FileName + '?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
CloseFile(F);
Erase(F);
end;
except
on EInOutError do
MessageDlg('File I/O error.', mtError, [mbOk], 0);
end;
end;
end;
##Erase, OpenDialog.Title, OpenDialog.FileName Example
-----------------------------------------------------------------------------
Rename 更改檔名.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Rename(var F; Newname);
範例 uses Dialogs;
var
f : file;
begin
OpenDialog1.Title := 'Choose a file... ';
if OpenDialog1.Execute then
begin
SaveDialog1.Title := 'Rename to...';
if SaveDialog1.Execute then
begin
AssignFile(f, OpenDialog1.FileName);
Canvas.TextOut(5, 10, 'Renaming ' +
OpenDialog1.FileName +' to ' +
SaveDialog1.FileName);
Rename(f, SaveDialog1.FileName);
end;
end;
end;
Example
uses Dialogs;
var
f : file;
begin
OpenDialog1.Title := 'Choose a file... ';
if OpenDialog1.Execute then begin
SaveDialog1.Title := 'Rename to...';
if SaveDialog1.Execute then begin
AssignFile(f, OpenDialog1.FileName);
Canvas.TextOut(5, 10, 'Renaming ' + OpenDialog1.FileName + ' to ' +
SaveDialog1.FileName);
Rename(f, SaveDialog1.FileName);
end;
end;
end;
-----------------------------------------------------------------------------
GetDir 傳回指定磁碟機的目錄.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure GetDir(D: Byte; var S: string);
說明 D
0=目前磁碟機,1=A磁碟機,2=B磁碟機....
**此函式不檢查磁碟機錯誤.
範例 var
s : string;
begin
GetDir(0,s); { 0 = Current drive }
MessageDlg('Current drive and directory: ' + s,
mtInformation, [mbOk] , 0);
end;
-----------------------------------------------------------------------------
MkDir 建立子目錄.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure MkDir(S: string);
範例 uses Dialogs;
begin
{$I-}
{ Get directory name from TEdit control }
MkDir(Edit1.Text);
if IOResult <> 0 then
MessageDlg('Cannot create directory', mtWarning,
[mbOk], 0)
else
MessageDlg('New directory created', mtInformation,
[mbOk], 0);
end;
-----------------------------------------------------------------------------
RmDir 刪除一個空的子目錄.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure RmDir(S: string);
範例 uses Dialogs;
begin
{$I-}
{ Get directory name from TEdit control }
RmDir(Edit1.Text);
if IOResult <> 0 then
MessageDlg('Cannot remove directory', mtWarning,
[mbOk], 0)
else
MessageDlg('Directory removed', mtInformation, [mbOk],
0);
end;
-----------------------------------------------------------------------------
ChDir 改變目前目錄.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure ChDir(S: string);
範例 begin
{$I-}
{ Change to directory specified in Edit1 }
ChDir(Edit1.Text);
if IOResult <> 0 then
MessageDlg('Cannot find directory', mtWarning,[mbOk],
0);
end;
==============================================
Memory-management routines 記憶體管理常式
==============================================
AllocMem 配置記憶體.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function AllocMem(Size: Cardinal): Pointer;
說明 FreeMem釋放記憶體.
-----------------------------------------------------------------------------
GetHeapStatus 傳回目前Heap區的記憶體配置狀態.
-----------------------------------------------------------------------------
Unit System
函數原型 function GetHeapStatus: THeapStatus;
-----------------------------------------------------------------------------
GetMemoryManager 傳回目前Heap區的記憶體配置 的進入點.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure GetMemoryManager(var MemMgr:
TMemoryManager);
EXample
var
GetMemCount: Integer;
FreeMemCount: Integer;
ReallocMemCount: Integer;
OldMemMgr: TMemoryManager;
function NewGetMem(Size: Integer): Pointer;
begin
Inc(GetMemCount);
Result := OldMemMgr.GetMem(Size);
end;
function NewFreeMem(P: Pointer): Integer;
begin
Inc(FreeMemCount);
Result := OldMemMgr.FreeMem(P);
end;
function NewReallocMem(P: Pointer; Size: Integer): Pointer;
begin
Inc(ReallocMemCount);
Result := OldMemMgr.ReallocMem(P, Size);
end;
const
NewMemMgr: TMemoryManager = (
GetMem: NewGetMem;
FreeMem: NewFreeMem;
ReallocMem: NewReallocMem);
procedure SetNewMemMgr;
begin
GetMemoryManager(OldMemMgr);
SetMemoryManager(NewMemMgr);
end;
## GetMemoryManager, SetMemoryManager Example
-----------------------------------------------------------------------------
ReAllocMem 重新配置記憶體.
-----------------------------------------------------------------------------
Unit Systems
函數原型 procedure ReallocMem(var P: Pointer; Size: Integer);
-----------------------------------------------------------------------------
SetMemoryManager 設定目前Heap區的記憶體配置 的進入點.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure SetMemoryManager(const MemMgr:
TMemoryManager);
type
THeapStatus = record
TotalAddrSpace: Cardinal;s
TotalUncommitted: Cardinal;
TotalCommitted: Cardinal;
TotalAllocated: Cardinal;
TotalFree: Cardinal;
FreeSmall: Cardinal;
FreeBig: Cardinal;
Unused: Cardinal;
Overhead: Cardinal;
HeapErrorCode: Cardinal;
end;
type
PMemoryManager = ^TMemoryManager;
TMemoryManager = record
GetMem: function(Size: Integer): Pointer;
FreeMem: function(P: Pointer): Integer;
ReallocMem: function(P: Pointer; Size: Integer): Pointer;
end;
Example
var
GetMemCount: Integer;
FreeMemCount: Integer;
ReallocMemCount: Integer;
OldMemMgr: TMemoryManager;
function NewGetMem(Size: Integer): Pointer;
begin
Inc(GetMemCount);
Result := OldMemMgr.GetMem(Size);
end;
function NewFreeMem(P: Pointer): Integer;
begin
Inc(FreeMemCount);
Result := OldMemMgr.FreeMem(P);
end;
function NewReallocMem(P: Pointer; Size: Integer): Pointer;
begin
Inc(ReallocMemCount);
Result := OldMemMgr.ReallocMem(P, Size);
end;
const
NewMemMgr: TMemoryManager = (
GetMem: NewGetMem;
FreeMem: NewFreeMem;
ReallocMem: NewReallocMem);
procedure SetNewMemMgr;
begin
GetMemoryManager(OldMemMgr);
SetMemoryManager(NewMemMgr);
end;
##GetMemoryManager, SetMemoryManager Example
======================================
Miscellaneous routines 其他常式
======================================
Exclude 刪除一組元素中的一個元素.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Exclude(var S: set of T;I:T);
說明 刪除S中的I元素.
-----------------------------------------------------------------------------
FillChar 填入元素.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure FillChar(var X; Count: Integer; value);
說明 以value填入X中Count個.
範例 Example
var
S: array[0..79] of char;
begin
{ Set to all spaces }
FillChar(S, SizeOf(S), Ord(' '));
MessageDlg(S, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
Hi 傳回高位元數字.
-----------------------------------------------------------------------------
Unit System
函數原型 function Hi(X): Byte;
範例 var B: Byte;
begin
B := Hi($1234); { $12 }
end;
-----------------------------------------------------------------------------
Include 加入一個元素到一組元素.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Include(var S: set of T; I:T);
說明 加入I元素到S中.
-----------------------------------------------------------------------------
Lo 傳回高位元數字.
-----------------------------------------------------------------------------
Unit System
函數原型 function Lo(X): Byte;
範例 var B: Byte;
begin
B := Lo($1234); { $34 }
end;
-----------------------------------------------------------------------------
Move 從來源變數拷貝n個Bytes到目的變數.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Move(var Source, Dest; Count: Integer);
範例 var
A: array[1..4] of Char;
B: Integer;
begin
Move(A, B, SizeOf(B));
{ SizeOf = safety! }
end;
-----------------------------------------------------------------------------
ParamCount 直接由執行檔後加上傳入變數的個數.(arj.exe a dr.arj d:*.*)
-----------------------------------------------------------------------------
Unit System
函數原型 function ParamCount: Integer;
說明 如上例則傳回3
Example
var
I: Integer;
ListItem: string;
begin
for I := 0 to IBQuery1.ParamCount - 1 do
begin
ListItem := ListBox1.Items[I];
case IBQuery1.Params[I].DataType of
ftString:
IBQuery1.Params[I].AsString := ListItem;
ftSmallInt:
IBQuery1.Params[I].AsSmallInt := StrToIntDef(ListItem, 0);
ftInteger:
IBQuery1.Params[I].AsInteger := StrToIntDef(ListItem, 0);
ftWord:
IBQuery1.Params[I].AsWord := StrToIntDef(ListItem, 0);
ftBoolean:
begin
if ListItem = 'True' then
IBQuery1.Params[I].AsBoolean := True
else
IBQuery1.Params[I].AsBoolean := False;
end;
ftFloat:
IBQuery1.Params[I].AsFloat := StrToFloat(ListItem);
ftCurrency:
IBQuery1.Params[I].AsCurrency := StrToFloat(ListItem);
ftBCD:
IBQuery1.Params[I].AsBCD := StrToCurr(ListItem);
ftDate:
IBQuery1.Params[I].AsDate := StrToDate(ListItem);
ftTime:
IBQuery1.Params[I].AsTime := StrToTime(ListItem);
ftDateTime:
IBQuery1.Params[I].AsDateTime := StrToDateTime(ListItem);
end;
end;
end;
##ParamCount, DataType, StrToIntDef, AsXXX Example
-----------------------------------------------------------------------------
ParamStr
-----------------------------------------------------------------------------
Unit System
函數原型 function ParamStr(Index: Integer): string;
說明 ParamStr(0);傳回執行檔的名稱及完整目錄.
(C:/ZIP/ARJ.EXE)
範例
var
I: Word;
Y: Integer;
begin
Y := 10;
for I := 1 to ParamCount do
begin
Canvas.TextOut(5, Y, ParamStr(I));
Y := Y + Canvas.TextHeight(ParamStr(I)) + 5;
end;
end;
Example
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
for i := 0 to ParamCount -1 do
begin
if LowerCase(ParamStr(i)) = 'beep' then
Windows.Beep(10000,1000)
else
if (LowerCase(ParamStr(i)) = 'exit' then
Application.Terminate;
end;
end;
##ParamCount, ParamStr Example
-----------------------------------------------------------------------------
Random 亂數
-----------------------------------------------------------------------------
Unit System
函數原型 function Random [ ( Range: Integer) ];
說明 0<=X<Range
範例 var
I: Integer;
begin
Randomize;
for I := 1 to 50 do
begin
{ Write to window at random locations }
Canvas.TextOut(Random(Width), Random(Height),
'Boo!');
end;
end;
-----------------------------------------------------------------------------
Randomize 亂數種子.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Randomize;
Example
var
I: Integer;
begin
Randomize;
for I := 1 to 50 do begin
{ Write to window at random locations }
Canvas.TextOut(Random(Width), Random(Height), 'Boo!');
end;
end;
##Randomize, Random Example
-----------------------------------------------------------------------------
SizeOf 傳回X變數的位元數.
-----------------------------------------------------------------------------
Unit System
函數原型 function SizeOf(X): Integer;
範例 type
CustRec = record
Name: string[30];
Phone: string[14];
end;
var
P: ^CustRec;
begin
GetMem(P, SizeOf(CustRec));
Canvas.TextOut(10, 10, 'The size of the record is ' +
IntToStr(SizeOf(CustRec)));
FreeMem (P, SizeOf(CustRec));
Readln;
end;
-----------------------------------------------------------------------------
Swap 將一組變數的高低位元交換.
-----------------------------------------------------------------------------
Unit System
函數原型 function Swap(X);
範例 var
X: Word;
begin
X := Swap($1234); { $3412 }
end;
-----------------------------------------------------------------------------
UpCase 將一字元轉爲大寫字母.
-----------------------------------------------------------------------------
Unit System
函數原型 function UpCase(Ch: Char): Char;
範例 uses Dialogs;
var
s : string;
i : Integer;
begin
{ Get string from TEdit control }
s := Edit1.Text;
for i := 1 to Length(s) do
s[i] := UpCase(s[i]);
MessageDlg('Here it is in all uppercase: ' + s, mtInformation,
[mbOk], 0);
end;
Example
var
s : string;
i : Integer;
begin
{ Get string from TEdit control }
s := Edit1.Text;
for i := 1 to Length(s) do
if i mod 2 = 0 then s[i] := UpCase(s[i]);
Edit1.Text := s;
end;
===========================================
Ordinal routines 序列常式
==========================================
Dec 使變數遞減.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Dec(var X[ ; N: Longint]);
說明 Dec(X) ==> X:=X-1;
Dec(X,N) ==> X:=X-N;
範例 var
IntVar: Integer;
LongintVar: Longint;
begin
Intvar := 10;
LongintVar := 10;
Dec(IntVar); { IntVar := IntVar - 1 }
Dec(LongintVar, 5); { LongintVar := LongintVar - 5 }
end;
-----------------------------------------------------------------------------
Inc 使變數遞增.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Inc(var X [ ; N: Longint ] );
說明 Inc(X) ==> X:=X-1;
Inc(X,N) ==> X:=X-N;
範例 var
IntVar: Integer;
LongintVar: Longint;
begin
Inc(IntVar); { IntVar := IntVar + 1 }
Inc(LongintVar, 5); { LongintVar := LongintVar + 5 }
end;
-----------------------------------------------------------------------------
Odd 檢查是否爲奇數.
-----------------------------------------------------------------------------
Unit System
函數原型 function Odd(X: Longint): Boolean;
Example
begin
if Odd(5) then
Canvas.TextOut(10, 10, '5 is odd.')
else
Canvas.TextOut(10, 10, 'Something is odd!');
end;
=======================================
Pointer and address routines 位址常式
=======================================
Addr 傳回一個物件的位址.
-----------------------------------------------------------------------------
Unit System
函數原型 function Addr(X): Pointer;
Example
var
I : Integer;
NodeNumbers: array [0 .. 100] of Integer;
begin
with TreeView1 do
begin
for I := 0 to Items.Count - 1 do
begin
NodeNumbers[I] := CalculateValue(Items[I]);
Items[I].Data := Addr(NodeNumber[I]);
end;
end;
end;
-----------------------------------------------------------------------------
Assigned 測試指標變數是否爲nil.
-----------------------------------------------------------------------------
Unit System
函數原型 function Assigned(var P): Boolean;
說明 當@P=nil ==> 傳回FALSE
範例 var P: Pointer;
begin
P := nil;
if Assigned (P) then
Writeln ('You won't see this');
GetMem(P, 1024); {P valid}
FreeMem(P, 1024); {P no longer valid and still not nil}
if Assigned (P) then
Writeln ('You'll see this');
end
===================================
String-formatting routines 字串格式化
==================================
FmtStr 格式化.
-----------------------------------------------------------------------------
FmtStr(var StrResult: string;const Format: string;const Args: array of string );
-----------------------------------------------------------------------------
Format
Format(const Format: string;const Args: array of string ): string;
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 procedure FmtStr(var Result: string; const Format: string;
const Args: array of const);
function Format(const Format: string; const Args: array of
const): string;
說明 %d : 整數
%e : 科學式
%f : 定點實數
%g : 實數
%n : 實數(-d,ddd,ddd.dd ...)
%m: 金錢格式
%p : point
%s : 字串
%x : Hex
範例 var
i: Integer;
j: Double;
s: String;
t: String;
begin
t:=Format('%d %8.2f %s',[i,j,s]);
ListBox1.Item.Add(t);
end;
BubbleSeries1.PercentFormat := '##0.0# %';
Example
procedure TForm1.Table1AfterDelete(DataSet: TDataSet);
begin
StatusBar1.SimpleText := Format('There are now %d records in the table', [DataSet.RecordCount]);
end;
S:= Format( '1-? ??????? ??????? - %d, 2-? - %d, 3-? - %d', [10,20,30] );
Format( '%*.*f', [ 9, 2, 12345.6789 ] );
Format( '%9.2f', [ 12345.6789 ] );
Format( '%3d, %d, %0:d, %2:-4d, %d', [ 1, 2, 3, 4 ] );
' 1,2,1,3 ,4'
## AfterDelete, Format Example
=======================================
String-handling routines (Pascal-style) 字串函式
=======================================
AnsiCompareStr 比較兩個字串的大小.依安裝的 language driver.
-----------------------------------------------------------------------------
AnsiCompareText ( AnsiCompareText 此項不分大小寫 ).
-----------------------------------------------------------------------------
Unit SysUtils
var
S1,S2: string;
I: Integer;
begin
S1:= 'A????';
S2:= '?????';
I:= CompareStr(S1, S2); { I = 0, ?.?. S1 = S2 }
if I=0 then
MessageDlg(S1, '=', S2, mtWarning, [mbOK], 0);
end;
函數原型 function AnsiCompareStr(const S1, S2: string):Integer;
函數原型 function AnsiCompareText(const S1, S2: string):Integer;
-----------------------------------------------------------------------------
AnsiLowerCase 將字串全部轉爲小寫字母.依安裝的 language driver.
-----------------------------------------------------------------------------
AnsiUpperCase 將字串全部轉爲大寫字母.依安裝的 language drive
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function AnsiLowerCase(const S: string): string;
函數原型 function AnsiUpperCase(const S: string): string;
-----------------------------------------------------------------------------
CompareStr 比較兩個字串的大小.
-----------------------------------------------------------------------------
CompareText ( CompareText 此項不分大小寫 ).
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function CompareStr(const S1, S2: string): Integer;
函數原型 function CompareText(const S1, S2: string): Integer;
範例 var
String1, String2 : string;
I : integer;
begin
String1 := 'STEVE';
String2 := 'STEVe';
I := CompareStr(String1, String2); { I < 0 }
if I < 0 then
MessageDlg('String1 < String2', mtWarning, [mbOK], 0);
end;
var
String1, String2 : string;
I : integer;
begin
String1 := 'ABC';
String2 := 'aaa';
I := CompareStr(String1, String2); { I < 0 }
if I < 0 then
MessageDlg(' String1 < String2', mtWarning, [mbOK], 0);
end;
Examlpe
var ColumnToSort: Integer;
The OnColumnClick event handler sets the global variable to indicate the column to sort and calls AlphaSort:
procedure TForm1.ListView1ColumnClick(Sender: TObject; Column: TListColumn);
begin
ColumnToSort := Column.Index;
(Sender as TCustomListView).AlphaSort;
end;
The OnCompare event handler causes the list view to sort on the selected column:
procedure TForm1.ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
var
ix: Integer;
begin
if ColumnToSort = 0 then
Compare := CompareText(Item1.Caption,Item2.Caption)
else begin
ix := ColumnToSort - 1;
Compare := CompareText(Item1.SubItems[ix],Item2.SubItems[ix]);
end;
end;
## OnColumnClick, AlphaSort, OnCompare, CompareText example
-----------------------------------------------------------------------------
Concat 將字串相加.
-----------------------------------------------------------------------------
Unit System
函數原型 function Concat(s1 [, s2,..., sn]: string): string;
說明 與 S := S1 + S2 + S3 ...; 相同.
範例 var
S: string;
begin
S := Concat('ABC', 'DEF'); { 'ABCDE' }
end;
var
S: string;
begin
S:= '? '+ '???? '+ '???????? ??????';
S:= Concat('? ', '???? ', '???????? ??????');
// ? ????? ??????? S := '? ???? ???????? ??????'
end;
-----------------------------------------------------------------------------
Copy 從母字串拷貝至另一個字串.
-----------------------------------------------------------------------------
Unit System
函數原型 function Copy(S: string; Index, Count: Integer): string;
說明 S : 字串.
Indexd : 從第幾位開始拷貝.
Count : 總共要拷貝幾位.
範例 var S: string;
begin
S := 'ABCDEF';
S := Copy(S, 2, 3); { 'BCD' }
end;
----------------
var
S: string;
begin
S:= '??????';
S:= Copy( S, 3, 4); // S := '????'
end;
---------------
Example
procedure TForm1.ComboBox1KeyPress(Sender: TObject; var Key: Char);
var
Found: boolean;
i,SelSt: Integer;
TmpStr: string;
begin
{ first, process the keystroke to obtain the current string }
{ This code requires all items in list to be uppercase}
if Key in ['a'..'z'] then Dec(Key,32); {Force Uppercase only!}
with (Sender as TComboBox) do
begin
SelSt := SelStart;
if (Key = Chr(vk_Back)) and (SelLength <> 0) then
TmpStr := Copy(Text,1,SelStart)+Copy(Text,SelLength+SelStart+1,255)
else if Key = Chr(vk_Back) then {SelLength = 0}
TmpStr := Copy(Text,1,SelStart-1)+Copy(Text,SelStart+1,255)
else {Key in ['A'..'Z', etc]}
TmpStr := Copy(Text,1,SelStart)+Key+Copy(Text,SelLength+SelStart+1,255);
if TmpStr = ' then Exit;
{ update SelSt to the current insertion point }
if (Key = Chr(vk_Back)) and (SelSt > 0) then Dec(SelSt)
else if Key <> Chr(vk_Back) then Inc(SelSt);
Key := #0; { indicate that key was handled }
if SelSt = 0 then
begin
Text:= ';
Exit;
end;
{Now that TmpStr is the currently typed string, see if we can locate a match }
Found := False;
for i := 1 to Items.Count do
if Copy(Items[i-1],1,Length(TmpStr)) = TmpStr then
begin
Text := Items[i-1]; { update to the match that was found }
ItemIndex := i-1;
Found := True;
Break;
end;
if Found then { select the untyped end of the string }
begin
SelStart := SelSt;
SelLength := Length(Text)-SelSt;
end
else Beep;
end;
end;
-----------------------
procedure TComponentEditor.Copy;
var
AFormat : Word;
AData,APalette : THandle;
begin
with Component as TImage do
begin
Picture.SaveToClipBoardFormat(AFormat,AData,APalette);
ClipBoard.SetAsHandle(AFormat,AData);
end;
end;
## Copy, Chr, SelStart, SelLength example
-----------------------------------------------------------------------------
Delete 刪除字串中的數個字元.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Delete(var S: string; Index, Count:Integer);
說明 S : 字串.
Indexd : 從第幾位開始刪.
Count : 總共要刪幾位.
範例 var
s: string;
begin
s := 'Honest Abe Lincoln';
Delete(s,8,4);
Canvas.TextOut(10, 10, s); { 'Honest Lincoln' }
end;
var
S: string;
begin
S:= '???????, ??????, ??????????!';
Delete(S, 8, 1); // S := '??????? ??????, ??????????!'
MessageDlg(S, mtWarning, [mbOK],0);
end;
-----------------------------------------------------------------------------
NewStr 在 heap 中配置一個新的字串空間給PString 指標.
-----------------------------------------------------------------------------
DisposeStr 在 heap 中釋放一個字串空間 PString指標.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function NewStr(const S: string): PString;
函數原型 procedure DisposeStr(P: PString);
說明 S : 字串.
Pstring : 新的字串指標.
範例 var
P: PString;
S: string;
begin
S := 'Ask me about Blaise';
P := NewStr(S);
DisposeStr(P):
end;
-----------------------------------------------------------------------------
Insert 將一個子字串插入另一個字串中.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Insert(Source: string; var S: string; Index: Integer);
說明 Source : 子字串.
S : 被插入的母字串.
Indexd : 從第幾位開始插入.
範例 var
S: string;
begin
S := 'Honest Lincoln';
Insert('Abe ', S, 8); { 'Honest Abe Lincoln' }
end;
var
S: string;
begin
S:= '??????? ?????? ??????????.';
Insert( '!', S, 8); { S := '???????! ?????? ??????????.'}
MessageDlg( S, mtWarning, [mbOK],0);
end;
-----------------------------------------------------------------------------
IntToHex 將 Int 轉爲 Hex.
-----------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
Label1.Caption := ';
for i := 1 to Length(Edit1.Text) do
begin
try
Label1.Caption := Label1.Caption + IntToHex(Edit1.Text[i],4) + ' ';
except
Beep;
end;
end;
end;
Exam:
Edit2.text:=(strtoint(Edit1.text),6);
-----------------------------------------------------------------------------
IntToStr 將 Int 轉爲 Str.
-----------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
begin
try
Label1.Caption := IntToStr(StrToInt(Edit1.Text) * StrToInt(Edit2.Text));
except
ShowMessage('You must specify integer values. Please try again.');
end;
end;
-----------------------------------------------------------------------------
StrToInt 將 Str 轉爲 Int.
-----------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
J: Integer;
begin
I := StrToInt(Edit1.Text);
J := StrToInt(Edit2.Text);
ShowMessage(IntToStr(I + J));
end;
-----------------------------------------------------------------------------
StrToIntDef 將 Str 轉爲 Int.當轉換有誤時,則傳回 Default 的值.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function IntToHex(Value: Integer; Digits: Integer): string;
函數原型 function IntToStr(Value: Integer): string;
函數原型 function StrToInt(const S: string): Integer;
函數原型 function StrToIntDef(const S: string; Default: Integer): Integer;
說明 Value : 欲轉換的整數.
Digits : 欲轉換爲幾位數的 Hex.
範例 procedure TForm1.Button1Click(Sender: TObject);
begin
Edit2.Text := IntToHex(StrToInt(Edit1.Text), 6);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Value: Integer;
begin
Value := 1234;
Edit1.Text := IntToStr(Value);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
S: string;
I: Integer;
begin
S := '22467';
I := StrToInt(S);
Inc(I);
Edit1.Text := IntToStr(I);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
NumberString: string;
Number: Integer;
begin
NumberString := Edit1.Text;
Number := StrToIntDef(NumberString, 1000);
Edit2.Text := IntToStr(Number);
end;
Example
var
I: Integer;
ListItem: string;
begin
for I := 0 to Query1.ParamCount - 1 do
begin
ListItem := ListBox1.Items[I];
case Query1.Params[I].DataType of
ftString:
Query1.Params[I].AsString := ListItem;
ftSmallInt:
Query1.Params[I].AsSmallInt := StrToIntDef(ListItem, 0);
ftInteger:
Query1.Params[I].AsInteger := StrToIntDef(ListItem, 0);
ftWord:
Query1.Params[I].AsWord := StrToIntDef(ListItem, 0);
ftBoolean:
begin
if ListItem = 'True' then
Query1.Params[I].AsBoolean := True
else
Query1.Params[I].AsBoolean := False;
end;
ftFloat:
Query1.Params[I].AsFloat := StrToFloat(ListItem);
ftCurrency:
Query1.Params[I].AsCurrency := StrToFloat(ListItem);
ftBCD:
Query1.Params[I].AsBCD := StrToCurr(ListItem);
ftDate:
Query1.Params[I].AsDate := StrToDate(ListItem);
ftTime:
Query1.Params[I].AsTime := StrToTime(ListItem);
ftDateTime:
Query1.Params[I].AsDateTime := StrToDateTime(ListItem);
end;
end;
end;
--------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
Number: Integer;
begin
Number := StrToIntDef(Edit1.Text, 1000);
Edit2.Text := IntToStr(Number);
end;
-------------------
## ParamCount, DataType, StrToIntDef, AsXXX Example
-----------------------------------------------------------------------------
Str 將數值轉換爲格式化的字串.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Str(X [: Width [: Decimals ]]; var S);
說明 X : 欲轉換的整數 or 實數.
Width : 格式化長度.(Integer)
Decimals : 小數點位數.(Integer)
範例 function MakeItAString(I: Longint): string;
{ Convert any integer type to a string }
var
S: string[11];
begin
Str(I, S);
MakeItAString:= S;
end;
begin
Canvas.TextOut(10, 10, MakeItAString(-5322));
end;
-----------------------------------------------------------------------------
Val 將字串轉爲數字.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Val(S; var V; var Code: Integer);
說明 S : 欲轉換的字串.
V : 轉換後的整數 or 實數.
Code : Code = 0 表示轉換成功.
範例 uses Dialogs;
var
I, Code: Integer;
begin
{ Get text from TEdit control }
Val(Edit1.Text, I, Code);
{ Error during conversion to integer? }
if code <> 0 then
MessageDlg('Error at position: ' + IntToStr(Code),
mtWarning, [mbOk], 0);
else
Canvas.TextOut(10, 10, 'Value = ' + IntToStr(I));
Readln;
end;
-----------------------------------------------------------------------------
Length 字串長度.
-----------------------------------------------------------------------------
Unit System
函數原型 function Length(S: string): Integer;
說明 S : 欲轉換的字串.
範例 var
S: string;
begin
S := 'The Black Knight';
Canvas.TextOut(10, 10, 'String Length = ' +
IntToStr(Length(S)));
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
Label1.Caption := ';
for i := 1 to Length(Edit1.Text) do
begin
try
Label1.Caption := Label1.Caption + IntToHex(Edit1.Text[i],4) + ' ';
except
Beep;
end;
end;
end;
範例
procedure TForm1.Button1Click(Sender: TObject);
var
S: string;
begin
S := memo1.text;
Label1.caption :=' ' + IntToStr(Length(S));
end;
var
S: string;
I: Integer;
begin
S:= '? ???? ???????? ??????';
I:= Length(S); // I:= 22
MessageDlg( '????? ??????='+ IntToStr(I), mtWarning, [mbOK], 0);
end;
## Length, IntToHex Example
-----------------------------------------------------------------------------
Pos 尋找子字串在母字串中的位置.
-----------------------------------------------------------------------------
Unit System
函數原型 function Pos(Substr: string; S: string): Integer;
說明 Substr : 子字串.
S : 母字串.
範例
procedure TForm1.Button1Click(Sender: TObject);
var S: string;
begin
S := ' 1234.5 ';
{ Convert spaces to zeroes }
while Pos(' ', S) > 0 do
S[Pos(' ', S)] := '0';
Label1.Caption := S;
Label1.Font.Size := 16;
end;
var
S: string;
I: Integer;
begin
S:= '? ???? ???????? ??????';
I:= Pos( '???', S); // I:= 3
end;
//DEMO 001234.50 //空白字串補零
-----------------------------------------------------------------------------
LowerCase 將字串全部轉爲小寫字母.
-----------------------------------------------------------------------------
Unit System
函數原型 function LowerCase(const S: string): string;
範例 procedure TForm1.Button1Click(Sender: TObject);
begin
Edit2.Text := LowerCase(Edit1.Text);
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := LowerCase(Edit1.Text);
end;
var
S: string;
begin
S:= LowerCase( '????????.TXT') ; // S := '????????.txt'
end;
-----------------------------------------------------------------------------
UpperCase 將字串全部轉爲大寫字母.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function UpperCase(const S: string): string;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
for I := 0 to ListBox1.Items.Count -1 do
ListBox1.Items[I] := UpperCase(ListBox1.Items[I]);
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
for I := 0 to ListBox1.Items.Count -1 do
ListBox1.Items[I] := UpperCase(ListBox1.Items[I]);
end;
-----------------------------------------------------------------------------
Trim 將字串前後的空白及控制字元清掉.
Trim ( const S: string ): string;
SysUtils
var
S: string;
L: Integer;
begin
S:= #13' ???! '#13;
L:= length( S); // L := 10
S:= Trim( S); // S := '???!'
L:= L-length( S); // L := 5
MessageDlg( '??????? ???????? - '+ IntToStr(L), mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
TrimLeft 將字串左邊的空白及控制字元清掉.
SysUtils
var
S: string;
L: Integer;
begin
S:= #13' ???! '#13;
L:= length( S); // L := 10
S:= TrimLeft( S); // S := '???! '#13
L:= L-length( S); // L := 3
MessageDlg( '??????? ???????? - '+IntToStr(L), mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
TrimRight 將字串右邊的空白及控制字元清掉.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function Trim(const S: string): string;
函數原型 function TrimLeft(const S: string): string;
函數原型 function TrimRight(const S: string): string;
var
S: string;
L: Integer;
begin
S:= #13' ???! '#13;
L:= length( S); // L := 10
S:= TrimRight( S); // S := #13' ???!'
L:= L-length( S); // L := 2
MessageDlg( '??????? ???????? - '+IntToStr(L), mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
AdjustLineBreaks 將字串的換行符號全部改爲#13#10
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function AdjustLineBreaks(const S: string): string;
=======================================
String-handling routines (null-terminated)字串函式
=======================================
StrAlloc 配置字串空間.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrAlloc(Size: Cardinal): PChar;
說明 Size=字串最大空間+1
-----------------------------------------------------------------------------
StrBufSize 傳回由 StrAlloc 配置空間的大小
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrBufSize(Str: PChar): Cardinal;
-----------------------------------------------------------------------------
StrCat 字串相加.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrCat(Dest, Source: PChar): PChar;
範例 uses SysUtils;
const
Obj: PChar = 'Object';
Pascal: PChar = 'Pascal';
var
S: array[0..15] of Char;
begin
StrCopy(S, Obj);
StrCat(S, ' ');
StrCat(S, Pascal);
Canvas.TextOut(10, 10, StrPas(S));
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
var
Buffer: PChar;
begin
GetMem(Buffer,Length(Label1.Caption) + Length(Edit1.Text) + 1);
StrCopy(Buffer, PChar(Label1.Caption));
StrCat(Buffer, PChar(Edit1.Text));
Label1.Caption := Buffer;
Edit1.Clear;
FreeMem(Buffer);
end;
const
P0: PChar = '??????-';
P1: PChar = '??????????';
P2: PChar = '????????';
var
S1, S2: array[0..20] of Char;
begin
StrCopy(S1, P0);
StrCopy(S2, P0);
StrCat(S1, P1); { S1 := '??????-??????????' }
StrCat(S2, P2); { S2 := '??????-????????' }
MessageDlg( S1+ #13+ S2, mtInformation, [mbOk], 0);
end;
##StrCopy, StrCat Example
-----------------------------------------------------------------------------
StrComp 比較兩字串大小.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrComp(Str1, Str2 : PChar): Integer;
範例 uses SysUtils;
const
S1: PChar = 'Wacky';
S2: PChar = 'Code';
var
C: Integer;
Result: string;
begin
C := StrComp(S1, S2);
if C < 0 then Result := ' is less than ' else
if C > 0 then Result := ' is greater than ' else
Result := ' is equal to ';
Canvas.TextOut(10, 10, StrPas(S1) + Result +
StrPas(S2));
end;
Example
uses SysUtils;
procedure TForm1.Button1Click(Sender: TObject);
var
Msg: string;
CompResult: Integer;
begin
Msg := Edit1.Text;
CompResult := StrComp(PChar(Edit1.Text), PChar(Edit2.Text));
if CompResult < 0 then
Msg := Msg + ' is less than '
else if CompResult > 0 then
Msg := Msg + ' is greater than '
else
Msg := Msg + ' is equal to '
Msg := Msg + Edit2.Text;
ShowMessage(Msg);
end;
var
S1,S2: PChar;
I: Integer;
Res: string;
begin
S1:= 'Company';
S2:= 'COMPANY';
I:= StrComp(S1, S2);
if I>0 then Res:= '>' else
if I<0 then Res:= '<' else Res:= '=';
MessageDlg(S1+ Res+ S2, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
StrCopy 拷貝字串.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrCopy(Dest, Source: PChar): PChar;
範例 uses SysUtils;
var
S: array[0..12] of Char;
begin
StrCopy(S, 'ObjectPascal');
Canvas.TextOut(10, 10, StrPas(S));
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
var
Buffer: PChar;
begin
GetMem(Buffer,Length(Label1.Caption) + Length(Edit1.Text) + 1);
StrCopy(Buffer, PChar(Label1.Caption));
StrCat(Buffer, PChar(Edit1.Text));
Label1.Caption := Buffer;
Edit1.Clear;
FreeMem(Buffer);
end;
## StrCopy, StrCat Example
-----------------------------------------------------------------------------
StrDispose 釋放StrAlloc or StrNew所配置的空間.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 procedure StrDispose(Str: PChar);
範例 uses SysUtils;
const
S: PChar = 'Nevermore';
var
P: PChar;
begin
P := StrNew(S);
Canvas.TextOut(10, 10, StrPas(P));
StrDispose(P);
end;
-----------------------------------------------------------------------------
StrECopy 拷貝字串並傳回字串結束位址.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrECopy(Dest, Source: PChar): PChar;
範例 uses SysUtils;
const
Turbo: PChar = 'Object';
Pascal: PChar = 'Pascal';
var
S: array[0..15] of Char;
begin
StrECopy(StrECopy(StrECopy(S, Turbo), ' '), Pascal);
Canvas.TextOut(10, 10, StrPas(S));
end;
Example
uses SysUtils;
const
Turbo: PChar = 'Object';
Pascal: PChar = 'Pascal';
var
S: array[0..15] of Char;
begin
StrECopy(StrECopy(StrECopy(S, Turbo), ' '), Pascal);
Canvas.TextOut(10, 10, string(S));
end;
-----------------------------------------------------------------------------
StrEnd 傳回字串結束位址.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrEnd(Str: PChar): PChar;
範例 uses SysUtils;
const
S: PChar = 'Yankee Doodle';
begin
Canvas.TextOut(5, 10, 'The string length of "' + StrPas(S)
+ '" is ' +IntToStr(StrEnd(S) - S));
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
var
TextBuffer: PChar;
Ptr: PChar;
begin
GetMem(TextBuffer, Length(Edit1.Text)+1);
StrCopy(TextBuffer, PChar(Edit1.Text));
Ptr := StrEnd(TextBuffer);
Label1.Caption := ';
while Ptr >= TextBuffer do
begin
Ptr := Ptr ? 1;
Label1.Caption := Label1.Caption + Ptr^;
end;
FreeMem(TextBuffer);
end;
var
Str: PChar;
L: Word;
begin
...
L:= StrEnd(Str) - Str;
...
end;
-----------------------------------------------------------------------------
StrIComp 比較兩字串大小.(不分大小寫)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrIComp(Str1, Str2:PChar): Integer;
範例 uses SysUtils;
const
S1: PChar = 'Wacky';
S2: PChar = 'Code';
var
C: Integer;
Result: string;
begin
C := StrIComp(S1, S2);
if C < 0 then Result := ' is less than ' else
if C > 0 then Result := ' is greater than ' else
Result := ' is equal to ';
Canvas.TextOut(10, 10, StrPas(S1) + Result +
StrPas(S2));
end;
xample
uses SysUtils;
procedure TForm1.Button1Click(Sender: TObject);
var
Msg: string;
CompResult: Integer;
begin
Msg := Edit1.Text;
CompResult := StrIComp(PChar(Edit1.Text), PChar(Edit2.Text));
if CompResult < 0 then
Msg := Msg + ' is less than '
else if CompResult > 0 then
Msg := Msg + ' is greater than '
else
Msg := Msg + ' is equal to '
Msg := Msg + Edit2.Text;
ShowMessage(Msg);
end;
var
S1,S2: PChar;
I: Integer;
Res: string;
begin
S1:= 'ABC';
S2:= 'abc';
I:= StrIComp(S1, S2); { I := 0, ?.?. S1 = S2 }
if I>0 then Res:= '>' else
if I<0 then Res:= '<' else Res:= '=';
MessageDlg( S1 + Res + S2, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
StrLCat 字串相加.(指定長)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrLCat(Dest, Source: PChar; MaxLen: Cardinal):
PChar;
範例 uses SysUtils;
var
S: array[0..13] of Char;
begin
StrLCopy(S, 'Object', SizeOf(S) - 1);
StrLCat(S, ' ', SizeOf(S) - 1);
StrLCat(S, 'Pascal', SizeOf(S) - 1);
Canvas.TextOut(10, 10, StrPas(S));
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
var
FirstHalf: PChar;
SecondHalf: PChar;
HalfLen: Integer;
begin
HalfLen := StrLen(PChar(Edit1.Text)) div 2;
GetMem(FirstHalf,HalfLen+2);
GetMem(SecondHalf,HalfLen+2);
FirstHalf^ := Chr(0);
SecondHalf^ := Chr(0);
StrLCat(FirstHalf, PChar(Edit1.Text), HalfLen);
StrCat(SecondHalf, PChar(Edit1.Text) + HalfLen);
Application.MessageBox(FirstHalf, 'First Half', MB_OK);
Application.MessageBox(SecondHalf, 'Second Half', MB_OK);
FreeMem(FirstHalf);
FreeMem(SecondHalf);
end;
const
S1: PChar = '???';
S2: PChar = '?????????';
var
S: array[0..13] of Char;
begin
StrLCopy(S, S1, StrLen(S1));
StrLCat(S, S2, 6); { S :='??????' }
MessageDlg(S, mtInformation, [mbOk], 0);
end;
## StrLen, StrLCat Example
-----------------------------------------------------------------------------
StrLComp 比較兩字串大小.(指定長)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrLComp(Str1, Str2: PChar; MaxLen: Cardinal):
Integer;
範例 uses SysUtils;
const
S1: PChar = 'Enterprise'
S2: PChar = 'Enter'
var
Result: string;
begin
if StrLComp(S1, S2, 5) = 0 then
Result := 'equal'
else
Result := 'different';
Canvas.TextOut(10, 10, 'The first five characters are ' +
Result);
end;
example
uses SysUtils;
const
S1: PChar = 'Enterprise'
S2: PChar = 'Enter'
var
ComStr: string;
begin
if StrLComp(S1, S2, 5) = 0 then
ComStr := 'equal'
else
ComStr := 'different';
Canvas.TextOut(10, 10, 'The first five characters are ' + ComStr);
end;
const
S1: PChar = '?????????';
S2: PChar = '????????';
var
I: Integer;
S: string;
begin
I:= 5;
if StrLComp( S1, S2, I) = 0 then S:= '?????' else S:= '????????';
MessageDlg( '?????? '+ IntToStr(I)+ ' ???????? ????? '+ S, mtInformation,[mbOk], 0);
end;
-----------------------------------------------------------------------------
StrLCopy 拷貝字串.(指定長)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrLCopy(Dest, Source: PChar; MaxLen:
Cardinal): PChar;
範例 uses SysUtils;
var
S: array[0..11] of Char;
begin
StrLCopy(S, 'ObjectPascal', SizeOf(S) - 1);
Canvas.TextOut(10, 10, StrPas(S));
end;
Example
uses SysUtils;
const MAX_BUFFER = 10;
procedure TForm1.Button1Click(Sender TObject);
var
Buffer: array [0..MAX_BUFFER] of char;
begin
StrLCopy(Buffer, PChar(Edit1.Text), MAX_BUFFER);
Application.MessageBox(Buffer, 'StrLCopy Example', MB_OK);
end;
var
S: PChar;
begin
StrLCopy( S, '?????????', 5); { S := '?????' }
...
end;
-----------------------------------------------------------------------------
StrLen 傳回字串長度.(不含終止位元)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrLen(Str: PChar): Cardinal;
範例 uses SysUtils;
const
S: PChar = 'E Pluribus Unum';
begin
Canvas.TextOut(5, 10, 'The string length of "' + StrPas(S)
+ '" is ' + IntToStr(StrLen(S)));
end;
Example
procedure TForm1.Button1Click(Sender: TObject);
var
FirstHalf: PChar;
SecondHalf: PChar;
HalfLen: Integer;
begin
HalfLen := StrLen(PChar(Edit1.Text)) div 2;
GetMem(FirstHalf,HalfLen+2);
GetMem(SecondHalf,HalfLen+2);
FirstHalf^ := Chr(0);
SecondHalf^ := Chr(0);
StrLCat(FirstHalf, PChar(Edit1.Text), HalfLen);
StrCat(SecondHalf, PChar(Edit1.Text) + HalfLen);
Application.MessageBox(FirstHalf, 'First Half', MB_OK);
Application.MessageBox(SecondHalf, 'Second Half', MB_OK);
FreeMem(FirstHalf);
FreeMem(SecondHalf);
end;
const
S: PChar = '????? ????? ????? ????????!';
begin
MessageDlg( S+ #13#10 + '?????????? ???????? = ' + IntToStr( StrLen( S)), mtInformation, [mbOk], 0);
end;
## StrLen, StrLCat Example
-----------------------------------------------------------------------------
StrLIComp 比較兩字串大小.(指定長,不分大小寫)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrLIComp(Str1, Str2: PChar; MaxLen:
Cardinals): Integer;
範例 uses SysUtils;
const
S1: PChar = 'Enterprise'
S2: PChar = 'Enter'
var
Result: string;
begin
if StrLIComp(S1, S2, 5) = 0 then
Result := 'equal'
else
Result := 'different';
Canvas.TextOut(10, 10, 'The first five characters are ' +
Result);
end;
Examply
uses SysUtils;
const
S1: PChar = 'Enterprise'
S2: PChar = 'Enter'
var
ComStr: string;
begin
if StrLIComp(S1, S2, 5) = 0 then
ComStr := 'equal'
else
ComStr := 'different';
Canvas.TextOut(10, 10, 'The first five characters are ' + ComStr);
end;
const
S1: PChar = '?????????';
S2: PChar = '????????';
var
S: string;
begin
if StrLIComp( S1, S2, 5) = 0 then S:= '?????' else S:= '????????';
MessageDlg( S1 + #13 + S2 + #13 + '?????? ' + IntToStr( I) + ' ???????? ????? ' + S, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
StrLower 將字串全部轉爲小寫字母.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrLower(Str: PChar): PChar;
範例 uses SysUtils;
const
S: PChar = 'A fUnNy StRiNg'
begin
Canvas.TextOut(5, 10, StrPas(StrLower(S)) + ' ' +
StrPas(StrUpper(S)));
end;
-----------------------------------------------------------------------------
StrMove 從來源字串拷貝n個Bytes到目爬r串.(不含終止位元)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrMove(Dest, Source: PChar; Count:
Cardinal): PChar;
範例 uses SysUtils;
function AHeapaString(S: PChar): PChar;
{ Allocate string on heap }
var
L: Cardinal;
P: PChar;
begin
StrNew := nil;
if (S <> nil) and (S[0] <> #0) then
begin
L := StrLen(S) + 1;
GetMem(P, L);
StrNew := StrMove(P, S, L);
end;
end;
procedure DisposeDaString(S: PChar);
{ Dispose string on heap }
begin
if S <> nil then FreeMem(S, StrLen(S) + 1);
end;
var
S: PChar;
begin
AHeapaString(S);
DisposeDaString(S);
end;
var
S1, S2: PChar;
begin
S1:= 'ABcdEFgh';
StrMove( S2, S1, StrLen( S1) + 1 );
StrLower( S1); { S1:= 'abcdefgh' }
StrUpper( S2); { S2:= 'ABCDEFGH' }
MessageDlg( S1 + #13#10 + S2, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
StrNew 配置字串空間.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrNew(Str: PChar): PChar;
Example
uses Sysutils;
procedure TForm1.Button1Click(Sender: TObject);
var
Temp: PChar;
begin
// Allocate memory.
Temp := StrNew(PChar(Edit1.Text));
Application.MessageBox(Temp, 'StrNew, StrDispose Example', MB_OK);
// Deallocate memory.
StrDispose(Temp);
end;
const
S: PChar = '??????????? ??????';
var
SNew: PChar;
begin
SNew:= StrNew( S);
MessageDlg( 'S: ' + S + #13 + 'SNew: ' + SNew, mtInformation, [mbOk], 0);
StrDispose(SNew);
end;
## StrNew, StrDispose Example
-----------------------------------------------------------------------------
StrPas 將 null-terminated 字串轉爲Pascal-style 字串.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrPas(Str: PChar): string;
範例 uses SysUtils;
const
A: PChar = 'I love the smell of Object Pascal in the
morning.';
var
S: string[79];
begin
S := StrPas(A);
Canvas.TextOut(10, 10, S);
{ note that the following also works }
Canvas.TextOut(10, 10, A);
end;
-----------------------------------------------------------------------------
StrPCopy 拷貝 Pascal-style 字串到null-terminated 字串.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrPCopy(Dest: PChar; Source: string): PChar;
範例 uses SysUtils;
var
A: array[0..79] of Char;
S: String;
begin
S := 'Honk if you know Blaise.';
StrPCopy(A, S);
Canvas.TextOut(10, 10, StrPas(A));
end;
var
Source: string;
Dest: array[0..20] of Char;
begin
Source:= '???????? ??????';
StrPCopy( Dest, Source);
MessageDlg( Dest, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
StrPLCopy 拷貝 Pascal-style 字串到null-terminated 字串.(指定長)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrPLCopy(Dest: PChar; const Source: string;
MaxLen: Cardinal): PChar;
-----------------------------------------------------------------------------
StrPos 子字串在母字串中的位置.(第一個位置)
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrPos(Str1, Str2: PChar): PChar;
說明 Str1 母字串
Str2 子字串
Example
uses SysUtils;
procedure TForm1.Button1Click(Sender TObject);
var
Location: PChar;
begin
if StrPos(PChar(Edit1.Text), PChar(Edit2.Text)) <> nil
then
ShowMessage('Substring found')
else
ShowMessage('Substring not found');
end;
------------------
const
SubStr: PChar = 'www';
var
S, R: PChar;
begin
S:= 'http://www.atrussk.ru/delphi/';
R:= StrPos(S, SubStr);
if R<>nil then MessageDlg( R, mtInformation, [mbOk], 0) else
MessageDlg( '?? ????????? ?????? URL!', mtError, [mbOk], 0);
end;
-----------------------------------------------------------------------------
StrRScan 子字元在母字串中的位置的下一個位址.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrRScan(Str: PChar; Chr: Char): PChar;
範例 { Return pointer to name part of a full path name }
uses SysUtils;
function NamePart(FileName: PChar): PChar;
var
P: PChar;
begin
P := StrRScan(FileName, '/');
if P = nil then
begin
P := StrRScan(FileName, ':');
if P = nil then P := FileName;
end;
NamePart := P;
end;
var
S : string;
begin
S := StrPas(NamePart('C:/Test.fil'));
Canvas.TextOut(10, 10, S);
end;
const
S: PChar = 'MyFile.zzz';
var
R: PChar;
begin
R:= StrRScan( S, '.'); { R := '.zzz' }
MessageDlg( R, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
StrScan 子字元在母字串中的位置.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrScan(Str: PChar; Chr: Char): PChar;
範例 uses SysUtils;
function HasWildcards(FileName: PChar): Boolean;
{ Return true if file name has wildcards in it }
begin
HasWildcards := (StrScan(FileName, '*') <> nil) or
(StrScan(FileName, '?') <> nil);
end;
const
P: PChar = 'C:/Test.* ';
begin
if HasWildcards(P) then
Canvas.TextOut(20, 20, 'The string has wildcards')
else
Canvas.TextOut(20, 20, 'The string doesn't have
wildcards')
end;
const
S: PChar = 'http://www.atrussk.ru';
var
R: PChar;
begin
R:= StrScan( S, 'w'); { R := 'www.atrussk.ru' }
MessageDlg( R, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
StrUpper 將字串全部轉爲大寫字母.
-----------------------------------------------------------------------------
Unit SysUtils
函數原型 function StrUpper(Str: PChar): PChar;
範例 uses SysUtils;
const
S: PChar = 'A fUnNy StRiNg'
begin
Canvas.TextOut(5, 10, StrPas(StrLower(S)) + ' ' +
StrPas(StrUpper(S)));
end;
=========================================
Text-file routines Text-file常式
=========================================
Append 開起一個可供Append的檔案.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Append(var f: Text);
範例 var F: TextFile;
begin
if OpenDialog1.Execute then
{ Bring up open file dialog }
begin
AssignFile(F, OpenDialog1.FileName);
{ Open file selected in dialog }
Append(F); { Add more text onto end }
Writeln(F, 'appended text');
CloseFile(F); { Close file, save changes }
end;
end;
Example
var
f: TextFile;
begin
if OpenDialog1.Execute then
begin { open a text file }
AssignFile(f, OpenDialog1.FileName);
Append(f);
Writeln(f, 'I am appending some stuff to the end of the file.');
{ insert code here that would require a Flush before closing the file }
Flush(f); { ensures that the text was actually written to file }
CloseFile(f);
end;
end;
## Append, Flush Example
-----------------------------------------------------------------------------
Eoln 測試檔案是否結束.(For text file.)
-----------------------------------------------------------------------------
Unit System
函數原型 function Eoln [(var F: Text) ]: Boolean;
Flush 將Buffer中的資料存入磁碟.
(For text file)
Unit System
函數原型 procedure Flush(var F: Text);
範例 var
f: TextFile;
begin
if OpenDialog1.Execute then
begin { open a text file }
AssignFile(f, OpenDialog1.FileName);
Append(f);
Writeln(f, 'I am appending some stuff to the end of the
file.');
Flush(f);
{ ensures that the text was actually written to file }
{ insert code here that would require a Flush before
closing the file }
CloseFile(f);
end;
end;
Example
begin
{ Tells program to wait for keyboard input }
WriteLn(Eoln);
end;
-----------------------------------------------------------------------------
Read 讀檔.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Read(F , V1 [, V2,...,Vn ] );
procedure Read( [ var F: Text; ] V1 [, V2,...,Vn ] );
範例 uses Dialogs;
var
F1, F2: TextFile;
Ch: Char;
begin
if OpenDialog1.Execute then
begin
AssignFile(F1, OpenDialog1.Filename);
Reset(F1);
if SaveDialog1.Execute then
begin
AssignFile(F2, OpenDialog1.Filename);
Rewrite(F2);
While not Eof(F1) do
begin
Read(F1, Ch);
Write(F2, Ch);
end;
CloseFile(F2);
end;
CloseFile(F1);
end;
end.
-----------------------------------------------------------------------------
Readln 讀檔.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Readln([ var F: Text; ] V1 [, V2, ...,Vn ]);
範例 var
s : string;
begin
Write('Enter a line of text: ');
Readln(s);
Writeln('You typed: ',s);
Writeln('Hit <Enter> to exit');
Readln;
end;
-----------------------------------------------------------------------------
SeekEof 測試檔案是否結束.
-----------------------------------------------------------------------------
Unit System
函數原型 function SeekEof [ (var F: Text) ]: Boolean;
範例 var
f : System.TextFile;
i, j, Y : Integer;
begin
AssignFile(f,'TEST.TXT');
Rewrite(f);
{ Create a file with 8 numbers and some whitespace at the
ends of the lines }
Writeln(f,'1 2 3 4 ');
Writeln(f,'5 6 7 8 ');
Reset(f);
{ Read the numbers back. SeekEoln returns TRUE if there are
no more numbers on the current line; SeekEof returns
TRUE if there is no more text (other than whitespace) in
the file. }
Y := 5;
while not SeekEof(f) do
begin
if SeekEoln(f) then
Readln; { Go to next line }
Read(f,j);
Canvas.TextOut(5, Y, IntToStr(j));
Y := Y + Canvas.TextHeight(IntToStr(j)) + 5;
end;
end;
-----------------------------------------------------------------------------
SeekEoln 測試檔案中行是否結束.
-----------------------------------------------------------------------------
Unit System
函數原型 function SeekEoln [ (var F: Text) ]: Boolean;
Example
var
f : System.TextFile;
i, j, Y : Integer;
begin
AssignFile(f,'TEST.TXT');
Rewrite(f);
{ Create a file with 8 numbers and some
whitespace at the ends of the lines }
Writeln(f,'1 2 3 4 ');
Writeln(f,'5 6 7 8 ');
Reset(f);
{ Read the numbers back. SeekEoln returns TRUE if there are no more
numbers on the current line; SeekEof returns TRUE if there is no
more text (other than whitespace) in the file. }
Y := 5;
while not SeekEof(f) do
begin
if SeekEoln(f) then
Readln; { Go to next line }
Read(f,j);
Canvas.TextOut(5, Y, IntToStr(j));
Y := Y + Canvas.TextHeight(IntToStr(j)) + 5;
end;
end;
## SeekEoln, SeekEof Example
-----------------------------------------------------------------------------
SetTextBuf 指定 I/O buffer 給 text file.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure SetTextBuf(var F: Text; var Buf [ ; Size: Integer] );
範例 uses Dialogs;
var
F, FTwo: System.TextFile;
Ch: Char;
Buf: array[1..4095] of Char; { 4K buffer }
begin
if OpenDialog1.Execute then
begin
AssignFile(F, ParamStr(1));
{ Bigger buffer for faster reads }
SetTextBuf(F, Buf);
Reset(F);
{ Dump text file into another file }
AssignFile(FTwo, 'WOOF.DOG');
Rewrite(FTwo);
while not Eof(f) do
begin
Read(F, Ch);
Write(FTwoCh);
end;
System.CloseFile(F);
System.CloseFile(FTwo);
end;
end;
-----------------------------------------------------------------------------
Write 寫入檔案.
-----------------------------------------------------------------------------
Unit System
函數原型 Write(F, V1,...,Vn);
Write( [var F: Text; ] P1 [ , P2,..., Pn] );
procedure TForm1.Button3Click(Sender: TObject);
var
Stream: TBlobStream;
S: string;
begin
with Table1 do
begin
Edit;
Stream := CreateBlobStream(FieldByName('Notes'), bmReadWrite);
try
Stream.Seek(0, 2); {Seek 0 bytes from the stream's end point}
S := ' This line will be added to the end.';
Stream.Write(PChar(S), Length(S));
finally
Stream.Free;
end;
Post;
end;
end;
-----------------------------------------------------------------------------
Writeln 寫入檔案.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure Writeln([ var F: Text; ] P1 [, P2, ...,Pn ] );
範例 var
s : string;
begin
Write('Enter a line of text: ');
Readln(s);
Writeln('You typed: ',s);
Writeln('Hit <Enter> to exit');
Readln;
end;
=======================================
Transfer routines 轉換函式
=======================================
Chr 將 Byte 轉爲字元.
-----------------------------------------------------------------------------
Unit System
函數原型 function Chr(X: Byte): Char;
範例 begin
Canvas.TextOut(10, 10, Chr(65)); { The letter 'A'}
end;
Example
procedure TForm1.ComboBox1KeyPress(Sender: TObject; var Key: Char);
var
Found: boolean;
i,SelSt: Integer;
TmpStr: string;
begin
{ first, process the keystroke to obtain the current string }
{ This code requires all items in list to be uppercase}
if Key in ['a'..'z'] then Dec(Key,32); {Force Uppercase only!}
with (Sender as TComboBox) do
begin
SelSt := SelStart;
if (Key = Chr(vk_Back)) and (SelLength <> 0) then
TmpStr := Copy(Text,1,SelStart)+Copy(Text,SelLength+SelStart+1,255)
else if Key = Chr(vk_Back) then {SelLength = 0}
TmpStr := Copy(Text,1,SelStart-1)+Copy(Text,SelStart+1,255)
else {Key in ['A'..'Z', etc]}
TmpStr := Copy(Text,1,SelStart)+Key+Copy(Text,SelLength+SelStart+1,255);
if TmpStr = ' then Exit;
{ update SelSt to the current insertion point }
if (Key = Chr(vk_Back)) and (SelSt > 0) then Dec(SelSt)
else if Key <> Chr(vk_Back) then Inc(SelSt);
Key := #0; { indicate that key was handled }
if SelSt = 0 then
begin
Text:= ';
Exit;
end;
{Now that TmpStr is the currently typed string, see if we can locate a match }
Found := False;
for i := 1 to Items.Count do
if Copy(Items[i-1],1,Length(TmpStr)) = TmpStr then
begin
Text := Items[i-1]; { update to the match that was found }
ItemIndex := i-1;
Found := True;
Break;
end;
if Found then { select the untyped end of the string }
begin
SelStart := SelSt;
SelLength := Length(Text)-SelSt;
end
else Beep;
end;
end;
## Copy, Chr, SelStart, SelLength example
-----------------------------------------------------------------------------
High 傳回註腳的最大值.
-----------------------------------------------------------------------------
Unit System
函數原型 function High(X);
範例 [Ordinal type]
procedure TForm1.Button1Click(Sender: TObject);
var
Low_S:String;
High_S:string;
S:String;
begin
High_S:=' High='+IntToStr(High(Word));
Low_S:='Low='+IntToStr(Low(Word));
S:=Low_S+High_S;
Label1.Caption:=S;
end;
S:=Low=0 High=65535
[Array type]
procedure TForm1.Button1Click(Sender: TObject);
var
P : Array[5..21] of Double;
Low_S:String;
High_S:string;
S:String;
begin
High_S:=' High='+IntToStr(High(P));
Low_S:='Low='+IntToStr(Low(P));
S:=Low_S+High_S;
Label1.Caption:=S;
end;
S:=Low=5 High=21
[String type]
procedure TForm1.Button1Click(Sender: TObject);
var
P : String[23];
Low_S:String;
High_S:string;
S:String;
begin
High_S:=' High='+IntToStr(High(P));
Low_S:='Low='+IntToStr(Low(P));
S:=Low_S+High_S;
Label1.Caption:=S;
end;
S:=Low=0 Hight=23
P:ShortString;
S:=Low=0 Hight=255
P:String;
長字串不可,會有錯誤訊號.
[Open array]
function Sum( var X: array of Double): Double;
var
I: Word;
S: Double;
begin
S := 0;
{ Note that open array index range is always zero-based. }
for I := 0 to High(X) do S := S + X[I];
Sum := S;
end;
Example
function Sum( var X: array of Double): Double;
var
I: Word;
S: Real;
begin
S := 0; { Note that open array index range is always zero-based. }
for I := 0 to High(X) do S := S + X[I];
Sum := S;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
List1: array[0..3] of Double;
List2: array[5..17] of Double;
X: Word;
S, TempStr: string;
begin
for X := Low(List1) to High(List1) do
List1[X] := X * 3.4;
for X := Low(List2) to High(List2) do
List2[X] := X * 0.0123;
Str(Sum(List1):4:2, S);
S := 'Sum of List1: ' + S + #13#10;
S := S + 'Sum of List2: ';
Str(Sum(List2):4:2, TempStr);
S := S + TempStr;
MessageDlg(S, mtInformation, [mbOk], 0);
end;
## Low, High Example
-----------------------------------------------------------------------------
Low 傳回註腳的最小值.
-----------------------------------------------------------------------------
Unit System
函數原型 function Low(X);
說明 Ordinal type The lowest value in the range of the type
Array type The lowest value within the range of the
index type of the array
String type Returns 0
Open array Returns 0
String parameter Returns 0
-----------------------------------------------------------------------------
Ord 傳回列舉型態的數值.
-----------------------------------------------------------------------------
Unit System
函數原型 function Ord(X): Longint;
範例 procedure TForm1.Button1Click(Sender: TObject);
type
Colors = (RED,BLUE,GREEN);
var
S: string;
begin
S := 'BLUE has an ordinal value of ' + IntToStr(Ord(RED)) +
#13#10;
S := S+'The ASCII code for "c" is ' + IntToStr(Ord('c')) + '
decimal';
MessageDlg(S, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
Round 將實數轉爲整數.(有四捨五入)
-----------------------------------------------------------------------------
Unit System
函數原型 function Round(X: Extended): Longint;
範例 var
S, T: string;
begin
Str(1.4:2:1, T);
S := T + ' rounds to ' + IntToStr(Round(1.4)) + #13#10;
Str(1.5:2:1, T);
S := S + T + ' rounds to ' + IntToStr(Round(1.5)) + #13#10;
Str(-1.4:2:1, T);
S := S + T + ' rounds to ' + IntToStr(Round(-1.4)) + #13#10;
Str(-1.5:2:1, T);
S := S + T + ' rounds to ' + IntToStr(Round(-1.5));
MessageDlg(S, mtInformation, [mbOk], 0);
end;
-----------------------------------------------------------------------------
Trunc 將實數轉爲整數.(小數直接捨棄)
-----------------------------------------------------------------------------
Unit System
函數原型 function Trunc(X: Extended): Longint;
Untyped file routines
var
S, T: string;
begin
Str(1.4:2:1, T);
S := T + ' Truncs to ' + IntToStr(Trunc(1.4)) + #13#10;
Str(1.5:2:1, T);
S := S + T + ' Truncs to ' + IntToStr(Trunc(1.5)) + #13#10;
Str(-1.4:2:1, T);
S := S + T + ' Truncs to ' + IntToStr(Trunc(-1.4)) + #13#10;
Str(-1.5:2:1, T);
S := S + T + ' Truncs to ' + IntToStr(Trunc(-1.5));
MessageDlg(S, mtInformation, [mbOk], 0);
end;
-------------------------
var
f: file of Integer;
i,j: Integer;
begin
AssignFile(f,'TEST.INT');
Rewrite(f);
for i := 1 to 6 do
Write(f,i);
Writeln('File before truncation:');
Reset(f);
while not Eof(f) do
begin
Read(f,i);
Writeln(i);
end;
Reset(f);
for i := 1 to 3 do
Read(f,j); { Read ahead 3 records }
Truncate(f); { Cut file off here }
Writeln;
Writeln('File after truncation:');
Reset(f);
while not Eof(f) do
begin
Read(f,i);
Writeln(i);
end;
CloseFile(f);
Erase(f);
end;
-----------------------------------------------------------------------------
BlockRead 讀取檔案至記憶體區塊.
-----------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
FromF, ToF: file;
NumRead, NumWritten: Integer;
Buf: array[1..2048] of Char;
begin
if OpenDialog1.Execute then { 開檔對話盒}
begin
AssignFile(FromF, OpenDialog1.FileName);{}
Reset(FromF, 1); { Record size = 1 }
if SaveDialog1.Execute then { Display Save dialog box}
begin
AssignFile(ToF, SaveDialog1.FileName);{ Open output file }
Rewrite(ToF, 1); { Record size = 1 }
Canvas.TextOut(10, 10, 'Copying ' + IntToStr(FileSize(FromF))+'bytes...');
repeat
BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
BlockWrite(ToF, Buf, NumRead, NumWritten);
until (NumRead = 0) or (NumWritten <> NumRead);
CloseFile(FromF);
CloseFile(ToF);
end;
end;
end;
## BlockRead, BlockWrite, SaveDialog Example
-----------------------------------------------------------------------------
BlockWrite 將記憶體區塊寫入檔案.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure BlockRead(var F: File; var Buf; Count: Integer
[; var Result: Integer]);
函數原型 procedure BlockWrite(var f: File; var Buf; Count: Integer
[; var Result: Integer]);
範例 var
FromF, ToF: file;
NumRead, NumWritten: Integer;
Buf: array[1..2048] of Char;
begin
if OpenDialog1.Execute then
{ Display Open dialog box }
begin
AssignFile(FromF, OpenDialog1.FileName);
Reset(FromF, 1); { Record size = 1 }
if SaveDialog1.Execute then
{ Display Save dialog box }
begin
AssignFile(ToF, SaveDialog1.FileName);
{ Open output file }
Rewrite(ToF, 1); { Record size = 1 }
Canvas.TextOut(10, 10,'Copying '+
IntToStr(FileSize(FromF))+ ' bytes...');
repeat
BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
BlockWrite(ToF, Buf, NumRead, NumWritten);
until (NumRead = 0) or (NumWritten <>
NumRead);
CloseFile(FromF);
CloseFile(ToF);
end;
end;
end;
======================================
Variant support routines 鬼牌變數函式
======================================
VarArrayCreate 建立一個variant array.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarArrayCreate(const Bounds: array of Integer;
VarType: Integer): Variant;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
A:Variant;
S:String;
begin
A:=VarArrayCreate([0,4],varVariant);
A[0]:=1;
A[1]:=1234.5678;
A[2]:='Hello world';
A[3]:=TRUE;
A[4]:=VarArrayOf([1 ,10 ,100 ,10000]);
S:=A[4][2];
S:=A[2]+' '+S;
Label1.Caption:=S;
end;
說明 S:=A[4][2]; Variant可以不用函數來做轉換.
只能單獨使用,如爲下列則有誤.
S:=A[2]+' '+A[4][2];
VarType
varEmpty $0000 The variant is Unassigned.
varNull $0001 The variant is Null.
varSmallint $0002 16-bit signed integer (type Smallint).
varInteger $0003 32-bit signed integer (type Integer).
varSingle $0004 Single-precision floating-point value
(type Single).
varDouble $0005 Double-precision floating-point value
(type Double).
varCurrency $0006 Currency floating-point value (type Currency).
VarDate $0007 Date and time value (type TDateTime).
VarOleStr $0008 Reference to a dynamically allocated
UNICODE string.
varDispatch $0009 Reference to an OLE automation object
(an IDispatch interface pointer).
VarError $000A Operating system error code.
varBoolean $000B 16-bit boolean (type WordBool).
varVariant $000C Variant (used only with variant arrays).
varUnknown $000D Reference to an unknown OLE object
(an IUnknown interface pointer).
varByte $0011 8-bit unsigned integer (type Byte).
VarString $0100 Reference to a dynamically-allocated long string
(type AnsiString).
varTypeMask $0FFF Bit mask for extracting type code. This constant
is a mask that can be combined with the VType
field using a bit-wise AND..
varArray $2000 Bit indicating variant array. This constant is a
mask that can be combined with the VType field
using a bit-wise AND to determine if the variant
contains a single value or an array of values.
VarByRef $4000 This constant can be AND'd with Variant.VType
to determine if the variant contains a pointer to
the indicated data instead of containing the data
itself.
範例 var
V1, V2, V3, V4, V5: Variant;
I: Integer;
D: Double;
S: string;
begin
V1 := 1; { Integer value }
V2 := 1234.5678; { Real value }
V3 := 'Hello world'; { String value }
V4 := '1000'; { String value }
V5 := V1 +V2 +V4; { Real value 2235.5678 }
I := V1; { I = 1 }
D := V2; { D = 1234.5678 }
S := V3; { S = 'Hello world' }
I := V4; { I = 1000 }
S := V5; { S = '2235.5678' }
end;
-----------------------------------------------------------------------------
VarArrayOf 建立一個簡單的一維variant array
-----------------------------------------------------------------------------
Unit System
函數原型 function VarArrayOf(const Values: array of Variant): Variant;
範例 var
A:Variant;
begin
A:=VarArrayOf([1 ,10 ,'Hello ,10000]);
S:=A[1]+' '+IntToStr(A[2]);
Label1.Caption:=S;
end;
-----------------------------------------------------------------------------
VarArrayRedim 重定variant陣列中高維部分的高註腳.
-----------------------------------------------------------------------------
Unit System
-----------------------------------------------------------------------------
函數原型 procedure VarArrayRedim(var A: Variant; HighBound:Integer);
-----------------------------------------------------------------------------
VarArrayDimCount 傳回Variant陣列的維數.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarArrayDimCount(const A: Variant): Integer;
-----------------------------------------------------------------------------
VarArrayHighBound 傳回Variant陣列中一維的高註腳.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarArrayHighBound(const A: Variant; Dim: Integer):Integer;
-----------------------------------------------------------------------------
VarArrayLowBound 傳回Variant陣列中一維的低註腳.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarArrayLowBound(const A: Variant; Dim: Integer):
Integer;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
A:Variant;
Count:Integer;
HighBound:Integer;
LowBound:Integer;
i:Integer;
S:String;
begin
A:=VarArrayCreate([0,5, 1,3],varVariant);
Count:=VarArrayDimCount(A);
S:=#13+'維數:'+IntToStr(Count)+#13;
for i:=1 To Count do
Begin
HighBound:=VarArrayHighBound(A,i);
LowBound:=VarArrayLowBound(A,i);
S:=S+'HighBound: '+IntToStr(HighBound)+#13;
S:=S+'LowBound : '+IntToStr(LowBound)+#13;
End;
ShowMessage(S);
end;
-----------------------------------------------------------------------------
VarArrayLock 將variant陣列==>指定給一陣列變數.
-----------------------------------------------------------------------------
VarArrayUnLock 解除上述的指定.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarArrayLock(var A: Variant): Pointer;
函數原型 procedure VarArrayUnlock(var A: Variant);
範例 procedure TForm1.Button1Click(Sender: TObject);
Const
HighVal=12;
type
TData=array[0..HighVal, 0..HighVal] of Integer;
var
A:Variant;
i,j:Integer;
Data:^TData;
begin
A:=VarArrayCreate([0,HighVal, 0,HighVal],varInteger);
for i:=0 to HighVal do
for j:=0 to HighVal do
A[i,j]:=i*j;
Data:=VarArrayLock(A);
for i:=0 to HighVal do
for j:=0 to HighVal do
Grid1.Cells[i+1,j+1]:=IntToStr(Data^[i,j]);
VarArrayUnLock(A);
end;
-----------------------------------------------------------------------------
VarIsArray 傳回Variant是否爲一個陣列.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarIsArray(const V: Variant): Boolean;
VarIsEmpty 傳回Variant是否尚未註冊.(空的)
Unit System
函數原型 function VarIsEmpty(const V: Variant): Boolean;
範例 procedure TForm1.Button1Click(Sender: TObject);
var
A:Variant;
S:String;
begin
A:=VarArrayCreate([0,5, 0,7],varVariant);
if VarIsEmpty(A) Then
S:='True'
else
S:='False';
Label1.Caption:=S;
end;
-----------------------------------------------------------------------------
** S:=False,A以經建立了.
-----------------------------------------------------------------------------
VarIsNull 傳回Variant是否爲NULL.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarIsNull(const V: Variant): Boolean;
-----------------------------------------------------------------------------
VarAsType 將Variant轉爲另外一個型態的Variant.
-----------------------------------------------------------------------------
VarCast
-----------------------------------------------------------------------------
Unit System
函數原型 function VarAsType(const V: Variant; VarType: Integer):
Variant;
函數原型 procedure VarCast(var Dest: Variant; const Source: Variant;
VarType: Integer);
說明 VarType不可爲varArray or varByRef.
-----------------------------------------------------------------------------
VarType 傳回Variant的型態.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarType(const V: Variant): Integer;
-----------------------------------------------------------------------------
VarClear 將variant清除,成爲Unassigned狀態.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure VarClear(var V: Variant);
-----------------------------------------------------------------------------
VarCopy 拷貝一個variant.
-----------------------------------------------------------------------------
Unit System
函數原型 procedure VarCopy(var Dest: Variant; const Source: Variant);
說明 與Dest:=Source;效果一樣.
-----------------------------------------------------------------------------
VarFromDateTime 將DateTime轉爲Variant.
-----------------------------------------------------------------------------
VarToDateTime 將Variant轉爲DateTime.
-----------------------------------------------------------------------------
Unit System
函數原型 function VarFromDateTime(DateTime: TDateTime): Variant;
函數原型 function VarToDateTime(const V: Variant): TDateTime;
=============================
函數
==============================
procedure TForm1.Button2Click(Sender: TObject);
var
Bitmap: TBitmap;
begin
Bitmap := TBitmap.Create;
try
Bitmap.LoadFromFile('G:/33.bmp ');
Form1.Canvas.Brush.Bitmap := Bitmap;
Form1.Canvas.FillRect(Rect(0,0,18,15));
finally
Form1.Canvas.Brush.Bitmap := nil;
Bitmap.Free;
end;
end;
## Canvas, Brush, Bitmap, FillRect Example
=======================================
TextOut
=======================================
procedure TForm1.FormCreate(Sender: TObject);
var
HeaderSection: THeaderSection;
I: Integer;
begin
for I := 0 to 4 do
begin
HeaderSection := HeaderControl1.Sections.Add;
HeaderSection.Text := 'Text Section ' + IntToStr(I);
HeaderSection.MinWidth := length(HeaderSection.Text) * Font.Size;
// Owner draw every other section
if (I mod 2 = 0) then
HeaderSection.Style := hsOwnerDraw
else
HeaderSection.Style := hsText;
end;
end;
procedure TForm1.HeaderControl1DrawSection(HeaderControl: THeaderControl;
Section: THeaderSection; const Rect: TRect; Pressed: Boolean);
begin
with HeaderControl.Canvas do
begin
// highlight pressed sections
if Pressed then
Font.Color := clRed
else
Font.Color := clBlue;
TextOut(Rect.Left + Font.Size, Rect.Top + 2, 'Owner Drawn text');
end;
end;
## HeaderSection, OnDrawSection, Sections, Canvas, TextOut example
----------------------------------------------------------
Trunc Example
-----------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
S, T: string;
begin
Str(1.4:2:1, T);
S := T + ' Truncs to ' + IntToStr(Trunc(1.4)) + #13#10;
Str(1.5:2:1, T);
S := S + T + ' Truncs to ' + IntToStr(Trunc(1.5)) + #13#10;
Str(-1.4:2:1, T);
S := S + T + ' Truncs to ' + IntToStr(Trunc(-1.4)) + #13#10;
Str(-1.5:2:1, T);
S := S + T + ' Truncs to ' + IntToStr(Trunc(-1.5));
MessageDlg(S, mtInformation, [mbOk], 0);
end;
未歸類
--------------------
WrapText
--------------------
SysUtils
type TSysCharSet = set of Char
var
S, R: string;
begin
S:= '123456_123456_123456';
R:= WrapText( S, #13#10, ['1', '4'], 4);
MessageDlg( R, mtInformation, [mbOk], 0);
end;
================================
WideCharToStrVar(Source: PWideChar;var Dest: string );
-------------------------
System
-----------------
=========================
WideCharToString( Source: PWideChar ): string;
-------------------------
System
=============================
WideCharLenToStrVar( Source: PWideChar;SourceLen: Integer;var Dest: string );
------------------------------
System
==============================
WideCharLenToString(Source: PWideChar;SourceLen: Integer ): string
-----------------------
System
============================
AnsiCompareFileName(const S1, S2: string ): Integer; SysUtils
===================================
AnsiExtractQuotedStr (var S: PChar;Quote: Char ): string;
SysUtils
var
S1: PChar;
S2: string;
begin
S1:= '/??. ?????????? /???.56/';
S2:= AnsiExtractQuotedStr(S1,'/'); // S2 := '??. ?????????? '
MessageDlg(S2, mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
AnsiLastChar( const S: string ): PChar;
SysUtils
----------------------------------------------------------
AnsiLowerCaseFileName( const S: string ): string;
SysUtils
----------------------------------------------------------
AnsiPos ( const Substr, S: string ): Integer
SysUtils
var
Substr, S: string;
I: Integer;
begin
S:= '???????? ??????';
Substr:= '???';
I:= AnsiPos(Substr, S); // I:= 3
...
end;
----------------------------------------------------------
AnsiQuotedStr (const S: string;Quote: Char ): string;
SysUtils
var
S: string;
begin
S:= '1997-1998??.';
S:= AnsiQuotedStr(S, '-'); // S := '-1997--1998??.-'
MessageDlg(S, mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
AnsiSameStr ( const S1, S2: string ): Boolean;
SysUtils
----------------------------------------------------------
AnsiSameText ( const S1, S2: string ): Boolean;
SysUtils
----------------------------------------------------------
AnsiStrComp( S1, S2: PChar ): Integer
SysUtils
----------------------------------------------------------
AnsiStrIComp( S1, S2: PChar ): Integer;
SysUtils
----------------------------------------------------------
AnsiStrLastChar( P: PChar ): PChar;
SysUtils
----------------------------------------------------------
AnsiStrLComp(S1, S2: PChar;MaxLen: Cardinal ): Integer;
SysUtils
var
P1,P2: PChar;
Len : Integer;
begin
P1:= '?????? ?????????? ?? ?????? ????????? ????????.';
P2:= '?????? ?????????? ?? ?????? ????????? ????????!';
Len:= length(p1)-1;
If AnsiStrLIComp(P1, P2, Len)=0 then MessageDlg( P1+ #13+ P2+ #13+ '??????, ? ???????? ?????? '+ IntTostr(Len)+' ????????, ?????', mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
AnsiStrLIComp(S1, S2: PChar;MaxLen: Cardinal ): Integer;
SysUtils
var
P1,P2: PChar;
Len : Integer;
begin
Len:= 7;
P1:= '?????? 1';
P2:= '?????? 2';
If AnsiStrLIComp(P1, P2, Len)=0 then MessageDlg( P1+ #13+ P2+ #13+ '??????, ? ???????? ?????? '+ IntTostr(Len)+' ????????, ?????', mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
AnsiStrLower( S1, S2: PChar ): PChar;
SysUtils
----------------------------------------------------------
AnsiStrPos( S, SubStr: PChar ): PChar
SysUtils
var
S1,S2: Pchar;
begin
S1:= '???? ? ???? - ? ????? ????!';
S2:= AnsiStrPos(S1,'?????'); // S2 :='????? ????!'
MessageDlg( S2, mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
AnsiStrRScan( S : PChar; Chr: Char ): PChar;
SysUtils
var
P1,P2: PChar;
begin
P1:= 'C:/windows/temp';
P2:= AnsiStrRScan(P1, '/'); { P2 := '/temp' }
MessageDlg( P2, mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
AnsiStrScan( S : PChar; Chr: Char ): PChar;
SysUtils
var
P1,P2: PChar;
begin
P1:= 'http://www.atrussk.ru/delphi';
P2:= AnsiStrScan(P1, '/'); { P2 := '//www.atrussk.ru/delphi' }
MessageDlg( P2, mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
AnsiStrUpper( S : PChar ): PChar
SysUtils
----------------------------------------------------------
AnsiUpperCaseFileName( const S: string ): string;
SysUtils
----------------------------------------------------------
ByteToCharIndex(const S: string;Index: Integer ): Integer;
SysUtils
----------------------------------------------------------
ByteToCharLen( const S: string;MaxLen: Integer ): Integer;
SysUtils
----------------------------------------------------------
ByteType(const S: string;Index: Integer ): TMbcsByteType;
SysUtils
mbSingleByte -
mbLeadByte -
mbTrailByte -
----------------------------------------------------------
CharToByteIndex(const S: string;Index: Integer ): Integer;
SysUtils
----------------------------------------------------------
CharToByteLen(const S: string;MaxLen: Integer ): Integer;
SysUtils
----------------------------------------------------------
Chr ( X: Byte ): Char;
SysUtils
MessageDlg('ASCII-???? 77 ????????????? ?????? - ' + Chr(77), mtInformation, [mbOk], 0);
----------------------------------------------------------
FormatMaskText(const EditMask: string;const Value: string ): string;
Mask
----------------------------------------------------------
GetFormatSettings;
SysUtils
----------------------------------------------------------
IsDelimiter (const Delimiters, S: string;Index: Integer ): Boolean;
SysUtils
var
S: string;
begin
S:= '???????, ?????? ??????????!';
If IsDelimiter( '!.,-', S, 8) then
MessageDlg( '???????!', mtWarning, [mbOK], 0)
else
MessageDlg( '??????????!', mtWarning, [mbOK], 0);
end;
----------------------------------------------------------
IsPathDelimiter (const S: string;Index: Integer ): Boolean;
SysUtils
If IsPathDelimiter( S, Length(S))
then S:=Copy( S, 1, Length(S)-1);
----------------------------------------------------------
LastDelimiter (const Delimiters, S: string ): Integer;
SysUtils
var
I: Integer;
begin
I:= LastDelimiter('!;.,-', '???????, ??????, ??????????'); // I := 16
end;
----------------------------------------------------------
LineStart( Buffer, BufPos : PChar ): PChar
Classes--
--------------------------------------------------------
QuotedStr ( const S: string ): string;
SysUtils
----------------------------------------------------------
SetLength ( var S; Length: Integer );
System
----------------------------------------------------------
SetString (var S: string;Buffer: PChar;Length: Integer );
System
----------------------------------------------------------
Str ( X [: Width [: Decimals ]]; var S );
System
var
S: string;
I: Real;
begin
I:= -52.123456789;
Str( I:6:2, S); { S := ' -52.12' }
MessageDlg( S, mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
StrBufSize( S: PChar ): Cardinal;
SysUtils
----------------------------------------------------------
StrByteType(S: PChar;Index: Cardinal ): TMbcsByteType;
SysUtils
----------------------------------------------------------
StringOfChar (Ch: Char;Count: Integer ): string;
System
S:= StringOfChar( '.' , 3); // S:= '...'
----------------------------------------------------------
StringReplace (const S, OldSubstr, NewSubstr: string;Flags: TReplaceFlags ): string;
SysUtils
type TReplaceFlags = set of ( rfReplaceAll, rfIgnoreCase );
var
S: string;
Flags: TReplaceFlags;
begin
Flags:= [ rfReplaceAll, rfIgnoreCase ];
S:= '???? - ????? ?????';
S:= StringReplace( S, '??', '??', Flags); // S :='???? - ????? ?????' }
MessageDlg( S, mtInformation, [mbOk], 0);
end;
----------------------------------------------------------
StringToWideChar(const Source: string;Dest: PWideChar;DestSize: Integer ): PWideChar
System
----------------------------------------------------------
UniqueString( var S: string );
System
----------------------------------------------------------
==============================
訊息
==============================
---------------------------------------------------------------
ShowMessage 訊息
---------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
buffer: array [0..255] of char;
FileToFind: string;
begin
GetWindowsDirectory(buffer, SizeOf(buffer));
FileToFind := FileSearch(Edit1.Text, GetCurrentDir + ';' + buffer);
if FileToFind = ' then
ShowMessage('Couldn't find ' + Edit1.Text + '.')
else
ShowMessage('Found ' + FileToFind + '.');
end;
## FileSearch, ShowMessage Example
----------------------------------------------------------
FindComponent
範例(1)
type
LogPal = record
lpal : TLogPalette;
dummy:Array[0..255] of TPaletteEntry;
end;
procedure TForm1.SaveAsBmpClick(Sender: TObject);
var
Source: TComponent;
SysPal : LogPal;
tempCanvas: TCanvas;
sourceRect, destRect: TRect;
image2save: TImage;
notUsed: HWND;
begin
Source := FindComponent(Edit1.Text);
if (not Source is TControl) or
((not Source is TWinControl) and ((Source as TControl).Parent = nil)) then
begin
Beep;
ShowMessage(Edit1.Text + ' is not a valid control.');
Exit;
end;
tempCanvas := TCanvas.Create;
try
with Source as TControl do
tempCanvas.Handle := GetDeviceContext(notUsed);
image2save:=TImage.create(self);
try
with image2save do
begin
Height := (Source as TControl).Height;
Width := (Source as TControl).Width;
destRect := Rect(0,0,Width,Height);
if Source is TWinControl then
sourceRect := destRect;
else
sourceRect := (Source as TControl).BoundsRect;
Canvas.CopyRect(destRect,tempCanvas,sourceRect);
SysPal.lPal.palVersion:=$300;
SysPal.lPal.palNumEntries:=256;
GetSystemPaletteEntries(tempCanvas.Handle,0,256,SysPal.lpal.PalpalEntry);
Picture.Bitmap.Palette:= CreatePalette(Syspal.lpal);
end;
if SaveDialog1.Execute then
image2save.Picture.SaveToFile(SaveDialog1.FileName);
finally
image2save.Free;
end;
finally
tempCanvas.Free;
end;
end;
範例(2)
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
const
NamePrefix = 'MyEdit';
begin
for i := 1 to 20 do begin
TEdit.Create(Self).Name := NamePrefix + IntToStr(i);
with TEdit(FindComponent(NamePrefix + IntToStr(i))) do
begin
Left := 10;
Top := i * 20;
Parent := self;
end;
end;
end;
=========================================================
procedure TForm1.Button1Click(Sender: TObject);
var
A: Variant;
begin
A := VarArrayCreate([0, 4], varVariant);
A[0] := 1;
A[1] := 1234.5678;
A[2] := 'Hello world';
A[3] := True;
A[4] := VarArrayOf([1, 10, 100, 1000]);
Edit1.Text :=(A[2]); { Hello world }
Edit2.Text :=(A[4][2]); { 100 }
end;
procedure TForm1.Button2Click(Sender: TObject);
var
s: string;
begin
s := 'Honest Abe Lincoln';
Delete(s,8,4);
Canvas.TextOut(10, 130, s); { 'Honest Lincoln' }
end;
procedure TForm1.Button3Click(Sender: TObject);
var S: string;
begin
S := 'ABCDEF';
S := Copy(S, 2, 3);
Edit1.Text :=s;{ 'BCD' }
end;
procedure TForm1.Button4Click(Sender: TObject);
var
S: string;
begin
S := Concat('ABC', 'DEF');
Edit1.Text :=s; { 'ABCDE' }
end;
procedure TForm1.Button5Click(Sender: TObject);
var
S: string;
begin
S := 'Honest Lincoln';
Insert('Abe ', S, 8);
Edit1.Text :=s; { 'Honest Abe Lincoln' }
end;
procedure TForm1.Button6Click(Sender: TObject);
var
S: string;
begin
S := 'The Black Knight';
Canvas.TextOut(10, 130, 'String Length = ' + IntToStr(Length(S)));{String Length = 16}
Edit1.Text :=s;{The Black Knight}
end;
procedure TForm1.Button7Click(Sender: TObject);
var S: string;
begin
S := ' 123.5';
{ Convert spaces to zeroes }
while Pos(' ', S) > 0 do
S[Pos(' ', S)] := '0';
Edit1.Text :=s; {000123.5}
end;
===========================================================================
數學函數 (Arithmetic Routines)
Unit: System
===========================================================================
Abs 傳回叄數的絕對值。 function Abs(X);
ArcTan 傳回正切函數的反函數值。 function ArcTan(X: Real): Real;
Cos 傳回餘弦函數值 function Cos(X: Real): Real;
(X 以弧度爲單位)。
Exp 傳回自然指數值。 function Cos(X: Real): Real;
Frac 傳回叄數的小數部份。 function Frac(X: Real): Real;
Int 傳回叄數的整數部份。 function Int(X: Real): Real;
Ln 傳回自然對數值。 function Ln(X: Real): Real;
Pi 傳回圓周率π的值。 function Pi: Real;
Sin 傳回正弦函數值。 function Sin(X: Real): Real;
Sqr 傳回叄數的平方。 function Sqr(X: Real): (Real);
Sqrt 傳回叄數的平方根。 function Sqrt(X: Real): Real;
===========================================================================
控制檯函數 (Console Routines)
===========================================================================
Unit: WinCrt
函數名稱 函數說明 函數語法
===========================================================================
AssignCrt 將文字檔連結到一個控制檯視窗。 procedure AssignCrt(var f: Text);
ClrEol 清附遊標位置到該行最後的所有字元。procedure ClrEol;
ClrScr 清附螢幕並重置遊標至左上角。 procedure ClrScr;
CursorTo 移動遊標至給定座標。 procedure CursorTo(X, Y:Integer);
DoneWinCrt 結束控制檯視窗。 procedure DoneWinCrt;
GotoXY 移動遊標至給定座標。 procedure GotoXY(X, Y: Byte);
InitWinCrt 建立控制檯視窗。 procedure InitWinCrt;
KeyPressed 判斷是否有一按鍵。 function KeyPressed:Boolean;
ReadBuf 從控制檯視窗讀入一行。 function ReadBuf(Buffer: Pchar;Count: Word):
ReadKey 讀取按鍵字元。function ReadKey: Char;
ScrollTo 捲動控制檯視窗至顯示位置。procedure ScrollTo(X, Y: Integer);
TrackCursor 捲動控制檯視窗宜到遊標可見。procedure TrackCursor;
WhereX 傳回遊標的X 座標。function WhereX: Byte;
WhereY 傳回遊標的Y 標標。function WhereY: Byte;
WriteBuf 寫入一區塊字元到控制檯視窗。procedure WriteBuf
WriteChar 寫一個字元到控制檯視窗。procedure WriteChar(CH: Char);
=================================================
日期與時間函數 (Date and Time Routines)
Unit: SysUtils
========================================
Date 傳回今天日期。function Date: TDateTime;
DateTimeToStr 將時間格式轉爲字串。function DateTimeToStr(DateTime: TDateTime):String;
DateTimeToString 將時間格式轉爲字串。
procedure DateTimeToString(var Result: string;const Format: string;DateTime: TDateTime);
DateToStr 將日期格式轉爲字串。function DateToStr(Date: TDateTime): String;
DayOfWeek 傳回今天星期幾。function DayOfWeek(Date: TDateTime): Integer;
DecodeDate 分解所指定的日期爲年、月、日。
procedure DecodeDate(Date: TDateTime;var Year, Month, Day:Word);
DecodeTime 分解所指定的日期爲時、分、秒。
procedure DecodeTime(Time: TDateTime;var Hour, Min, Sec,MSec: Word);
EncodeDate 傳回將年、月、日所組合的日期格式。
function EncodeDate(Year, Month, Day: Word):TDateTime;
EncodeTime 傳回將時、分、秒所組合的時間格式。
function EncodeTime(Hour, Min, Sec, MSec:Word): TDateTime;
FormatDateTime 以指定的格式傳回日期時間。
function FormatDateTime(const Format: string;DateTime: TDateTime):String;
Now 傳回現在的日期時間。function Now: TDateTime;
StrToDate 將字串轉爲日期格式。function StrToDate(const S:string): TDateTime;
StrToDateTime 將字串轉爲日期時間格式function StrToDateTime(const S: string): TDateTime;
StrToTime 將字串轉爲時間格式。function StrToTime(const S:string): TDateTime;
Time 傳回現在時間。function Time: TDateTime;
TimeToStr 將時格式轉爲字串。function TimeToStr(Time:TDateTime): String;
========================================
動態配置函數(Dynamic Allocation Routines)
Unit: System
========================================
Dispose 釋回一個動態變數。procedure Dispose(var P: Pointer);
Free 釋放一個物件複本。procedure Free;
FreeMem 釋回一給定大小的動態變數。procedure FreeMem(var P:Pointer; Size: Word);
GetMem 建立一個指定大小的動態變數,並由Pointer 叄數傳回位址。
procedure GetMem(var P:Pointer; Size: Word);
New 建立一個新的動態變數,並將Pointer 叄數指向它。
procedure New(var P: Pointer);
function New(<pointer type>):Pointer;
MaxAvail 傳回連續最大的可配置空間。function MaxAvail: Longint;
MemAvail 傳回所有的可配置空間。function MemAvail: Longint;
========================================
檔案管理函數
Unit: SysUtils
========================================
ChangeFileExt 變更檔案的延伸檔名。
function ChangeFileExt(const FileName,Extension: string):string;
DateTimeToFileDate 將Delphi 的日期格式轉換爲DOS的日期格式。
functionDateTimeToFileDate(DateTime:TDateTime): Longint;
DeleteFile 刪除一個檔案。
function DeleteFile(const FileName: string):Boolean;
DiskFree 傳回磁碟的可用空間。function DiskFree(Drive: Byte): Longint;
DiskSize 傳回指定磁碟的容量大小。function DiskSize(Drive: Byte): Longint;
ExpandFileName 傳回一個完整的路徑及檔名字串。
function expandFileName(const FileName: string):string;
ExtractFileExt 傳回檔案的延伸檔名。function ExtractFileExt(const FileName string):string;
ExtractFileName 傳回檔案的檔名。function ExtractFileName(const FileName: string):string;
ExtractFilePath 傳回檔案的路徑。function ExtractFilePath(const FileName: string):string;
FileAge 傳回檔案的年紀function FileAge(const FileName: string):Longint;
FileCreate 以指定檔名建立一個檔案。function FileCreate(const FileName: string):Integer;
FileClose 關閉指定的檔案。procedureFileClose(Handle: Integer);
FileDateToDateTime 將DOS 的日期格式轉爲Delphi 的日期格式。
function FileDateToDateTime(FileDate: Longint):TDateTime;
FileExists 判別檔案是否存在。function FileExists(const FileName: string):Boolean;
FileGetAttr 傳回檔案屬性。function FileGetAttr(const FileName: string):Integer;
FileGetDate 傳回檔案的日期及時間。function FileGetDate(Handle: Integer): Longint;
FileRead 從指定的檔案讀入資料。
function FileRead(Handle:Integer; var Buffer;Count:Longint):Longint;
FileSearch 在目錄列中搜尋指定的檔案。function FileSearch(constName, DirList: string):string;
FileSeek 改變檔案遊標的位置。function FileSeek(Handle: Integer;Offset: Longint;Origin: Integer):Longint;
FileSetAttr 設定檔案屬性。function FileSetAttr(const FileName: string;Attr:Integer): Integer;
FileSetDate 設定檔案的日期及時間。procedure FileSetDate(Handle: Integer; Age:Longint);
FileOpen 開啓檔案。function FileOpen(const FileName: string; Mode:Word): Integer;
FileWrite 寫資料到檔案。function FileWrite(Handle:Integer;const Buffer; Count:Longint): Longint;
FindClose 終止找尋第一個/下一個的動作。procedure FindClose(var SearchRec: TSearchRec);
FindFirst 尋找第一個符合的檔案並設定其屬性。
function FindFirst(const Path: string;Attr: Word; var F:TSearchRec): Integer;
FindNext 傳回下一個符合的檔案。function FindNext(var F:TSearchRec): Integer;
RenameFile 變更檔名。function RenameFile(const OldName,NewName: string):Boolean;
========================================
浮點數轉換函數 (Floating-point Conversion Routines)
Unit: SysUtils
========================================
FloatToDecimal 將浮點數值分成小數及整數部份的數字傳回。
procedure FloatToDecimal(var Result: TFloatRec;Value:Extended;Precision, Decimals:Integer);
FloatToStrF 依照指定格式將浮點數轉成字串描述。
function FloatToStrF(Value: Extended; Format:TFloatFormat;Precision,Digits: Integer): string;
FloatToStr 將浮點數轉成字串描述。function FloatToStr(Value: Extended): string;
FloatToText 將所給的浮點數值,分成小數及整數部份的數字依照格式傳回。
function FloatToText(Buffer: Pchar; Value:Extended;Format:TFloatFormat;Precision,Digits: Integer): Integer;
FloatToTextFmt 將浮點數依照格式轉成字串傳回。
function FloatToTextFmt(Buffer: PChar; Value:Extended;Format: PChar) :Integer;
FormatFloat 將浮點數值依照Format 格式傳回。
function FormatFloat(constFormat: string;Value:Extended):string;
StrToFloat 將所給字串轉成一個浮點數值。
function StrToFloat(const S: string): Extended;
TextToFloat 將一個null 結尾字串轉成浮點數值
function TextToFloat(Buffer: PChar;var Value:Extended): Boolean;
========================================
流程控制函數 (Flow-control Routines)
Unit: System
========================================
Break 終止迴圈。如for, while 及repeat 迴圈。
procedure Break;
Continue 繼續迴圈。如for, while 及repeat 迴圈。
procedure Continue;
Exit 離開目前的區塊。procedure Exit;
Halt 停止程式的執行並回到作業系統。
procedure Halt[ ( Exitcode: Word ) ];
RunError 停止程式執行。procedure RunError[ ( Errorcode: Byte ) ];
========================================
輸出入函數 (I/O Routines)
Unit: System
========================================
AssignFile 指定一個檔案到檔案變數。procedure AssignFile(var f, String);
CloseFile 關閉檔案。procedure CloseFile(var F);
Eof 判斷是否已到檔案結尾。
Typed or untyped files: functionEof(var F): BooleanText files:function Eof [ (var F: Text) ]:Boolean;
Erase 清除檔案內容。procedure Erase(var F);
FilePos 傳回目前檔案遊標位置。function FilePos(var F): Longint;
FileSize 傳回檔案的大小function FileSize(var F):Longint;
GetDir 傳回指定磁碟的工作目錄。procedure GetDir(D: Byte; var S: String);
IOResult 傳回最後I/O 執行的狀態。function IOResult: Integer;
MkDir 建立一子目錄。procedure MkDir(S: String);
Rename 變更外部檔案的檔名。procedure Rename(var F; Newname);
Reset 開啓一個已存在的檔案。procedure Reset(var F [: File; Recsize: Word ] );
Rewrite 建立並開啓一個新檔。procedure Rewrite(var F: File [; Recsize: Word ] );
RmDir 刪除一個空目錄。procedure RmDir(S: String);
Seek 移動檔案遊標。procedure Seek(var F; N: Longint);
Truncate 刪截目前位置以後的檔案內容。procedure Truncate(var F);
========================================
記憶體管理函數 Memory-management Routines)
Unit: SysUtils
========================================
AllocMem 配置一個記憶體區塊給堆積heap 。
function AllocMem(Size: Cardinal): Pointer;
ReAllocMem 從堆積釋回一區塊。function ReAllocMem(P: Pointer;CurSize, NewSize:Cardinal): Pointer;
========================================
雜項函數 (Miscellaneous Routines)
Unit: System, SysUtils
========================================
AddExitProc 加入一個程序到執行時期程式庫的出囗程序列中。
procedure AddExitProc(Proc: TProcedure);
Exclude 從一個集合除去一個元素。procedure Exclude(var S: set of T;I:T);
FillChar 以一個字元填入指定個數到一個變數上。
procedure FillChar(var X; Count: Word; value);
Hi 傳回叄數的高位元組。function Hi(X): Byte;
Include 將元素包含到集合內。procedure Include(var S: set of T; I:T);
Lo 傳回叄數的低位元組。function Lo(X): Byte;
Move 從Source 複製Count 個數的位元組到Dest 。
procedure Move(varSource,Dest; Count: Word);
ParamCount 傳回命令列叄數的個數。function ParamCount: Word;
ParamStr 傳回一個指定的命令列叄數。function ParamStr(Index): String;
Random 傳回一個隨機亂數。function Random[ ( Range: Word) ];
Randomize 初值化亂數產生器。procedure Randomize;
SizeOf 傳回叄數所佔位元組數。function SizeOf(X): Word;
Swap 將叄數的高位元組和低位元組交換。function Swap(X);
TypeOf 傳回指向物件型態的虛擬方法表的指標。function TypeOf(X) : Pointer
UpCase 將字元轉爲大寫。function UpCase(Ch: Char):Char;
========================================
次序函數 (Ordinal Routines)
Unit: System
========================================
Dec 遞減一個變數。procedure Dec(var X[ ; N:Longint]);
Inc 遞增一個變數procedure Inc(var X[ ; N:Longint ] );
Odd 判別式否爲奇數。function Odd(X: Longint):Boolean;
Pred 傳回叄數的前任者。function Pred(X);
Succ 傳回叄數的後繼者。function Succ(X);
========================================
指標和位址函數 (Pointer and Address Routines)
Unit: System
========================================
addr 傳回指定物件的位址。function Addr(X): pointer;
Assigned 判斷是否一個函數或程序是nil function Assigned(var P):Boolean;
CSeg 傳回CS 程式段暫存器的內容。function CSeg: Word;
DSeg 傳回DS 資料段暫存器的內容。function DSegt: Word;
Ofs 傳回叄數的偏移位址。function Ofs(X): Word;
Ptr 將所指定的節段及偏移位址組合到一個指標。function Ptr(Seg, Ofs: Word):Pointer;
Seg 傳回叄數的節段位址。function Seg(X): Word;
SPtr 傳回SP 堆疊存器的內容。function SPtr: Word;
SSeg 傳回SS 堆疊段暫存器的內容。function SSeg: Word;
========================================
字串格式函數 (String-formatting Routines)
Unit: SysUtils
========================================
FmtStr 將所列叄數依照Format 的格式組合到Result 字串傳回。
procedure FmtStr(var Resut: string; const Format:string;const Args: array of const);
Format 將所列叄數依照Format 的格式組合到Pascal 格式字串傳回。
fonction Format(const Format: string;const Args:array of const): string;
FormatBuf 格式化所列的叄數。
FormatBuf(var Buffer;BufLen: Cardinal;const Format;FmtLen: Cardinal;const Args: array of string ): Cardinal;
function FormatBuf(var Buffer; BufLen: Word;const Format; FmtLen:Word;Const Args: array of const):Word;
StrFmt 格式化所列的叄數。
function StrFmt(Buffer, Format: PChar;const Args: array of const):PChar;
SysUtils
StrLFmt 格式化所列叄數,並將結果指向Buffer 指標。
function StrLFmt(Buffer: PChar; MxLen: Word;Format: PChar;const Args: array of const):PChar;
SysUtils
========================================
字串處理函數(String-handling Routines :Pascal-style)
Unit: SystUtils
========================================
AnsiCompareStr 比較兩個字串。function AnsiCompareStr(const S1, S2: string):Integer;
SysUtils
var
S: string;
mas: array[0..99] of string;
i, j: integer;
begin
...
for i:=1 to 98 do
for j:=i+1 to 99 do
if AnsiCompareStr( mas[i], mas[j] ) >0 then
begin
S:= mas[i]; mas[i]:= mas[j]; mas[j]:= S;
end;
end;
var
S1,S2: string;
I: Integer;
begin
S1:= '? ???? ???????? ??????';
S2:= '? ???? ???????? ??????';
I:= CompareStr(S1, S2); { I > 0, ?.?. S1 > S2 }
if I<>0 then
MessageDlg( '?????? ????????!', mtWarning, [mbOK],0);
end;
AnsiCompareText 比較兩個字串且無大小寫區別。
AnsiCompareText ( const S1, S2: string ): Integer;
SysUtils
AnsiCompareStr('a', 'A') <0
CompareStr('a', 'A') >0
function AnsiCompareText(const S1, S2: string):Integer;
AnsiLowerCase 將字串內容轉爲小寫。function AnsiLowerCase(const S: string): string;
SysUtils
var
S: string;
begin
S:= 'MyFile.TXT';
S:= AnsiLowerCase(S); // S := 'myfile.txt'
MessageDlg(S, mtInformation, [mbOk], 0);
end;
AnsiUpperCase 將字串內容轉爲大寫。function AnsiUpperCase(const S: string): string;
SysUtils
var
S: string;
begin
S:= 'c:/windows';
S:= AnsiUpperCase (S); { S := 'C:/WINDOWS' }
MessageDlg(S, mtInformation, [mbOk], 0);
end;
AppendStr 將所給字串連接到Dest 字串後面。procedure AppendStr(var Dest: string; const S:string);
AssignStr 配置記憶體空間給字串。procedure AppendStr(var P: PString; const S:String);
CompareStr 比較兩個字串。function CompareStr(const S1,S2: string):Integer;
CompareText 比較兩個字串且無大小寫區別。function CompareText(const S1, S2: String):Integer;
Concat 連結所列字串。function Concat(s1 [, s2,… , sn]: String):String;
Copy 傳回字串的部份字串內容。function Copy(S: String; Index, Count:Integer): String;
Delete 刪除所給字串內的子字串。procedure Delete(var S: String; Index,Count:Integer);
DisposeStr 釋回字串佔用的空間。procedure DisposeStr(P: PString);
FmtLoadStr 從程式的資源字串表中載入一個字串。
FmtLoadStr(Ident: Integer;const Args: array of string ): string;
SysUtils
function FmtLoadStr(Ident: Word;const Args: array of const): string;
Insert 在一個字串內插入一個子字串
procedure Insert(Source: String; var S: String;Index: Integer);
Insert (Source: string;var S: string;Index: Integer );
System
var
S: string;
begin
S:= '??????? ?????? ??????????.';
Insert( '!', S, 8); { S := '???????! ?????? ??????????.'}
MessageDlg( S, mtWarning, [mbOK],0);
end;
IntToHex 將一個整數轉爲十六進位。
function IntToHex(Value: Longint; Digits:Integer): string;
IntToStr 將數字轉成字中格式。function IntToStr(Value: Longint): string;
IsValidIdent 判別字串內容是否爲正確的識別字。function IsValidIdent(const Ident: string):Boolean;
Length 傳回字串的長度。function Length(S: String): Integer;
LoadStr 從應用程式的可執行檔中載入一個字串資源。
function LoadStr(Ident: Word): string;
SysUtils
LowerCase 將字串轉成小寫。function LowerCase(const S: string): string;
NewStr 從堆積配置一個字串空間。function NewStr(const S: string): PString;
Pos 傳回子字串在字串中的位置。function Pos(Substr: String; S: String):
Str 將數值轉爲字串。procedure Str(X [: Width [: Decimals ]];var S);
StrToInt 將字串轉爲整數值。function StrToInt(const S: string): Longint;
StrToIntDef 將字串轉整數值或預設值。function StrToIntDef(const S: string; Default:Longint): Longint;
Uppercase 將字串轉成大寫。function UpperCase(const S: string): string;
SysUtils
var
S: string;
begin
S:= UpperCase( '???????? Intel'); { S := '???????? INTEL'}
end;
val 將字串內容轉爲數值描述。procedure Val(S; var V; var Code: Integer);
System { $R+ } { $R- }
var
I, Code: Integer;
begin
Val( Edit1.Text, I, Code); { ??????????????? ????? ????????? ? ???? Edit1.Text ? ???????? ????? }
if Code<>0 then { ????????? ??????? ?????? ? ????????? ?????
MessageDlg( '?????? ???????? ? ???????: '+ IntToStr(Code), mtWarning,[mbOk], 0)
else { ??????? ??????? ?????}
Canvas.TextOut( 20, 20, IntToStr(Sqr(I)));
end;
========================================
字串處理函數 (String-handling Routines : Null-terminated)
Unit: SysUtils
========================================
StrAlloc 配置一個最大長度爲Size-1 的緩衝區給null 結尾字串
function StrAlloc(Size: Word): PChar;
StrBufSize 傳回由StrAlloc 配置的字串緩衝區內可以儲存的最大字元數。
StrBufSize( S: PChar ): Cardinal;
SysUtils
function StrBufSize(Str: PChar): Wrd;StrCat 連結兩個字串並傳回該字串。
function StrCat(Dest, Source: PCar): PChar;
StrComp 比照兩個字串。function StrComp(Str1, Str2 : Pchar): Integer;
StrCopy 拷貝Source 字串到Dest 上。function StrCopy(Dest, Source: PChar): PChar
StrDispose 釋回一個字串空間。function StrDispose(Str:PChar);
StrCopy 拷貝Source 字串到Dest 上並傳回指向該字串結尾的指標。
function StrECopy(Dest, Surce: Pchar): Pchar;
StrEnd 傳回一指標指向字串的結尾function StrEnd(Str: Pchar): Pchar;
StrLCat 將Source 字串連結到Dest 字串後,並傳回連結的字串。
function StrLCat(Dest, Source:PCar; MaxLen: Word): PChar;
StrIComp 比較兩個字串具無大小寫區別
function StrIComp(Str1, Str2:Pchar): Integer;
StrLComp 比較兩個字串到所指定的最大長度
function StrLComp(Str1, Str2:Pchar; MaxLen: Word): Integer;
StrLCopy 從一字串拷貝指定字元數到另一字串
Function StrLCopy(Dest,Source:PChar;MaxLen: Cardinal): PChar;
StrLen 傳回字串的長度。function StrLen(Str: PChar):Cardinal;
StrLIComp 比較兩個字串到所指定的最大長度具無大小寫區別。
function StrLIComp(Str1, Str2:PChar; MaxLen: Word):Integer;
StrLower 將字串轉成小寫。
function StrLower(Str: PChar):PChar;
StrMove 拷貝Count 字元數,從Source 到Dest字串。
function StrMove(Dest, Source:PChar; Count: Cardinal): PChar
StrNew 從堆積配置一個字串。function StrNew(Str: PChar):PChar;
StrPas 將null 結尾字中轉成一個Pascal 格式字串。
function StrPas(Str: Pchar):String;
StrPCopy 拷貝一個Pascal 格式字串到一個null結尾字串。
Function StrPCopy(Dest:PChar;Source: String): PChar;
StrPLCopy 拷貝MaxLen 所指字元數,從Pascal格式字串到null 結尾字串。
Function StrPLCopy(Dest:Pchar;cost Source: string;MaxLen: Word): PChar;
StrPos 傳回一指標指向在Str1 內最先出現 Str2 字串的位置。
function StrPos(Str1, Str2: Pchar): Pchar;
StrScan 傳回一指標指向在Str 字串中第一個出現chr 字元的位置。
function StrScan(Str: PChar; Chr: Char): PChar;
StrRScan 傳回一指標指向在Str 子串中最後出現chr 字元的位置。
function StrRScan(Str: Pchar; Chr: Char): PChar;
StrUpper 將字串轉成大寫。function StrUpper(Str: PChar):PChar;
========================================
文字檔案函數 (Text-file Routines)
Unit: System
========================================
Append 開啓一個存在的檔案供增加。procedure Append(var f: Text);
Eoln 判別一文字檔是否在行尾。function Eoln [(var F: Text) ]:Boolean;
Flush 清除文字輸出檔的緩衝區。procedure Flush(var F: Text);
Read 從檔案讀入資料到所列變數。Typed files:
Procedure Read(F , V1[, V2,… ,Vn ] );
Text files:
procedure Read( [ var F: Text; ] V1 [,V2,… ,Vn]);
Readln 從檔案讀入資料到所列變數並跳至下一行。
procedure Readln( [ var F:Text; ]V1 [, V2,… ,Vn ]);
SeekEof 判別是否已到檔尾。function SeekEof [ ( var F:Text) ]: Boolean;
SeekEoln 判別一檔案是否在行尾。function SeekEoln [(var F: Text) ]: Boolean;
SetTextBuf 指定一個I/O 緩衝區給一文字檔。procedure SetTextBuf(var F: Text; var Buf [ ; Size:Word ] );
Write 將變數內的資料寫到檔案。Text files:
procedure Write( [ var F:Text; ] P1 [,P2,… ,Pn ] );
Typed files:
procedure Write(F, V1[V2,… Vn]);
writeln 執行Write 程序並輸出一個跳行到檔案。
procedure Writeln([ var F: Text; ] P1 [, P2,… ,Pn ] );
========================================
轉換函數(Transfer Routines)
Unit: System
========================================
Chr 傳回ASCII 碼所對應的字元。function Chr(X: Byte): Char;
Delphi 源碼任務 ( http://home.kimo.com.tw/bruce0211/ ) 打字整理15
High 傳回叄數在範圍內的最高值。function High(X);
Low 傳回叄數在範圍內的最低值。function Low(X);
Ord 傳回一個有序型態所對應的順序值。function Ord(X): Longint;
Round 將一個實數值四捨五入而傳回整數值。function Round(X: Real):Longint;
Trunc 將一個實數值去尾而傳回整數值。function Trunc(X: Real):Longint;
========================================
未定型態檔案函數(Untyped-file Routines)
Unit: System
========================================
BlockRead 從檔案讀入一個或數個記錄到Buf 變數。
procedure BlockRead(var F: File; var Buf;Count: Word [; var Result:Word]);
BlockWrite 從一變數寫入一個或數個記錄。
procedure BlockWrite(var f: File; var Buf;Count: Word [; var Result:Word]);
======================================================
WinAPI 控件與消息函數
----------------
AdjustWindowRect
AdjustWindowRectEx
給定一種窗囗樣式,計算獲得目標客戶區矩形所需的窗囗大小
======================================================
VB聲明
Declare Function AdjustWindowRect Lib "user32" Alias "AdjustWindowRect" (lpRect As RECT, ByVal dwStyle As Long, ByVal bMenu As Long) As Long
Declare Function AdjustWindowRectEx Lib "user32" Alias "AdjustWindowRectEx" (lpRect As RECT, ByVal dsStyle As Long, ByVal bMenu As Long, ByVal dwEsStyle As Long) As Long
說明
在給定一種窗囗樣式的前提下,計算獲得目標客戶區矩形所需的窗囗大小
返回值
Long,如執行成功,則返回非零值;如失敗,返回零值。會設置GetLastError
叄數表
叄數 類型及說明
lpRect RECT,最初包含要求的客戶區。由函數設爲目標窗囗矩形大小
dwStyle Long,窗囗樣式
bMenu Long,如窗囗有菜單,則設爲TRUE(非零)
dwEsStyle Long,擴展窗囗樣式(只適用於AdjustWindowRectEx)
註解
在調用本函數前,先用GetWindowLong取得一個窗體的樣式。如菜單佔用兩行以上的空間,則函數不能正確計算大小。如程序使用了多行標題,則應使用GetSystemMetrics
======================================================
AnyPopup
判斷屏幕上是否存在任何彈出式窗囗
-----------------------------------------
VB聲明
Declare Function AnyPopup Lib "user32" Alias "AnyPopup" () As Long
說明
判斷屏幕上是否存在任何彈出式窗囗
返回值
Long,如存在彈出式菜單,則返回TRUE(非零)
註解
對該函數來說,彈出式菜單包含所有可見的包容頂級窗囗,無論彈出式還是重疊窗囗
=====================================================
ArrangeIconicWindows 排列一個父窗囗的最小化子窗囗
VB聲明
Declare Function ArrangeIconicWindows Lib "user32" Alias "ArrangeIconicWindows" (ByVal hwnd As Long) As Long
說明
排列一個父窗囗的最小化子窗囗(在vb裏使用:用於在桌面排列圖標,用GetDesktopWindow
函數獲得桌面窗囗的一個句柄)
返回值
Long,圖標行的高度;如失敗,則返回零。會設置GetLastError
叄數表
叄數 類型及說明
hwnd Long,父窗囗的句柄
註解
也可將該函數用於包含了圖標化子窗囗的的定製控件
=======================================================
AttachThreadInput 連接線程輸入函數
BeginDeferWindowPos 啓動構建一系列新窗囗位置的過程
BringWindowToTop 將指定的窗囗帶至窗囗列表頂部
CascadeWindows 以層疊方式排列窗囗
ChildWindowFromPoint 返回父窗囗中包含了指定點的第一個子窗囗的句柄
ClientToScreen 判斷窗囗內以客戶區座標表示的一個點的屏幕座標
CloseWindow 最小化指定的窗囗
CopyRect 矩形內容複製
DeferWindowPos 該函數爲特定的窗囗指定一個新窗囗位置
DestroyWindow 清除指定的窗囗以及它的所有子窗囗
DrawAnimatedRects 描繪一系列動態矩形
EnableWindow 指定的窗囗裏允許或禁止所有鼠標及鍵盤輸入
EndDeferWindowPos 同時更新DeferWindowPos調用時指定的所有窗囗的位置及狀態
EnumChildWindows 爲指定的父窗囗枚舉子窗囗
EnumThreadWindows 枚舉與指定任務相關的窗囗
EnumWindows 枚舉窗囗列表中的所有父窗囗
EqualRect 判斷兩個矩形結構是否相同
FindWindow 尋找窗囗列表中第一個符合指定條件的頂級窗囗
FindWindowEx 在窗囗列表中尋找與指定條件相符的第一個子窗囗
=============================
FlashWindow 閃爍顯示指定窗囗
-----------------------------
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2.Show;
Form1.BringToFront;
Timer1.Interval:=GetCaretBlinkTime;
Timer1.Enabled:=Not Timer1.Enabled;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
FlashWindow(Form2.Handle,TRUE);
end;
==============================
GetActiveWindow 獲得活動窗囗的句柄
GetCapture 獲得一個窗囗的句柄,這個窗囗位於當前輸入線程,且擁有鼠標捕獲(鼠標活動由它接收)
GetClassInfo 取得WNDCLASS結構(或WNDCLASSEX結構)的一個副本,結構中包含了與指定類有關的信息
GetClassLong 取得窗囗類的一個Long變量條目
GetClassName 爲指定的窗囗取得類名
GetClassWord 爲窗囗類取得一個整數變量
GetClientRect 返回指定窗囗客戶區矩形的大小
GetDesktopWindow 獲得代表整個屏幕的一個窗囗(桌面窗囗)句柄
GetFocus 獲得擁有輸入焦點的窗囗的句柄
GetForegroundWindow 獲得前臺窗囗的句柄
GetLastActivePopup 獲得在一個給定父窗囗中最近激活過的彈出式窗囗的句柄
GetLastError 針對之前調用的api函數,用這個函數取得擴展錯誤信息
GetParent 判斷指定窗囗的父窗囗
GetTopWindow 搜索內部窗囗列表,尋找隸屬於指定窗囗的頭一個窗囗的句柄
GetUpdateRect 獲得一個矩形,它描敘了指定窗囗中需要更新的那一部分
=================================================
GetWindow
獲得一個窗囗的句柄,該窗囗與某源窗囗有特定的關係
------------------------------------------------
procedure TForm1.Timer1Timer(Sender: TObject);
var
s:array [0..29999]of char;
H:integer;
begin
h:=Getwindow(handle,GW_OWNER );
//Getwindow取一個窗囗的句柄,該窗囗與某源窗囗有特定的關係
getwindowtext(H,s,300);
//getwindowtext取一個窗體標題(caption)文字,或控件內容
Edit1.text:=inttostr(H);
Label1.caption := S;
end;
================================================
GetWindowContextHelpId 取得與窗囗關聯在一起的幫助場景ID
GetWindowLong 從指定窗囗的結構中取得信息
GetWindowPlacement 獲得指定窗囗的狀態及位置信息
GetWindowRect 獲得整個窗囗的範圍矩形,窗囗的邊框、標題欄、滾動條及菜單等都在這個矩形內
================================================
GetWindowText
取得一個窗體的標題(caption)文字,或者一個控件的內容
--------------------------
procedure TForm1.Timer1Timer(Sender: TObject);
var
s:array [0..29999]of char;
H:integer;
begin
h:=Getwindow(handle,GW_OWNER );
//Getwindow取一個窗囗的句柄,該窗囗與某源窗囗有特定的關係
getwindowtext(H,s,300);
//getwindowtext取一個窗體標題(caption)文字,或控件內容
Edit1.text:=inttostr(H);
Label1.caption := S;
end;
============================
GetWindowTextLength 調查窗囗標題文字或控件內容的長短
GetWindowWord 獲得指定窗囗結構的信息
InflateRect 增大或減小一個矩形的大小
IntersectRect 這個函數在lpDestRect裏載入一個矩形,它是lpSrc1Rect與lpSrc2Rect兩個矩形的交集
InvalidateRect 屏蔽一個窗囗客戶區的全部或部分區域
IsChild 判斷一個窗囗是否爲另一窗囗的子或隸屬窗囗
IsIconic 判斷窗囗是否已最小化
IsRectEmpty 判斷一個矩形是否爲空
IsWindow 判斷一個窗囗句柄是否有效
IsWindowEnabled 判斷窗囗是否處於活動狀態
IsWindowUnicode 判斷一個窗囗是否爲Unicode窗囗。這意味着窗囗爲所有基於文本的消息都接收Unicode文字
IsWindowVisible 判斷窗囗是否可見
IsZoomed 判斷窗囗是否最大化
LockWindowUpdate 鎖定指定窗囗,禁止它更新
MapWindowPoints 將一個窗囗客戶區座標的點轉換到另一窗囗的客戶區座標系統
MoveWindow 改變指定窗囗的位置和大小
OffsetRect 通過應用一個指定的偏移,從而讓矩形移動起來
OpenIcon 恢復一個最小化的程序,並將其激活
PtInRect 判斷指定的點是否位於矩形內部
RedrawWindow 重畫全部或部分窗囗
ReleaseCapture 爲當前的應用程序釋放鼠標捕獲
ScreenToClient 判斷屏幕上一個指定點的客戶區座標
ScrollWindow 滾動窗囗客戶區的全部或一部分
ScrollWindowEx 根據附加的選項,滾動窗囗客戶區的全部或部分
SetActiveWindow 激活指定的窗囗
SetCapture 將鼠標捕獲設置到指定的窗囗
SetClassLong 爲窗囗類設置一個Long變量條目
SetClassWord 爲窗囗類設置一個條目
SetFocusAPI 將輸入焦點設到指定的窗囗。如有必要,會激活窗囗
SetForegroundWindow 將窗囗設爲系統的前臺窗囗
SetParent 指定一個窗囗的新父
SetRect 設置指定矩形的內容
SetRectEmpty 將矩形設爲一個空矩形
SetWindowContextHelpId 爲指定的窗囗設置幫助場景(上下文)ID
SetWindowLong 在窗囗結構中爲指定的窗囗設置信息
SetWindowPlacement 設置窗囗狀態和位置信息
SetWindowPos 爲窗囗指定一個新位置和狀態
SetWindowText 設置窗囗的標題文字或控件的內容
SetWindowWord 在窗囗結構中爲指定的窗囗設置信息
ShowOwnedPopups 顯示或隱藏由指定窗囗所有的全部彈出式窗囗
ShowWindow 控制窗囗的可見性
ShowWindowAsync 與ShowWindow相似
SubtractRect 裝載矩形lprcDst,它是在矩形lprcSrc1中減去lprcSrc2得到的結果
TileWindows 以平鋪順序排列窗囗
UnionRect 裝載一個lpDestRect目標矩形,它是lpSrc1Rect和lpSrc2Rect聯合起來的結果
UpdateWindow 強制立即更新窗囗
ValidateRect 校驗窗囗的全部或部分客戶區
WindowFromPoint 返回包含了指定點的窗囗的句柄。忽略屏蔽、隱藏以及透明窗囗
======================================================
硬件與系統函數
----------------
ActivateKeyboardLayout
激活一個新的鍵盤佈局。鍵盤佈局定義了按鍵在一種物理性鍵盤上的位置與含義
-----------------------------
VB聲明
Declare Function ActivateKeyboardLayout Lib "user32" Alias "ActivateKeyboardLayout" (ByVal HKL As Long, ByVal flags As Long) As Long
說明
激活一個新的鍵盤佈局。鍵盤佈局定義了按鍵在一種物理性鍵盤上的位置與含義
返回值
Long,如執行成功,返回前一個鍵盤佈局的句柄;零表示失敗。會設置GetLastError
叄數表
叄數 類型及說明
HKL Long,指定一個鍵盤佈局的句柄。這個佈局是隨同LoadKeyboardLayout 或 GetKeyboardLayoutList函數載入的。也可用HKL_NEXT常數激活下一個已裝載佈局;或用
HKL_PREV載入前一個佈局
flags Long,將指定的鍵盤移至內部鍵盤佈局列表的起始處
=====================================================
Beep 用於生成簡單的聲音
CharToOem 將一個字串從ANSI字符集轉換到OEM字符集
ClipCursor 將指針限制到指定區域
ConvertDefaultLocale 將一個特殊的地方標識符轉換成真實的地方ID
CreateCaret 根據指定的信息創建一個插入符(光標),並將它選定爲指定窗囗的默認插入符
DestroyCaret 清除(破壞)一個插入符
EnumCalendarInfo 枚舉在指定“地方”環境中可用的日曆信息
EnumDateFormats 列舉指定的“當地”設置中可用的長、短日期格式
EnumSystemCodePages 枚舉系統中已安裝或支持的代碼頁
EnumSystemLocales 枚舉系統已經安裝或提供支持的“地方”設置
EnumTimeFormats 枚舉一個指定的地方適用的時間格式
ExitWindowsEx 退出windows,並用特定的選項重新啓動
ExpandEnvironmentStrings 擴充環境字串
FreeEnvironmentStrings 翻譯指定的環境字串塊
GetACP 判斷目前正在生效的ANSI代碼頁
GetAsyncKeyState 判斷函數調用時指定虛擬鍵的狀態
GetCaretBlinkTime 判斷插入符光標的閃爍頻率
GetCaretPos 判斷插入符的當前位置
GetClipCursor 取得一個矩形,用於描述目前爲鼠標指針規定的剪切區域
GetCommandLine 獲得指向當前命令行緩衝區的一個指針
GetComputerName 取得這臺計算機的名稱
GetCPInfo 取得與指定代碼頁有關的信息
GetCurrencyFormat 針對指定的“地方”設置,根據貨幣格式格式化一個數字
GetCursor 獲取目前選擇的鼠標指針的句柄
GetCursorPos 獲取鼠標指針的當前位置
GetDateFormat 針對指定的“當地”格式,對一個系統日期進行格式化
GetDoubleClickTime 判斷連續兩次鼠標單擊之間會被處理成雙擊事件的間隔時間
GetEnvironmentStrings 爲包含了當前環境字串設置的一個內存塊分配和返回一個句柄
GetEnvironmentVariable 取得一個環境變量的值
GetInputState 判斷是否存在任何待決(等待處理)的鼠標或鍵盤事件
GetKBCodePage 由GetOEMCP取代,兩者功能完全相同
GetKeyboardLayout 取得一個句柄,描述指定應用程序的鍵盤佈局
GetKeyboardLayoutList 獲得系統適用的所有鍵盤佈局的一個列表
GetKeyboardLayoutName 取得當前活動鍵盤佈局的名稱
GetKeyboardState 取得鍵盤上每個虛擬鍵當前的狀態
GetKeyboardType 瞭解與正在使用的鍵盤有關的信息
GetKeyNameText 在給出掃描碼的前提下,判斷鍵名
GetKeyState 針對已處理過的按鍵,在最近一次輸入信息時,判斷指定虛擬鍵的狀態
GetLastError 針對之前調用的api函數,用這個函數取得擴展錯誤信息
GetLocaleInfo 取得與指定“地方”有關的信息
GetLocalTime 取得本地日期和時間
GetNumberFormat 針對指定的“地方”,按特定的格式格式化一個數字
GetOEMCP 判斷在OEM和ANSI字符集間轉換的windows代碼頁
GetQueueStatus 判斷應用程序消息隊列中待決(等待處理)的消息類型
GetSysColor 判斷指定windows顯示對像的顏色
GetSystemDefaultLangID 取得系統的默認語言ID
GetSystemDefaultLCID 取得當前的默認系統“地方”
GetSystemInfo 取得與底層硬件平臺有關的信息
GetSystemMetrics 返回與windows環境有關的信息
GetSystemPowerStatus 獲得與當前系統電源狀態有關的信息
GetSystemTime 取得當前系統時間,這個時間採用的是“協同世界時間”(即UTC,也叫做GMT)格式
GetSystemTimeAdjustment 使內部系統時鐘與一個外部的時鐘信號源同步
GetThreadLocale 取得當前線程的地方ID
GetTickCount 用於獲取自windows啓動以來經歷的時間長度(毫秒)
GetTimeFormat 針對當前指定的“地方”,按特定的格式格式化一個系統時間
GetTimeZoneInformation 取得與系統時區設置有關的信息
GetUserDefaultLangID 爲當前用戶取得默認語言ID
GetUserDefaultLCID 取得當前用戶的默認“地方”設置
GetUserName 取得當前用戶的名字
GetVersion 判斷當前運行的Windows和DOS版本
GetVersionEx 取得與平臺和操作系統有關的版本信息
HideCaret 在指定的窗囗隱藏插入符(光標)
IsValidCodePage 判斷一個代碼頁是否有效
IsValidLocale 判斷地方標識符是否有效
keybd_event 這個函數模擬了鍵盤行動
LoadKeyboardLayout 載入一個鍵盤佈局
MapVirtualKey 根據指定的映射類型,執行不同的掃描碼和字符轉換
MapVirtualKeyEx 根據指定的映射類型,執行不同的掃描碼和字符轉換
MessageBeep 播放一個系統聲音。系統聲音的分配方案是在控制面板裏決定的
mouse_event 模擬一次鼠標事件
OemKeyScan 判斷OEM字符集中的一個ASCII字符的掃描碼和Shift鍵狀態
OemToChar 將OEM字符集的一個字串轉換到ANSI字符集
SetCaretBlinkTime 指定插入符(光標)的閃爍頻率
SetCaretPos 指定插入符的位置
SetComputerName 設置新的計算機名
SetCursor 將指定的鼠標指針設爲當前指針
SetCursorPos 設置指針的位置
SetDoubleClickTime 設置連續兩次鼠標單擊之間能使系統認爲是雙擊事件的間隔時間
SetEnvironmentVariable 將一個環境變量設爲指定的值
SetKeyboardState 設置每個虛擬鍵當前在鍵盤上的狀態
SetLocaleInfo 改變用戶“地方”設置信息
SetLocalTime 設置當前地方時間
SetSysColors 設置指定窗囗顯示對像的顏色
SetSystemCursor 改變任何一個標準系統指針
SetSystemTime 設置當前系統時間
SetSystemTimeAdjustment 定時添加一個校準值使內部系統時鐘與一個外部的時鐘信號源同步
SetThreadLocale 爲當前線程設置地方
SetTimeZoneInformation 設置系統時區信息
ShowCaret 在指定的窗囗裏顯示插入符(光標)
ShowCursor 控制鼠標指針的可視性
SwapMouseButton 決定是否互換鼠標左右鍵的功能
SystemParametersInfo 獲取和設置數量衆多的windows系統叄數
SystemTimeToTzSpecificLocalTime 將系統時間轉換成地方時間
ToAscii 根據當前的掃描碼和鍵盤信息,將一個虛擬鍵轉換成ASCII字符
ToUnicode 根據當前的掃描碼和鍵盤信息,將一個虛擬鍵轉換成Unicode字符
UnloadKeyboardLayout 卸載指定的鍵盤佈局
VkKeyScan 針對Windows字符集中一個ASCII字符,判斷虛擬鍵碼和Shift鍵的狀態
完
======================================================
菜單函數
---------------
AppendMenu
在指定的菜單裏添加一個菜單項
----------------------------------------
VB聲明
Declare Function AppendMenu Lib "user32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, ByVal lpNewItem As Any) As Long
說明
在指定的菜單裏添加一個菜單項
返回值
Long,非零表示成功,零表示失敗。會設置GetLastError
叄數表
叄數 類型及說明
hMenu Long,菜單句柄
wFlags Long,叄考ModifyMenu函數中的菜單常數標誌定義表,其中列出了允許使用的所有常數
wIDNewItem Long,指定菜單條目的新命令ID。如果在wFlags叄數中指定了MF_POPUP字段,那麼這應該是指向一個彈出式菜單的句柄
lpNewItem String(相應的vb聲明見註解),如果在wFlags叄數中指定了MF_STRING標誌,這就代表在菜單中設置的字串。如設置了MF_BITMAP標誌,這就代表一個Long型變量,其中包含了一個位圖句柄。如設置了MF_OWNERDRAW,這個值就會包括在
DRAWITEMSTRUCT和MEASUREITEMSTRUCT結構中,在條目需要重畫的時候由windows
發送出去
註解
Declare Function AppendMenu& Lib "user32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, ByVal lpNewItem As String)
=========================================
CheckMenuItem 複選或撤消複選指定的菜單條目
CheckMenuRadioItem 指定一個菜單條目被複選成“單選”項目
CreateMenu 創建新菜單
CreatePopupMenu 創建一個空的彈出式菜單
DeleteMenu 刪除指定的菜單條目
DestroyMenu 刪除指定的菜單
DrawMenuBar 爲指定的窗囗重畫菜單
EnableMenuItem 允許或禁止指定的菜單條目
GetMenu 取得窗囗中一個菜單的句柄
GetMenuCheckMarkDimensions 返回一個菜單複選符的大小
GetMenuContextHelpId 取得一個菜單的幫助場景ID
GetMenuDefaultItem 判斷菜單中的哪個條目是默認條目
GetMenuItemCount 返回菜單中條目(菜單項)的數量
GetMenuItemID 返回位於菜單中指定位置處的條目的菜單ID
GetMenuItemInfo 取得(接收)與一個菜單條目有關的特定信息
GetMenuItemRect 在一個矩形中裝載指定菜單條目的屏幕座標信息
GetMenuState 取得與指定菜單條目狀態有關的信息
GetMenuString 取得指定菜單條目的字串
GetSubMenu 取得一個彈出式菜單的句柄,它位於菜單中指定的位置
GetSystemMenu 取得指定窗囗的系統菜單的句柄
HiliteMenuItem 控制頂級菜單條目的加亮顯示狀態
InsertMenu 在菜單的指定位置處插入一個菜單條目,並根據需要將其他條目向下移動
InsertMenuItem 插入一個新菜單條目
IsMenu 判斷指定的句柄是否爲一個菜單的句柄
LoadMenu 從指定的模塊或應用程序實例中載入一個菜單
LoadMenuIndirect 載入一個菜單
MenuItemFromPoint 判斷哪個菜單條目包含了屏幕上一個指定的點
ModifyMenu 改變菜單條目
RemoveMenu 刪除指定的菜單條目
SetMenu 設置窗囗菜單
SetMenuContextHelpId 設置一個菜單的幫助場景ID
SetMenuDefaultItem 將一個菜單條目設爲默認條目
SetMenuItemBitmaps 設置一幅特定位圖,令其在指定的菜單條目中使用,代替標準的複選符號( )
SetMenuItemInfo 爲一個菜單條目設置指定的信息
TrackPopupMenu 在屏幕的任意地方顯示一個彈出式菜單
TrackPopupMenuEx 與TrackPopupMenu相似,只是它提供了額外的功能
完
以下是幾個關於菜單函數的類型定義
MENUITEMINFO 這個結構包含了菜單條目的信息
TPMPARAMS 這個結構用於TrackPopupMenuEx函數以支持額外的功能
======================================================
繪圖函數
--------
AbortPath
拋棄選入指定設備場景中的所有路徑。也取消目前正在進行的任何路徑的創建工作
-----------------------------------------------------------------------
VB聲明
Declare Function AbortPath Lib "gdi32" Alias "AbortPath" (ByVal hdc As Long) As Long
說明
拋棄選入指定設備場景中的所有路徑。也取消目前正在進行的任何路徑的創建工作
返回值
Long,非零表示成功,零表示失敗。會設置GetLastError
叄數 類型及說明
hdc Long,設備場景
======================================
AngleArc 用一個連接弧畫一條線
-----------------------------
VB聲明
Declare Function AngleArc Lib "gdi32" Alias "AngleArc" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal dwRadius As Long, ByVal eStartAngle As Double, ByVal eSweepAngle As Double) As Long
說明
用一個連接弧畫一條線,叄考註解
返回值
Long,非零表示成功,零表示失敗
叄數表
叄數 類型及說明
hdc Long,要在其中作圖的設備場景
x,y Long,對弧進行描述的一個圓的中心點座標
dwRadius Long,圓的半徑
eStartAngle Double,線同圓連接時的角度(以度數爲單位)
eSweepAngle Double,弧在圓上佔據的範圍(以度數爲單位)
註解
注意eStartAngle和eSweepAngle叄數是以度數爲單位指定的,而且應該是單精度數(Single
)而不是雙精度。相應的函數聲明爲:Declare Function AngleArc& Lib "gdi32" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal dwRadius As Long, ByVal eStartAngle As Single, ByVal eSweepAngle As Single)。
我的理解:本文開頭的函數聲明覆制於vb的api文本查看器,此處的聲明來自於我的叄考資料,也不知誰對誰錯。叄數表的說明,按vb的api文本查看器中複製來的聲明中的數據類型。請使用者注意
=====================================================
Arc 畫一個圓弧
BeginPath 啓動一個路徑分支
CancelDC 取消另一個線程裏的長時間繪圖操作
Chord 畫一個弦
CloseEnhMetaFile 關閉指定的增強型圖元文件設備場景,並將新建的圖元文件返回一個句柄
CloseFigure 描繪到一個路徑時,關閉當前打開的圖形
CloseMetaFile 關閉指定的圖元文件設備場景,並向新建的圖元文件返回一個句柄
CopyEnhMetaFile 製作指定增強型圖元文件的一個副本(拷貝)
CopyMetaFile 製作指定(標準)圖元文件的一個副本
CreateBrushIndirect 在一個LOGBRUSH數據結構的基礎上創建一個刷子
CreateDIBPatternBrush 用一幅與設備無關的位圖創建一個刷子,以便指定刷子樣式(圖案)
CreateEnhMetaFile 創建一個增強型的圖元文件設備場景
CreateHatchBrush 創建帶有陰影圖案的一個刷子
CreateMetaFile 創建一個圖元文件設備場景
CreatePatternBrush 用指定了刷子圖案的一幅位圖創建一個刷子
CreatePen 用指定的樣式、寬度和顏色創建一個畫筆
CreatePenIndirect 根據指定的LOGPEN結構創建一個畫筆
CreateSolidBrush 用純色創建一個刷子
DeleteEnhMetaFile 刪除指定的增強型圖元文件
DeleteMetaFile 刪除指定的圖元文件
DeleteObject 刪除GDI對像,對像使用的所有系統資源都會被釋放
DrawEdge 用指定的樣式描繪一個矩形的邊框
DrawEscape 換碼(Escape)函數將數據直接發至顯示設備驅動程序
DrawFocusRect 畫一個焦點矩形
DrawFrameControl 描繪一個標準控件
DrawState 爲一幅圖像或繪圖操作應用各式各樣的效果
Ellipse 描繪一個橢圓,由指定的矩形圍繞
EndPath 停止定義一個路徑
EnumEnhMetaFile 針對一個增強型圖元文件,列舉其中單獨的圖元文件記錄
EnumMetaFile 爲一個標準的windows圖元文件枚舉單獨的圖元文件記錄
EnumObjects 枚舉可隨同指定設備場景使用的畫筆和刷子
ExtCreatePen 創建一個擴展畫筆(裝飾或幾何)
ExtFloodFill 在指定的設備場景裏,用當前選擇的刷子填充一個區域
FillPath 關閉路徑中任何打開的圖形,並用當前刷子填充
FillRect 用指定的刷子填充一個矩形
FlattenPath 將一個路徑中的所有曲線都轉換成線段
FloodFill 用當前選定的刷子在指定的設備場景中填充一個區域
FrameRect 用指定的刷子圍繞一個矩形畫一個邊框
GdiComment 爲指定的增強型圖元文件設備場景添加一條註釋信息
GdiFlush 執行任何未決的繪圖操作
GdiGetBatchLimit 判斷有多少個GDI繪圖命令位於隊列中
GdiSetBatchLimit 指定有多少個GDI繪圖命令能夠進入隊列
GetArcDirection 畫圓弧的時候,判斷當前採用的繪圖方向
GetBkColor 取得指定設備場景當前的背景顏色
GetBkMode 針對指定的設備場景,取得當前的背景填充模式
GetBrushOrgEx 判斷指定設備場景中當前選定刷子起點
GetCurrentObject 獲得指定類型的當前選定對像
GetCurrentPositionEx 在指定的設備場景中取得當前的畫筆位置
GetEnhMetaFile 取得磁盤文件中包含的一個增強型圖元文件的圖元文件句柄
GetEnhMetaFileBits 將指定的增強型圖元文件複製到一個內存緩衝區裏
GetEnhMetaFileDescription 返回對一個增強型圖元文件的說明
GetEnhMetaFileHeader 取得增強型圖元文件的圖元文件頭
GetEnhMetaFilePaletteEntries 取得增強型圖元文件的全部或部分調色板
GetMetaFile 取得包含在一個磁盤文件中的圖元文件的圖元文件句柄
GetMetaFileBitsEx 將指定的圖元文件複製到一個內存緩衝區
GetMiterLimit 取得設備場景的斜率限制(Miter)設置
GetNearestColor 根據設備的顯示能力,取得與指定顏色最接近的一種純色
GetObjectAPI 取得對指定對像進行說明的一個結構
GetObjectType 判斷由指定句柄引用的GDI對像的類型
GetPath 取得對當前路徑進行定義的一系列數據
GetPixel 在指定的設備場景中取得一個像素的RGB值
GetPolyFillMode 針對指定的設備場景,獲得多邊形填充模式
GetROP2 針對指定的設備場景,取得當前的繪圖模式
GetStockObject 取得一個固有對像(Stock)
GetSysColorBrush 爲任何一種標準系統顏色取得一個刷子
GetWinMetaFileBits 通過在一個緩衝區中填充用於標準圖元文件的數據,將一個增強型圖元文件轉換成標準windows圖元文件
InvertRect 通過反轉每個像素的值,從而反轉一個設備場景中指定的矩形
LineDDA 枚舉指定線段中的所有點
LineTo 用當前畫筆畫一條線,從當前位置連到一個指定的點
======================================================
StrToInt
StrToInt64
StrToIntDef
StrToInt64Def
IntToStr
StrLen
StrEnd
StrCopy
StrMove
StrECopy
StrLCopy
StrPCopy
StrPLCopy
StrCat
StrLCat
StrComp
StrIComp
StrLComp
StrLIComp
StrScan
StrRScan
StrPos
StrUpper
StrLower
StrPas
StrAlloc
StrBufSize
StrNew
StrDispose