星期四, 10月 02, 2008

自動塞入一萬萬行資料


declare @counter int
set @counter = 0
while @counter <10000begin set @counter = @counter + 1 print 'The counter is ' + cast(@counter as char) insert into log (
logdate,userid,pcid,sourcefile,filesize,filehash,writez,logmemo,domainid,hasfile,filelogtype,domain_name,user_name,full_name,compu
ter_name,location,format_tag,dept_name,host_address,backup_path,exe_name,remote_host,is_blocked,dest_drive,dest_drive_type,self_ex
tract_type,fort_server_id) select top 10000
logdate,userid,pcid,sourcefile,filesize,filehash,writez,logmemo,domainid,hasfile,filelogtype,domain_name,user_name,full_name,compu
ter_name,location,format_tag,dept_name,host_address,backup_path,exe_name,remote_host,is_blocked,dest_drive,dest_drive_type,self_ex
tract_type,fort_server_id from log
end

星期一, 9月 15, 2008

CoreBoot系統改讀其路徑


uses Registry;

Function GetCoreBootValue : string;
var
reg:TRegistry;
skey : string;
begin
Result := '';
reg:=TRegistry.create;
try
reg.RootKey:=HKEY_LOCAL_MACHINE;
skey:='SYSTEM\CurrentControlSet\Services\Coreboot';
if reg.OpenKeyReadOnly(skey) then
begin
if(reg.ValueExists('CorebootEnable')) then
begin
if (reg.ReadInteger('CorebootEnable')=1) and (reg.ValueExists('CorebootDrive')) then
Result:=Trim(reg.ReadString('CorebootDrive'));
end;
reg.closekey;
end;
finally
reg.free;
end;
end;

星期四, 9月 11, 2008

將秒轉成天、小時、分、秒


procedure TForm1.FormCreate(Sender: TObject);
var
DateTime:TDateTime;
ASec:integer;
Hour,Min,Sec,MSec:word;
begin
ASec:=801;
//Day:=ASec div 86400;//一天為86400秒
DateTime:=IncSecond(DateTime,ASec);//轉成TDateTime型態
DecodeTime(DateTime,Hour,Min,Sec,MSec);//解析成小時,分鐘,秒
Caption:= IntToStr(Hour)+'小時'+IntToStr(Min)+'分鐘'+IntToStr(Sec)+'秒';
end;

星期二, 8月 05, 2008

cxgrid分組加上共幾筆的資訊


//create呼叫
// 設定分組之群組資訊
SetCxGridSummaryItems(cxGDBTV1);

procedure TfmMain.SetCxGridSummaryItems(cxGDBTV: TcxGridDBTableView);
var
x: Integer;
sFormat :String;
begin
with cxGDBTV.DataController.Summary do
begin
BeginUpdate;
try
SummaryGroups.Clear;

DefaultGroupSummaryItems.BeginText := '{';
DefaultGroupSummaryItems.EndText := '}';

// Add summary group
with SummaryGroups.Add do
begin
// Add proposed grouping column(s)
// 即以這欄位作分組時會顯示summary items的資訊
for x:=1 to cxGDBTV.ColumnCount-1 do
begin
TcxGridTableSummaryGroupItemLink(Links.Add).Column := cxGDBTV.Columns[x-1];
end;
// Add summary items
sFormat := Format('共 %d 筆', [0]); // '共 0 筆'
with SummaryItems.Add as TcxGridDBTableSummaryItem do
begin
Kind := skCount; // 計算群組筆數
Position := spGroup;
Format := sFormat; // '共 0 筆'
end;
end;

{
// 增加寫出檔案大小統計功能
with SummaryGroups.Add do
begin
// Add proposed grouping column(s)
// 即以這欄位作分組時會顯示summary items的資訊
for x:=1 to cxGDBTV.ColumnCount-1 do
begin
TcxGridTableSummaryGroupItemLink(Links.Add).Column := cxGDBTV.Columns[x-1];
end;
// Add summary items
with SummaryItems.Add as TcxGridDBTableSummaryItem do
begin
//Column := cxGDBTV.GetColumnByFieldName('filesize');
//Column := cxGDBTV.GetColumnByFieldName('filesize'); //GetColumnByFieldName('cxGDBTV1filesize;
ItemLink := cxGDBTV.GetColumnByFieldName('filesize');
Kind := skSum;
Position := spFooter;
Format := 'TOTAL = 0';
end;
end;
//FooterSummaryItems.Add;
}
finally
EndUpdate;
end;
end;
end;

星期四, 7月 31, 2008

使用sharememory方式在各程式之間傳送參數


//宣告部分,寫入及讀取端程式都要有
const
_SMWithXMonitorPolicy = 'XFortMonitorPolicy';

type
TCmdDataWithMonitorPolicy = record // policy
btData1: Byte; //壓縮率
btData2: Byte; //縮放率
btData3: Byte; //
boolData1: Boolean; //是否抓完整圖 ?
boolData2: Boolean;
boolData3: Boolean;
dwData1: DWORD; //錄影間隔時間(秒) ?
dwData2: DWORD; //影像長度(pixel) ?
dwData3: DWORD; //影像寬度(pixel) ?
dwData4: DWORD;
dwData5: DWORD;
dwData6: DWORD;
intData1: Integer; //sessionid
intData2: Integer; //usrid
intData3: Integer; //port
intData4: Integer;
intData5: Integer;
int64Data1: Int64;
int64Data2: Int64;
dtDateTimeData1: TDateTime; // Double(8 bytes)
dtDateTimeData2: TDateTime;
ptData1: Pointer;
ptData2: Pointer;
strData1: array [0..511] of Char; //IP
strData2: array [0..511] of Char; //擷取端電腦名稱
strData3: array [0..511] of Char;
strData4: array [0..511] of Char;
strData5: array [0..511] of Char;
end;
PCmdDataWithMonitorPolicy = ^TCmdDataWithMonitorPolicy;


public
g_hShareMemPolicy :Thandle;
g_pShareMemPolicy :Pointer;



//一端的create須先建立起sharememory
create
g_hShareMemPolicy := CreateFileMapping(
$FFFFFFFF, // Shared memory File,Handle 傳入 $FFFFFFFF
nil, // 不設定安全屬性
PAGE_READWRITE, // 存取模式設定為可讀寫以便行程交換資料
0, // 使用 paging file 時一般將之設為零
SizeOf(TCmdDataWithMonitorPolicy), // 共享記憶體的大小 2048bytes
_SMWithXMonitorPolicy); // 其他的行程將以此名稱參考到選擇共享記憶體

//MapViewOfFile函數返回一個指向共用記憶體塊的在該程式記憶體空間中有效的指標
g_pShareMemPolicy :=MapViewOfFile(
g_hShareMemPolicy , // File-mapping object 的 Handle 值
FILE_MAP_ALL_ACCESS, //設為 FILE_MAP_ALL_ACCESS 開放存取
0,
0,
//0); // 映射回來的 byte 數
SizeOf(TCmdDataWithMonitorPolicy));

//將資料寫入sharememory中
procedure TFormMain.Button1Click(Sender: TObject);
begin
PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.btData1 := 100; //壓縮率
PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.btData2 := 90; //縮放率


PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.intData1 := 5; //sessionid
PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.intData2 := 33; //usrid
PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.intData3 := 24137; //port

//IP
FillChar(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.strData1,SizeOf(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.strData1),0);
StrCopy(PCmdDataWithMonitorPolicy(g_pShareMemPolicy).strData1, PCHAR('10.1.0.3'));

//擷取端電腦名稱
FillChar(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.strData2,SizeOf(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.strData2),0);
StrCopy(PCmdDataWithMonitorPolicy(g_pShareMemPolicy).strData2, PCHAR('Yivon'));
end;



//讀取sharememory資料
procedure TForm1.Button2Click(Sender: TObject);
var
piRes :^Integer;
sTmpFileName : string;
begin
g_hShareMemPolicy := OpenFileMapping(
FILE_MAP_ALL_ACCESS, // Shared memory File,Handle 傳入 $FFFFFFFF
true,
_SMWithXMonitorPolicy); // 其他的行程將以此名稱參考到選擇共享記憶體
if g_hShareMemPolicy <> 0 then //判斷這一塊SHAREMEMORY有無配置
begin
g_pShareMemPolicy:=MapViewOfFile(
g_hShareMemPolicy, // File-mapping object 的 Handle 值
FILE_MAP_ALL_ACCESS, //設為 FILE_MAP_ALL_ACCESS 開放存取
0,
0,
//0); // 映射回來的 byte 數
SizeOf(TCmdDataWithMonitorPolicy));

Memo1.Lines.add('壓縮率:'+inttostr(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.btData1));
Memo1.Lines.add('縮放率:'+inttostr(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.btData2));
Memo1.Lines.add('SessionID:'+inttostr(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.intData1));
Memo1.Lines.add('usrid:'+inttostr(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.intData2));
Memo1.Lines.add('Port:'+inttostr(PCmdDataWithMonitorPolicy(g_pShareMemPolicy)^.intData3));
Memo1.Lines.add('IP:'+String(PCmdDataWithMonitorPolicy(g_pShareMemPolicy).strData1));
Memo1.Lines.add('CapComputerName:'+String(PCmdDataWithMonitorPolicy(g_pShareMemPolicy).strData2));
end;
end;

初始化ADOConnection函數


procedure TRecUIControl.InitADOConnectionBeginTrans(ADOConnBatchTrans: TADOConnection);
begin
// 設定ADOConnBatchTrans物件所需參數
with ADOConnBatchTrans do
begin
CommandTimeout := 300;
//ConnectOptions := coAsyncConnect; // The connection is formed asynchronously
CursorLocation := clUseServer; // Connection is client-side
LoginPrompt := False; // Don't show the login dialog when connecting to a database
Provider := 'SQLOLEDB.1'; //
ConnectionString := frmMain.ADOConnection1.ConnectionString; // 取主程式的ConnectionString
end;
end;

星期三, 7月 23, 2008

星期四, 7月 10, 2008

判斷工作管理員內的某個處理程序是否還存在


uses
Tlhelp32;

function FindProc(ProcName: string): Boolean;
var
OK: Bool;
hPL: THandle;
ProcessStruct: TProcessEntry32;
begin
Result := False;
hPL := CreateToolHelp32SnapShot(TH32CS_SNAPPROCESS, 0);
ProcessStruct.dwSize := SizeOf(TProcessEntry32);
OK := Process32First(hPL, ProcessStruct);
while OK do
begin
if UpperCase(ProcessStruct.szExeFile) = UpperCase(ProcName) then
begin
Result := True;
end;
OK := Process32Next(hPL, ProcessStruct);
end;
CloseHandle(hPL);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
if FindProc('bds.exe') then
begin

end;

end;



///////////////////new////////////
//加入process的數量判斷,若大於2,一定是重復執行囉~
function FindProc(ProcName: string): integer;
var
OK: Bool;
hPL: THandle;
ProcessStruct: TProcessEntry32;
i:integer;
begin
i:=0;
hPL := CreateToolHelp32SnapShot(TH32CS_SNAPPROCESS, 0);
ProcessStruct.dwSize := SizeOf(TProcessEntry32);
OK := Process32First(hPL, ProcessStruct);
while OK do
begin
if UpperCase(ProcessStruct.szExeFile) = UpperCase(ProcName) then
begin
i := i+1;
end;
OK := Process32Next(hPL, ProcessStruct);
end;
Result := i;
CloseHandle(hPL);
end;

星期四, 7月 03, 2008

取得Windows的SessionID

windows xp的SessionID從0開始
windows vista的SessionID從1開始.0是給特殊權限如SYSTEM

function GetSessionId:DWord;
type _P2S=function (PId:DWORD; var SId:DWORD):BOOL; stdcall;
var P2S: _P2S;
Hd :HMODULE;
SId:DWord;
begin
Result:=0;
Hd:=LoadLibrary('Kernel32.dll');
if Hd<>0 then begin
@P2S:=GetProcAddress(Hd,'ProcessIdToSessionId');
if Assigned(P2S) and P2S(GetCurrentProcessId,SId) then Result:=SId;
FreeLibrary(Hd);
end;
end;

星期二, 5月 13, 2008

開啟chm某個關聯的位置網頁


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

function HtmlHelpA (hwndcaller:Longint; lpHelpFile:string; wCommand:Longint;dwData:string): HWND;stdcall; external 'hhctrl.ocx'
procedure ShowChmHelp(sTopic:string);
var
i : integer;
begin
i:=HtmlHelpA(Application.Handle,Pchar('c:\windows.chm'), 0, sTopic);
if i=0 then
begin
showmessage(' help.chm幫助文件損壞!');
exit;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
tmp : integer;
begin
tmp := 10100;
case tmp of
10100: ShowChmHelp('Win32GDI/15.htm');
10101: ShowChmHelp('edtInput.htm');

else ShowChmHelp('default.htm');
end;
end;

end.

星期五, 5月 02, 2008

StrToDate可能會發生not a valid date

這是因為控制台->地區選項->日期分隔字元或型式有改變。
這是你須用程式去設定其地區選項設定

//設定日期格式為 yyyy/MM/dd
SetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, 'yyyy/MM/dd') ;

//設定日曆格式為1 型式
SetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_ICALENDARTYPE, '1') ;

星期三, 4月 30, 2008

寫網卡MAC到exe檔裡,並在程式開始時做判斷


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
Edit5: TEdit;
Edit6: TEdit;
Button1: TButton;
Label1: TLabel;
SaveDialog1: TSaveDialog;
Button2: TButton;
Edit7: TEdit;
Button3: TButton;
Label2: TLabel;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

type
DWordA =array [0..7] of DWord;
DWordP =^DWordA;
DWordB =array [0..7] of Byte;
var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button2Click(Sender: TObject);
begin
if SaveDialog1.Execute then
Edit7.Text := SaveDialog1.FileName ;
end;

function UpdateExe(N:string; ChkL:DWord; ChkH:DWord):boolean; // Write CRC to file
var
Hd,i:integer;
D,R:DWordB; // $1E
begin
Result:=False;
DWordP(@D[0])[0]:=ChkL; //20處開始由低位元塞CRC資料 若為DWordP(@D[3])[0] 則是從21處開始塞
DWordP(@D[4])[0]:=ChkH;

if FileExists(N) then
begin
Hd:=FileOpen(N,fmOpenReadWrite); //開啟N
FileSeek(Hd,$20,0);
FileWrite(Hd,D[0],8); //從20開始寫入8個byte值
FileSeek(Hd,$20,0);
FileRead(Hd,R[0],8);
//檢查
Result:=TRUE;
for i:=0 to SizeOf(D)-1 do
if D[i]<>R[i] then
begin
Result:=False;
end;
FileClose(Hd);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
m1 : DWord;
m2 : DWord;
begin
m1 := (strtoint('$'+Edit1.Text) + strtoint('$'+Edit2.Text+'00') + strtoint('$'+Edit3.Text+'0000') + strtoint('$'+Edit4.Text+'000000')) xor $AE5C2DDA;
m2 := (strtoint('$'+Edit5.Text) + strtoint('$'+Edit6.Text+'00')) xor $0000C1A3;
UpdateExe(Edit7.Text, m1, m2);

end;

function ReadFileHeader(N:string;var Chk:DWordB):boolean; // Write CRC to file
var
Hd : integer;
R : DWordB; // $1E
begin
Result:=False;
if FileExists(N) then
begin
Hd:=FileOpen(N,fmOpenRead); //開啟N
FileSeek(Hd,$20,0);
FileRead(Hd,R[0],8);
CHk := R;
Result:=True;
FileClose(Hd);
end;
end;

function MacAddress: string;
var
Lib: Cardinal;
Func: function(GUID: PGUID): Longint; stdcall;
GUID1, GUID2: TGUID;
begin
Result := '';
Lib := LoadLibrary('rpcrt4.dll');
if Lib <> 0 then
begin
if Win32Platform <>VER_PLATFORM_WIN32_NT then
@Func := GetProcAddress(Lib, 'UuidCreate')
else @Func := GetProcAddress(Lib, 'UuidCreateSequential');
if Assigned(Func) then
begin
if (Func(@GUID1) = 0) and
(Func(@GUID2) = 0) and
(GUID1.D4[2] = GUID2.D4[2]) and
(GUID1.D4[3] = GUID2.D4[3]) and
(GUID1.D4[4] = GUID2.D4[4]) and
(GUID1.D4[5] = GUID2.D4[5]) and
(GUID1.D4[6] = GUID2.D4[6]) and
(GUID1.D4[7] = GUID2.D4[7]) then
begin
Result :=
IntToHex(GUID1.D4[2] xor $DA, 2) + '-' +
IntToHex(GUID1.D4[3] xor $2D, 2) + '-' +
IntToHex(GUID1.D4[4] xor $5C, 2) + '-' +
IntToHex(GUID1.D4[5] xor $AE, 2) + '-' +
IntToHex(GUID1.D4[6] xor $A3, 2) + '-' +
IntToHex(GUID1.D4[7] xor $C1, 2);
end;
end;
FreeLibrary(Lib);
end;
end;

procedure TForm1.Button3Click(Sender: TObject);
var
R1: DWordB; // $1E
begin
ReadFileHeader(Edit7.Text, R1);
Label1.Caption:=IntToHex(R1[0],2)+'-'+IntToHex(R1[1],2)+'-'+IntToHex(R1[2],2)+'-'+IntToHex(R1[3],2)+'-'+IntToHex(R1[4],2)+'-'+IntToHex(R1[5],2);
Label2.Caption:=MacAddress;

if not SameText(Label1.Caption, Label2.Caption) then
application.Terminate ;
end;
end.

星期四, 4月 24, 2008

設定快捷鍵的方法

方法一:
用TActionList來管理

方法二:
安裝ElPack4元件
開到ELPack Tools,選擇ElSysHotKey元件
在其屬性ShortCut就可以修改快捷鍵
Enabled設為true
並在事件OnPress設定為欲執行的事件即可(如Button1.click;)

用訊號燈的方式,限制thread同時執行的數目

MainForm

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FSemaphor: THandle;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses Unit2;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
FSemaphor := CreateSemaphore( nil, 3, 3, nil );
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
CloseHandle( FSemaphor );
end;
procedure TForm1.Button1Click(Sender: TObject);
var
aIndex: Integer;
aExchange: TExchange;
begin
for aIndex := 1 to 20 do
begin
if ( WaitForSingleObject( FSemaphor, INFINITE ) = WAIT_OBJECT_0 ) then
begin
aExchange := TExchange.Create( True, FSemaphor );
aExchange.FreeOnTerminate := True;
aExchange.Resume;
end;
end;
end;
end.

Thread

type
TExchange = class(TThread)
private
{ Private declarations }
FSemaphor: THandle;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended:Boolean; ASemaphor: THandle); reintroduce;
end;
implementation
{ TExchange }
constructor TExchange.Create(CreateSuspended: Boolean; ASemaphor: THandle);
begin
inherited Create( CreateSuspended );
FSemaphor := ASemaphor;
end;
procedure TExchange.Execute;
begin
while not Self.Terminated do
begin
Sleep( 10000 );
Break;
end;
ReleaseSemaphore( FSemaphor, 1, nil );
end;

將組合字串還原存進TStringList陣列的方法


procedure GetSetData(CombinedStr:String;var sl:TStringList);
var
s : String;
p,l : integer;
begin
sl.Clear;
l:=Length(CombinedStr);
if l=0 then exit;
p:=1;
while p > 0 do
begin
p:=Pos(',,,',CombinedStr);
if p > 0 then
begin
s:=Copy(CombinedStr,1,p-1);
sl.Add(s);
CombinedStr:=Copy(CombinedStr,p+3,Length(CombinedStr));
end;
end;
if Length(CombinedStr) > 0 then
begin
sl.Add(CombinedStr);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
mysl : TStringList;
begin
mysl := TStringList.Create;
try
GetSetData('oo,,,ertff,,,wett' ,mysl);
caption := mysl[0]+'__'+mysl[1]+'__'+mysl[2];
finally
mysl.Free;
end;
end;

星期三, 4月 23, 2008

如何讓Button上的文字顯示二行以上

首先將Button1屬性WordWrap設為true
方法1:
在Object Inspector去點兩下修改Button的Caption,
記得使用Ctrl+Enter來換行喔!!

方法2:
接下來按ALT+F12去編輯dfm的檔案
去搜尋到Button1的caption去編輯
如:
'AAA'+#13#10+'BBB'

UpperCase轉中文字時會出現錯誤的問題

可用UpperCaseEx來取代UpperCase函數

function UpperCaseEx(const S: string): string;
var
Ch: Char;
L: Integer;
Source, Dest: PChar;
nH: Integer;
begin
L := Length(S);
SetLength(Result, L);
Source := Pointer(S);
Dest := Pointer(Result);
nH := 0;
while L <> 0 do
begin
Ch := Source^;
if nH = 0 then
if Ord(ch) >= 128 then
nH := 2;
if nH > 0 then
Dec(nH)
else
if (Ch >= 'a') and (Ch <= 'z') then Dec(Ch, 32);
Dest^ := Ch;
Inc(Source);
Inc(Dest);
Dec(L);
end;
end;

多國語言讀入字串後要注意的事

Label屬性設定
AutoSize=False
Height=20
Layout=tlcenter
ParentFont=false
TransParent=true
Button屬性設定
ParentFont=true

// caption及Label要設定為螢幕字型及語言,Button不同,會依照form來決定字型
self.Font.Name := Screen.MenuFont.Name;
self.Font.Charset := Screen.MenuFont.Charset;
Caption := _sArray[_L_ExportCaption];

Label1.Font.Name :=Screen.MenuFont.Name;
Label1.Font.Charset :=Screen.MenuFont.Charset;
Label1.Caption := _sArray[_L_ExportPleaseSel];

星期五, 4月 18, 2008

截取當前的視窗(不是全螢幕)


procedure TForm1.Button1Click(Sender: TObject);
var
HWND:THandle;
dc:HDC ;
rect:TRect ;
dest:TBitmap;
jpg :TJpegImage;
w, h : integer;
begin
HWND:=handle;
GetWindowRect(HWND,rect);
dc:=GetWindowDC(HWND);
dest := TBitmap.Create;
jpg := TJpegImage.create;
w := rect.Right-rect.Left;
h := rect.Bottom-rect.Top;
dest.Width := w;
dest.height := h;
try
BitBlt(dest.canvas.handle,0,0,w,h,dc,0,0,SRCCOPY );
jpg.Assign(dest);
jpg.CompressionQuality:=100;
jpg.JPEGNeeded;
jpg.Compress;
jpg.SaveToFile('c:\1.jpg');
finally
ReleaseDC(HWND,dc);
jpg.free;
dest.Free;
end;
end;

星期二, 4月 08, 2008

開始寫Delphi程式要注意的事

Project -> options > Compiler -> Code generation -> 取消勾選Optimization
Tool -> Environment Options -> Delphi Direct -> 取消勾選Automatically poll network

Form 屬性scaled設成false 屬性設字型大小建議用Height

主視窗隱藏

Application.ShowMainForm := False;

隱藏主視窗窗體

Application.ShowMainForm := False;

星期一, 4月 07, 2008

UTC跟LocalTime


var
g_dtTimeZoneInfo:TIME_ZONE_INFORMATION ;
function GetTimeZoneInfo():boolean ;//取得utc時間
begin
Result := (TIME_ZONE_ID_INVALID<>GetTimeZoneInformation(g_dtTimeZoneInfo) ) ;
end ;
function LocalTimeToUTC(const dtLocalTime: TDateTime) : TDateTime ;
begin
Result := IncMinute(dtLocalTime, g_dtTimeZoneInfo.Bias ) ;
end ;

function UTCToLocalTime(const dtUTC: TDateTime) : TDateTime ;
begin
Result := IncMinute(dtUTC, -g_dtTimeZoneInfo.Bias ) ;
end ;

function UTCNow(): TDateTime;
var
st: SYSTEMTIME;

begin
GetSystemTime(st);
Result:=SystemTimeToDateTime(st);
end;
//---------------------------------------------------------------------------

function UTCDate(): TDateTime;
var
st: SYSTEMTIME;

begin
GetSystemTime(st);
Result:=EncodeDate(st.wYear, st.wMonth, st.wDay);
end;

星期一, 3月 31, 2008

判斷磁碟機是否有效

可判斷磁碟機,如A槽或光碟槽是否有效

function ValidDrive( driveletter: Char ): Boolean;
var
mask: String[6];
sRec: TSearchRec;
oldMode: Cardinal;
retcode: Integer;
begin
oldMode :=SetErrorMode( SEM_FAILCRITICALERRORS );
mask:= '?:\*.*';
mask[1] := driveletter;
{$I-} { don't raise exceptions if we fail }
retcode := FindFirst( mask, faAnyfile, SRec );
if retcode = 0 then
FindClose( SRec );
{$I+}
Result := Abs(retcode) in
[ERROR_SUCCESS,ERROR_FILE_NOT_FOUND,ERROR_NO_MORE_FILES];
SetErrorMode( oldMode );
end; { ValidDrive }

星期二, 3月 25, 2008

防呆裝置,無效的按鍵不能按


procedure TFormMain.SpinTotalTimeKeyPress(Sender: TObject;var Key: Char);
begin
if (Key='-') or (Key='.') or (Key='+') then Key:=char(0);
end;

function CheckLegalSpinValue( var spin:TSpinEdit; var Key:Word ):boolean;overload;
begin
//if not( Key in [$9, $30..$57, $60..$69, $D, $A, $25, $27, $90, VK_BACK, VK_DELETE] ) then
//應觀眾要求修改 20070625 Ma
if not( Key in [$9, $30..$57, $60..$69, $D, $A, $25, $26, $27, $28, $90, VK_BACK, VK_DELETE] ) then
begin
OneBtnMsgBox(g_saMsg[27], MB_ICONSTOP) ; // '請輸入合法的數字'
spin.Value := 0 ;
Result := false ; // defined in windows
Exit ;
end ;
Result := true ;
end ;


{ check if the input in TSpinEdit is legal }
function CheckLegalSpinValue( var spin:TSpinEdit):boolean;overload;
begin
if( IsLegalInt(spin.Text) ) then
Result := true
else
Result := false ;
end ;

procedure TFrame3.SpinEdit1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if( not CheckLegalSpinValue(SpinEdit1, Key) ) then
Exit;
end;

星期四, 3月 20, 2008

月利率來看,則存入多少金額可獲得最高報酬利率


procedure TForm1.Button1Click(Sender: TObject);
var
i : double;
j : integer;
want_money : integer;
begin
if Edit2.text='0' then
j := 1
else
j := strtoint(Edit2.text);
i := trunc(j*strtofloat(Edit1.Text)/1200+0.4)+0.5;
want_money := trunc(i*1200/strtofloat(Edit1.Text)+0.5);
Label3.Caption := floattostr(want_money);
Label4.Caption := floattostr((i+0.5)*1200/want_money);
Label5.Caption := floattostr(i+0.5);
end;

星期三, 3月 19, 2008

記錄平均cpu使用率多少的程式

主程式,新增一個TMemo,一個Timer

unit fmTest;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, adCpuUsage, ExtCtrls;

type
TTestForm = class(TForm)
MInfo: TMemo;
LbAldynUrl: TLabel;
Timer: TTimer;
procedure LbAldynUrlClick(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
TestForm: TTestForm;

implementation

{$R *.DFM}

uses shellapi;

procedure TTestForm.LbAldynUrlClick(Sender: TObject);
begin
ShellExecute(Application.Handle, 'open', 'http://www.aldyn.ru/',
nil, nil, SW_SHOWDEFAULT);
end;

procedure TTestForm.TimerTimer(Sender: TObject);
var i: Integer;
begin
CollectCPUData;
MInfo.Lines.BeginUpdate;
for i:=0 to GetCPUCount-1 do
MInfo.Lines[i+1]:=Format('CPU #%d - %5.2f%%',[i,GetCPUUsage(i)*100]);
MInfo.Lines.EndUpdate;
end;

procedure TTestForm.FormCreate(Sender: TObject);
var i: Integer;
begin
MInfo.Lines.Clear;

MInfo.Lines.Add(Format('There are %d total CPU in your system',[GetCPUCount]));

for i:=0 to GetCPUCount-1 do MInfo.Lines.Add('');
end;

end.


adCpuUsage.pas

unit adCpuUsage;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
CPU Usage Measurement routines for Delphi and C++ Builder

Author: Alexey A. Dynnikov
EMail: aldyn@chat.ru
WebSite: http://www.aldyn.ru/
Support: Use the e-mail aldyn@chat.ru
or support@aldyn.ru

Creation: Jul 8, 2000
Version: 1.02

Legal issues: Copyright (C) 2000 by Alexey A. Dynnikov

This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:

1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.

2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.

3. This notice may not be removed or altered from any source
distribution.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
USAGE:

1. Include this unit into project.

2. Call GetCPUCount to obtain the numbr of processors in the system

3. Each time you need to know the value of CPU usage call the CollectCPUData
to refresh the CPU usage information. Then call the GetCPUUsage to obtain
the CPU usage for given processor. Note that succesive calls of GetCPUUsage
without calling CollectCPUData will return the same CPU usage value.

Example:

procedure TTestForm.TimerTimer(Sender: TObject);
var i: Integer;
begin
CollectCPUData; // Get the data for all processors

for i:=0 to GetCPUCount-1 do // Show data for each processor
MInfo.Lines[i]:=Format('CPU #%d - %5.2f%%',[i,GetCPUUsage(i)*100]);
end;
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}

interface

uses
Windows, SysUtils;

// Call CollectCPUData to refresh information about CPU usage
procedure CollectCPUData;

// Call it to obtain the number of CPU's in the system
function GetCPUCount: Integer;

// Call it to obtain the % of usage for given CPU
function GetCPUUsage(Index: Integer): Double;

// For Win9x only: call it to stop CPU usage monitoring and free system resources
procedure ReleaseCPUData;

implementation

{$ifndef ver110}

{$ifndef ver90}
{$ifndef ver100}
{$define UseInt64}
{$endif}
{$endif}


{$ifdef UseInt64}
type TInt64 = Int64;
{$else}
type TInt64 = Comp;
{$endif}

{$else}

type TInt64 = TLargeInteger;

{$endif}

type
PInt64 = ^TInt64;

type
TPERF_DATA_BLOCK = record
Signature : array[0..4 - 1] of WCHAR;
LittleEndian : DWORD;
Version : DWORD;
Revision : DWORD;
TotalByteLength : DWORD;
HeaderLength : DWORD;
NumObjectTypes : DWORD;
DefaultObject : Longint;
SystemTime : TSystemTime;
Reserved: DWORD;
PerfTime : TInt64;
PerfFreq : TInt64;
PerfTime100nSec : TInt64;
SystemNameLength : DWORD;
SystemNameOffset : DWORD;
end;

PPERF_DATA_BLOCK = ^TPERF_DATA_BLOCK;

TPERF_OBJECT_TYPE = record
TotalByteLength : DWORD;
DefinitionLength : DWORD;
HeaderLength : DWORD;
ObjectNameTitleIndex : DWORD;
ObjectNameTitle : LPWSTR;
ObjectHelpTitleIndex : DWORD;
ObjectHelpTitle : LPWSTR;
DetailLevel : DWORD;
NumCounters : DWORD;
DefaultCounter : Longint;
NumInstances : Longint;
CodePage : DWORD;
PerfTime : TInt64;
PerfFreq : TInt64;
end;

PPERF_OBJECT_TYPE = ^TPERF_OBJECT_TYPE;

type
TPERF_COUNTER_DEFINITION = record
ByteLength : DWORD;
CounterNameTitleIndex : DWORD;
CounterNameTitle : LPWSTR;
CounterHelpTitleIndex : DWORD;
CounterHelpTitle : LPWSTR;
DefaultScale : Longint;
DetailLevel : DWORD;
CounterType : DWORD;
CounterSize : DWORD;
CounterOffset : DWORD;
end;

PPERF_COUNTER_DEFINITION = ^TPERF_COUNTER_DEFINITION;

TPERF_COUNTER_BLOCK = record
ByteLength : DWORD;
end;

PPERF_COUNTER_BLOCK = ^TPERF_COUNTER_BLOCK;

TPERF_INSTANCE_DEFINITION = record
ByteLength : DWORD;
ParentObjectTitleIndex : DWORD;
ParentObjectInstance : DWORD;
UniqueID : Longint;
NameOffset : DWORD;
NameLength : DWORD;
end;

PPERF_INSTANCE_DEFINITION = ^TPERF_INSTANCE_DEFINITION;

//------------------------------------------------------------------------------
{$ifdef ver130}
{$L-} // The L+ causes internal error in Delphi 5 compiler
{$O-} // The O+ causes internal error in Delphi 5 compiler
{$Y-} // The Y+ causes internal error in Delphi 5 compiler
{$endif}

{$ifndef ver110}
type
TInt64F = TInt64;
{$else}
type
TInt64F = Extended;
{$endif}

{$ifdef ver110}
function FInt64(Value: TInt64): TInt64F;
function Int64D(Value: DWORD): TInt64;
{$else}
type
FInt64 = TInt64F;
Int64D = TInt64;
{$endif}

{$ifdef ver110}
function FInt64(Value: TInt64): TInt64F;
var V: TInt64;
begin
if (Value.HighPart and $80000000) = 0 then // positive value
begin
result:=Value.HighPart;
result:=result*$10000*$10000;
result:=result+Value.LowPart;
end else
begin
V.HighPart:=Value.HighPart xor $FFFFFFFF;
V.LowPart:=Value.LowPart xor $FFFFFFFF;
result:= -1 - FInt64(V);
end;
end;

function Int64D(Value: DWORD): TInt64;
begin
result.LowPart:=Value;
result.HighPart := 0; // positive only
end;
{$endif}

//------------------------------------------------------------------------------

const
Processor_IDX_Str = '238';
Processor_IDX = 238;
CPUUsageIDX = 6;

type
AInt64F = array[0..$FFFF] of TInt64F;
PAInt64F = ^AInt64F;

var
_PerfData : PPERF_DATA_BLOCK;
_BufferSize: Integer;
_POT : PPERF_OBJECT_TYPE;
_PCD: PPerf_Counter_Definition;
_ProcessorsCount: Integer;
_Counters: PAInt64F;
_PrevCounters: PAInt64F;
_SysTime: TInt64F;
_PrevSysTime: TInt64F;
_IsWinNT: Boolean;

_W9xCollecting: Boolean;
_W9xCpuUsage: DWORD;
_W9xCpuKey: HKEY;


//------------------------------------------------------------------------------
function GetCPUCount: Integer;
begin
if _IsWinNT then
begin
if _ProcessorsCount < 0 then CollectCPUData;
result:=_ProcessorsCount;
end else
begin
result:=1;
end;

end;

//------------------------------------------------------------------------------
procedure ReleaseCPUData;
var H: HKEY;
R: DWORD;
dwDataSize, dwType: DWORD;
begin
if _IsWinNT then exit;
if not _W9xCollecting then exit;
_W9xCollecting:=False;

RegCloseKey(_W9xCpuKey);

R:=RegOpenKeyEx( HKEY_DYN_DATA, 'PerfStats\StopStat', 0, KEY_ALL_ACCESS, H );

if R <> ERROR_SUCCESS then exit;

dwDataSize:=sizeof(DWORD);

RegQueryValueEx ( H, 'KERNEL\CPUUsage', nil, @dwType, PBYTE(@_W9xCpuUsage), @dwDataSize);

RegCloseKey(H);

end;

//------------------------------------------------------------------------------
function GetCPUUsage(Index: Integer): Double;
begin
if _IsWinNT then
begin
if _ProcessorsCount < 0 then CollectCPUData;
if (Index >= _ProcessorsCount) or (Index < 0) then
raise Exception.Create('CPU index out of bounds');
if _PrevSysTime = _SysTime then result:=0 else
result:=1-(_Counters[index] - _PrevCounters[index])/(_SysTime-_PrevSysTime);
end else
begin
if Index <> 0 then
raise Exception.Create('CPU index out of bounds');
if not _W9xCollecting then CollectCPUData;
result:=_W9xCpuUsage / 100;
end;
end;

var VI: TOSVERSIONINFO;

//------------------------------------------------------------------------------
procedure CollectCPUData;
var BS: integer;
i: Integer;
_PCB_Instance: PPERF_COUNTER_BLOCK;
_PID_Instance: PPERF_INSTANCE_DEFINITION;
ST: TFileTime;

var H: HKEY;
R: DWORD;
dwDataSize, dwType: DWORD;
begin
if _IsWinNT then
begin
BS:=_BufferSize;
while RegQueryValueEx( HKEY_PERFORMANCE_DATA, Processor_IDX_Str, nil, nil,
PByte(_PerfData), @BS ) = ERROR_MORE_DATA do
begin
// Get a buffer that is big enough.
INC(_BufferSize,$1000);
BS:=_BufferSize;
ReallocMem( _PerfData, _BufferSize );
end;

// Locate the performance object
_POT := PPERF_OBJECT_TYPE(DWORD(_PerfData) + _PerfData.HeaderLength);
for i := 1 to _PerfData.NumObjectTypes do
begin
if _POT.ObjectNameTitleIndex = Processor_IDX then Break;
_POT := PPERF_OBJECT_TYPE(DWORD(_POT) + _POT.TotalByteLength);
end;

// Check for success
if _POT.ObjectNameTitleIndex <> Processor_IDX then
raise Exception.Create('Unable to locate the "Processor" performance object');

if _ProcessorsCount < 0 then
begin
_ProcessorsCount:=_POT.NumInstances;
GetMem(_Counters,_ProcessorsCount*SizeOf(TInt64));
GetMem(_PrevCounters,_ProcessorsCount*SizeOf(TInt64));
end;

// Locate the "% CPU usage" counter definition
_PCD := PPERF_Counter_DEFINITION(DWORD(_POT) + _POT.HeaderLength);
for i := 1 to _POT.NumCounters do
begin
if _PCD.CounterNameTitleIndex = CPUUsageIDX then break;
_PCD := PPERF_COUNTER_DEFINITION(DWORD(_PCD) + _PCD.ByteLength);
end;

// Check for success
if _PCD.CounterNameTitleIndex <> CPUUsageIDX then
raise Exception.Create('Unable to locate the "% of CPU usage" performance counter');

// Collecting coutners
_PID_Instance := PPERF_INSTANCE_DEFINITION(DWORD(_POT) + _POT.DefinitionLength);
for i := 0 to _ProcessorsCount-1 do
begin
_PCB_Instance := PPERF_COUNTER_BLOCK(DWORD(_PID_Instance) + _PID_Instance.ByteLength );

_PrevCounters[i]:=_Counters[i];
_Counters[i]:=FInt64(PInt64(DWORD(_PCB_Instance) + _PCD.CounterOffset)^);

_PID_Instance := PPERF_INSTANCE_DEFINITION(DWORD(_PCB_Instance) + _PCB_Instance.ByteLength);
end;

_PrevSysTime:=_SysTime;
SystemTimeToFileTime(_PerfData.SystemTime, ST);
_SysTime:=FInt64(TInt64(ST));
end else
begin
if not _W9xCollecting then
begin
R:=RegOpenKeyEx( HKEY_DYN_DATA, 'PerfStats\StartStat', 0, KEY_ALL_ACCESS, H );
if R <> ERROR_SUCCESS then
raise Exception.Create('Unable to start performance monitoring');

dwDataSize:=sizeof(DWORD);

RegQueryValueEx( H, 'KERNEL\CPUUsage', nil, @dwType, PBYTE(@_W9xCpuUsage), @dwDataSize );

RegCloseKey(H);

R:=RegOpenKeyEx( HKEY_DYN_DATA, 'PerfStats\StatData', 0,KEY_READ, _W9xCpuKey );

if R <> ERROR_SUCCESS then
raise Exception.Create('Unable to read performance data');

_W9xCollecting:=True;
end;

dwDataSize:=sizeof(DWORD);
RegQueryValueEx( _W9xCpuKey, 'KERNEL\CPUUsage', nil,@dwType, PBYTE(@_W9xCpuUsage), @dwDataSize );
end;
end;


initialization
_ProcessorsCount:= -1;
_BufferSize:= $2000;
_PerfData := AllocMem(_BufferSize);

VI.dwOSVersionInfoSize:=SizeOf(VI);
if not GetVersionEx(VI) then raise Exception.Create('Can''t get the Windows version');

_IsWinNT := VI.dwPlatformId = VER_PLATFORM_WIN32_NT;
finalization
ReleaseCPUData;
FreeMem(_PerfData);
end.

星期一, 3月 17, 2008

模擬ListBox按上下鍵會有游標移動的功能

目前尚有問題:未能得知第一個被選的

case TWMKey(Msg).CharCode of
VK_DELETE : BtnRealTimeDelete.Click;

VK_DOWN :
begin
if (LBRealTime.ItemIndex = LBRealTime.Count-1) or (LBRealTime.Count=0) then
exit;
LBRealTime.ItemIndex := LBRealTime.ItemIndex+1;
if GetKeyState(VK_SHIFT) >= 0 then //代表沒按shift
begin
for i:=0 to LBRealTime.Count-1 do
LBRealTime.Selected [i] := false;
g_RealTimeShift := false;
LBRealTime.Selected[LBRealTime.ItemIndex] := true;
end else
begin
for i:=0 to LBRealTime.Count-1 do
LBRealTime.Selected [i] := false;
g_RealTimeShift := true;
if g_RealTimeShiftRec<= LBRealTime.ItemIndex then
for i:=g_RealTimeShiftRec to LBRealTime.ItemIndex do
LBRealTime.Selected [i] := true
else
for i:=g_RealTimeShiftRec downto LBRealTime.ItemIndex do
LBRealTime.Selected [i] := true;
end;
LBRealTimeClick(self);
end;
VK_UP :
begin
if (LBRealTime.ItemIndex = 0) or (LBRealTime.Count=0) then
exit;
LBRealTime.ItemIndex := LBRealTime.ItemIndex-1;
if GetKeyState(VK_SHIFT) >= 0 then //代表沒按shift
begin
for i:=0 to LBRealTime.Count-1 do
LBRealTime.Selected [i] := false;
g_RealTimeShift := false;
LBRealTime.Selected[LBRealTime.ItemIndex] := true;
end else
begin
for i:=0 to LBRealTime.Count-1 do
LBRealTime.Selected [i] := false;
g_RealTimeShift := true;
if g_RealTimeShiftRec<= LBRealTime.ItemIndex then
for i:=g_RealTimeShiftRec to LBRealTime.ItemIndex do
LBRealTime.Selected [i] := true
else
for i:=g_RealTimeShiftRec downto LBRealTime.ItemIndex do
LBRealTime.Selected [i] := true;
end;
LBRealTimeClick(self);
end;

end;

按鍵上下鍵變成下一個物件去


procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_DOWN: Perform(WM_NEXTDLGCTL, 0, 0);
VK_UP: Perform(WM_NEXTDLGCTL, 1, 0);
end;
end;

星期日, 3月 16, 2008

判斷字串是否為整數

Str:string;
if StrToIntDef(Str,-1)=-1 then
Str 不是數字。

星期一, 3月 10, 2008

取得檔案大小


procedure TForm1.Button1Click(Sender: TObject);
var FileRec:TSearchrec;
begin
FindFirst('C:\blowfish11.rar',faAnyfile,FileRec);
SHOWMESSAGE(INTTOSTR(FILEREC.Size));
FindClose(FileRec);
end;

星期五, 3月 07, 2008

將涵有半型及全型字串轉為全型字串


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}
function AsciiToAlpha(Source: String): String;
const
Alpha: array[32..126] of String = ( ' ', '!', '”','#' ,'$' ,'%','&' ,'’' ,'(' ,')','*','+', ',',
'-', '.', '/', '0', '1', '2', '3', '4', '5', '6','7', '8', '9',
':', ';', '<', '=', '>', '?', '@' , 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J','K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '〔', '\', '〕', '︿','_', '’',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v','w','x','y','z',
'{', '|', '}', '~'
);
ASCII: array[32..126] of String = (
' ', '!', '"','#' ,'$' ,'%','&' ,'`' ,'(' ,')','*','+', ',',
'-', '.', '/', '0', '1','2', '3', '4', '5', '6','7', '8', '9',
':', ';','<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E','F',
'G', 'H', 'I', 'J','K', 'L', 'M', 'N', 'O','P', 'Q', 'R', 'S',
'T','U', 'V', 'W', 'X', 'Y','Z', '[', '\', ']', '^','_', '`',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x','y','z',
'{', '|', '}', '~'
);
var
w:WideString;
ret:WideString;
i:integer;
begin
w:= Source;
i:=1;
ret := '';
for i := 1 to length(w) do
begin
if w[i] > #128 then
begin
ret := ret+ w[i];
end else begin
if ((Ord(w[i]) >=(32)) and (Ord(w[i])<=(126))) then
begin
ret := ret+ Alpha[ ord(w[i]) ];
end;
end;
end;
result := ret;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
caption := AsciiToAlpha('YAO');
end;

end.

星期二, 3月 04, 2008

使按鈕能有下壓(凹下去)的效果

使用SpeedButton元件,但注意屬性要設定對喔:
AllowAllUp = true;
Down = true;(設定凹下去或凸出來)
GroupIndex = 1;

星期五, 1月 18, 2008

取得目前(所有)的螢幕解析度及色彩

目前

procedure TForm1.Button1Click(Sender: TObject);
var
dm: TDeviceMode;
Mode: string;
begin
Memo1.Clear;
Mode := '';

EnumDisplaySettings(nil, High(DWORD)-1, dm);
Mode := IntToStr(dm.dmBitsPerPel) + ' Bits Per Pixel ' +
IntToStr(dm.dmPelsWidth) + ' x ' +
IntToStr(dm.dmPelsHeight);
memo1.lines.Add(Mode);
end;



procedure GetVideoModes(ModeList: TStrings);
var
i, j: integer;
MoreModes,
AddMode: boolean;
dm: TDeviceMode;
Mode: string;
begin
ModeList.Clear;
MoreModes := True;
Mode := '';
i := 0;
while MoreModes do
begin
MoreModes := EnumDisplaySettings(nil, i, dm);
Mode := IntToStr(dm.dmBitsPerPel) + ' Bits Per Pixel ' +
IntToStr(dm.dmPelsWidth) + ' x ' +
IntToStr(dm.dmPelsHeight);
AddMode := True;
{ Check to make sure this mode is not already in the list. }
for j := 0 to ModeList.Count-1 do
if Mode = ModeList[j] then
AddMode := False;
if AddMode then
ModeList.Add(Mode);
Inc(i);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
GetVideoModes(memo1.lines);
end;

星期四, 1月 17, 2008

使用一個隱藏視窗在跑Timer

Unit1.pas
新增2個按鈕,並在入事件

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AppEvnts, StdCtrls, UnitTAA;

type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
ApplicationEvents1: TApplicationEvents;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ApplicationEvents1Message(var Msg: tagMSG;
var Handled: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
AAInit;
g_AA.TestHD:=Self.Handle;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
g_AA.Destroy;
end;

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
var Handled: Boolean);
begin
if Msg.message = WM_USER + 22 then
begin
Self.Caption:=IntToStr(Msg.wParam);
end;
end;

end.

UnitTAA.pas

unit UnitTAA;

interface

uses Windows, SysUtils, Classes, Graphics, ExtCtrls, Messages, UnitCommon;

const
TimerID_15 = 11111;

type
TAA = class(TObject)
private
{ Private declarations }
MyWinClass : TWndClass;
FMyHideHD : THandle;
FTestHd : THandle;
procedure Init;
public
{ Public declarations }
property MyHideHD : THandle read FMyHideHD;
property TestHD : THandle read FTestHD write FTestHd;
constructor Create;
destructor Destroy;
procedure OnTimer();
end;

procedure AAInit();

var
g_AA : TAA;

implementation

{ TAA }

function TAAWindowProc(hWnd:HWND; iMsg:Integer; wParam:WPARAM; lParam:LPARAM): Integer; stdcall;
var
uTimer : DWORD;
begin
Result:=0;
case iMsg of
WM_CREATE :
begin
uTimer:=SetTimer(hWnd,TimerID_15,1000,nil); //hWnd控制的把柄 TimerId_15標誌 nil指WM_TIMER將處理消息
//if(uTimer = 0) then
// Result:=-1;
exit;
end;
WM_DESTROY :
begin
KillTimer(hWnd, TimerID_15); //銷毀SetTimer建立的計時器
PostQuitMessage(0); //跟Windows說我要退出囉。
exit;
end;
WM_TIMER :
begin
g_AA.OnTimer();
exit;
end;
end;

Result := DefWindowProc(hWnd,iMsg,wParam,lParam); //不感興趣的消息,由windows去處理
end;


constructor TAA.Create;
var
uTimer : DWORD;
begin
DebugStr('TAA.Create');
inherited;
Init;
if IsWindow(FMyHideHD) then
begin
uTimer:=SetTimer(FMyHideHD,TimerID_15,1000,nil);
DebugStr('uTimer = ' + IntToStr(uTimer));
end;
end;

destructor TAA.Destroy;
begin
inherited;
if FMyHideHD <> 0 then
begin
KillTimer(FMyHideHD,TimerID_15);
DestroyWindow(FMyHideHD);
FMyHideHD:=0;
end;
end;

procedure TAA.Init;
var
TempClass : TWndClass;
ClassRegistered : Boolean;
begin
if IsWindow(FMyHideHD) then //檢查MyHD是否為有效的視窗代碼
exit;

try
MyWinClass.style := 0;
MyWinClass.lpfnWndProc := @TAAWindowProc;
MyWinClass.cbClsExtra := 0;
MyWinClass.cbWndExtra := SizeOf(Pointer);
MyWinClass.hInstance := 0;
MyWinClass.hIcon := 0;
MyWinClass.hCursor := 0;
MyWinClass.hbrBackground := 0;
MyWinClass.lpszMenuName := nil;
MyWinClass.lpszClassName := 'MyTAA';
MyWinClass.hInstance := HInstance;
ClassRegistered:=GetClassInfo( HInstance,
MyWinClass.lpszClassName,
TempClass);
//如果沒有存在此class 註冊一個
if not ClassRegistered then
begin
if Windows.RegisterClass(MyWinClass) = 0 then
Exit;
end;

FMyHideHD := CreateWindowEx( WS_EX_TOOLWINDOW,
MyWinClass.lpszClassName,
'', { Window name }
WS_POPUP, { Window Style }
0, 0, { X, Y }
0, 0, { Width, Height }
0, { hWndParent }
0, { hMenu }
HInstance, { hInstance }
nil); { CreateParam }
except
end;
end;

procedure TAA.OnTimer();
var
t : DWORD;
begin
DebugStr('TAA.OnTimer');
t := Random(1000);
PostMessage(g_AA.FTestHd, WM_USER + 22, t, 0);
end;

procedure AAInit();
begin
DebugStr('AAInit');
g_AA := TAA.Create();
end;
end.

記錄Log的pos檔 for DebugView觀看

將UnitCommon.pas程式碼加到入的專案中。

unit UnitCommon;

interface

uses Windows, Forms, SysUtils, Dialogs;
{
const
LOG_LEVEL_HIGH = 1;
LOG_LEVEL_NONE = 0;
}
var
//g_loglevel : integer;
//Buf : array[1..MAX_PATH] of char ;
g_sTempPath : string; // (TempPath)
g_sWorkPath : string; // (WorkingPath)
g_sLogFile : string;
m_create_txt : textFile;
function GetWorkDirectory :String;
function GetTmpDirectory() : string;

procedure DebugStr(sMsg : string);
procedure LogToFile(s:string);

//function GetUserInfoForTest(var sInfo:string) : boolean;

implementation

function GetWorkDirectory;
var
aBuf : array[0..260] of Char;
begin
GetModuleFileName(HINSTANCE, @aBuf[0], SizeOf(aBuf));
Result := IncludeTrailingBackslash(ExtractFilePath(StrPas(aBuf)));
end;

function GetTmpDirectory(): string;
var
dwBuffSize : DWORD;
cBuffer : array[0..MAX_PATH] of char;
begin
dwBuffSize := MAX_PATH;
GetTempPath(dwBuffSize, cBuffer);
Result := cBuffer;
end;
{
//---------------------------------------------------------

procedure ReportLog(str: string);
begin
if(not Assigned(m_Report)) then
Exit;
m_Report.Add(FormatDateTime('yyyy"/"mm"/"dd" "hh:nn:ss ', Now())+str);
end;
//---------------------------------------------------------

procedure ReportLog(str: string; Args: array of const);
var
buf: string;
begin
//Format string.
buf:=Format(str, Args);
//Put Log to Log Factory.
ReportLog(buf);
end;
//---------------------------------------------------------
}

procedure DebugStr(sMsg : string) ;
begin
OutputDebugString(PChar(sMsg));
{
if g_loglevel = LOG_LEVEL_HIGH then
begin
OutputDebugString(PChar(sMsg));
LogToFile(g_sLogFile) ;
end ;
}
end;

procedure LogToFile(s:string) ;
var
txt : textFile;
begin
if g_sLogFile='' then
exit;
try
AssignFile(txt,g_sLogFile);

Append(txt);
writeln(txt,formatDateTime('yyyy/mm/dd hh:nn:ss.zzz',now),' ',s);
CloseFile(txt);
except
g_sLogFile:='';
end;
end;


{
function GetUserInfoForTest(var sInfo:string): boolean;
var
hOpenMap : THandle;
pAddr : pchar;
begin
Result := false;
hOpenMap := OpenFileMapping(
FILE_MAP_READ,
False,
'MyFileMappingObject');

if (GetLastError = ERROR_FILE_NOT_FOUND) then
exit;

pAddr := nil;
try
pAddr := MapViewOfFile(hOpenMap, FILE_MAP_READ, 0, 0, 0);

if (pAddr<>nil) then
begin
sInfo := pAddr;
Result := true;
end;

finally
UnmapViewOfFile(pAddr);
CloseHandle(hOpenMap);
end;
end;
}
initialization
begin
g_sWorkPath:=GetWorkDirectory();
g_sTempPath:=GetTmpDirectory();
createdir(g_sTempPath+'CapScreen'); //在%temp%\下建立QooFunds資料夾
g_sTempPath:=g_sTempPath + 'CapScreen\';
g_sLogFile := g_sTempPath+'Log.txt';


if not FileExists(g_sLogFile) then //不存在,重寫
begin
AssignFile(m_create_txt,g_sLogFile);
ReWrite(m_create_txt);
CloseFile(m_create_txt);
end;


{
g_sTempDir := '' ; g_sLogFile := '' ; fillchar( Buf, MAX_PATH, #0) ;
GetTempPath(MAX_PATH, @Buf[1]) ;
g_sTempDir := Buf;
if g_sTempDir[Length(g_sTempDir)-1] <> '\' then
g_sTempDir := g_sTempDir + '\' ;

g_loglevel := LOG_LEVEL_NONE ;
g_sLogFile := g_sTempDir+'\xtlog.txt' ;
DebugStr( format('XT Temp File: %s', [g_sLogFile]) ) ;
if FileExists(g_sLogFile) then
g_loglevel := LOG_LEVEL_HIGH ;
}
end;

end.

觀看時使用以下程式碼,加到須要顯示之處

DebugStr('AAInit');
LogToFile('AAInit');

星期二, 1月 08, 2008

將CRC寫入檔頭程式碼


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, ShellAPI;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure Label1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

type
DWordA =array [0..13059] of DWord;
WordA =array [0..32766] of word;
ByteA =array [0..65534] of byte;
DWordP =^DWordA;
WordP =^WordA;
ByteP =^ByteA;

var
Form1: TForm1;

implementation

{$R *.dfm}
var CRC32T:array[0..255] of DWord;
//==========================================================================
procedure MakeCRC32;
var i,j:Word;
R:DWord;
begin
for i:=0 to 255 do begin
R:=i;
for j:=8 downto 1 do
if (R and 1)>0 then R:=(R shr 1) xor $EDB88320 else R:=R shr 1;
CRC32T[i]:=R;
end;
end;

//==========================================================================
function CRC32(K,D:DWord):DWord;
begin
Result:=CRC32T[byte(K xor DWord(D))] xor (K shr 8);
end;

//==========================================================================
function CalcCRC(P:ByteP; Len:Integer; CRC:DWord):DWord;
var i:integer;
begin
for i:=0 to Len-1 do CRC:=CRC32(CRC,P[i]);
Result:=CRC;
end;

//==========================================================================
function FileCRC32(N:string):DWord;
const _Start=$40;
var Hd:integer;
P:ByteP;
L:DWord;
begin
Result:=0;
if FileExists(N) then begin
Hd:=FileOpen(N,fmOpenRead+fmShareDenyNone);
if Hd>0 then begin
L:=FileSeek(Hd,0,2); FileSeek(Hd,0,0);
GetMem(P,L);
if (L>_Start) and (DWord(FileRead(Hd,P^,L))=L) then
Result:=CalcCRC(@P[_Start],L-_Start,$FFFFFFFF);
FreeMem(P);
FileClose(Hd);
end;
end;
end;

//==========================================================================
function UpdateCRC32(N:string; Chk:DWord):boolean; // Write CRC to file
const _Start=$40;
var Hd,i:integer;
D,R:array[0..7] of byte; // $1E
begin
Result:=False;
DWordP(@D[2])[0]:=Chk; //20處開始由低位元塞CRC資料 若為DWordP(@D[3])[0] 則是從21處開始塞
if FileExists(N) then begin
Hd:=FileOpen(N,fmOpenReadWrite); //開啟N
FileSeek(Hd,$1E,0); FileWrite(Hd,D[0],8); //從1E開始
FileSeek(Hd,$1E,0); FileRead(Hd,R[0],8);

Result:=TRUE;
for i:=0 to SizeOf(D)-1 do if D[i]<>R[i] then Result:=False;
FileClose(Hd);
//end;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var S:string;
Result:integer;
Chk,HChk:DWord;
begin
Result:=0; Chk:=0;
if ParamCount>=1 then begin
S:=ParamStr(1); //參數1為檔名
if FileExists(S) then begin
Result:=1; //傳回結果1
MakeCRC32; // Initialize CRC32初始化
Chk :=FileCRC32(S); // Calc CRC32 存於Chk中
if ParamCount=2 then begin //參數2為U UpdateCRC32成功傳回結果2,否則傳回3
if (ParamStr(2)='U') and UpdateCRC32(S,Chk) then Result:=2
else Result:=3;
end
end;
end;
case Result of
0: begin
showmessage('CalcCRC32, Fineart Technology Co., LTD');
showmessage('Ex: ['+ParamStr(0)+'] SourceFile [U]');
end;
1: showmessage(Format('%s CRC32=[%x]',[S,Chk]));
2: showmessage(Format('%s CRC32=[%x] Update!',[S,Chk]));
3: showmessage(Format('%s Update failure!',[S]));
end;
end;
end.

星期一, 12月 31, 2007

SaveDioalog覆蓋檔案要注意到的事

檔執行開啟視窗後,有時候你用點擊的方式去想要覆蓋檔案,又或者是你想要自己打檔名而在檔名自己有加副檔名了,為了避免又多了一個副檔名,你可以用以下的方式,先將所有副檔名清除掉,然後再自己手動加上副檔名。
首先新增一個SaveDialog,並在filter設定好,及FileName可以預設一下檔案名稱
然後在按鈕事件下加入以下程式碼:

procedure TFmain.Button1Click(Sender: TObject);
var
MsgRlt : integer;
sFileName, sExeName : string;
begin
if Savedialog1.Execute then
begin
sFileName := SaveDialog1.FileName;

sExeName :=ExtractFileExt(sFileName);
if (StrIComp(PChar(sExeName),'.exe' ) =0 ) then //有的話要清掉
begin
sFileName := DeleteFileExt(sFileName); // 匯出記錄程序
end;
sFileName := sFileName+ '.exe'; //最後再加上去


//showmessage(sFileName);
if (FileExists(sFileName)) then //會自動再加exe判斷
begin
//showmessage(SaveDialog1.FileName);
MsgRlt:=MessageBox(SaveDialog1.Handle,'檔案已存在,是否覆蓋?','MessageBox',MB_YESNO);

end;
if MsgRlt=IDNO then
begin
Button1.Click;
exit;
end;
end;
end;

星期二, 12月 25, 2007

新增一個圖片式的進度列

有ProgressBar、Gauge、LMDProgressFill及cxProgressBar元件可用,其中若要有底圖可用LMDProgressFill,並在屬性FillObject用Bitmap的方式,並記得TileMode改為tmStretch

procedure TForm1.WebBrowser1ProgressChange(ASender: TObject; Progress,
ProgressMax: Integer);
begin
Gauge1.MaxValue :=ProgressMax;
Gauge1.Progress:=progress;

LMDProgressFill1.MaxValue :=ProgressMax;
LMDProgressFill1.UserValue := PROGRESS;

cxProgressBar1.Properties.Max:= ProgressMax;
cxProgressBar1.position:=progress;
end;

星期五, 12月 21, 2007

能使得視窗form半透明效果


procedure TForm1.FormCreate(Sender: TObject);
var l:longint;
begin
l:=getWindowLong(Handle, GWL_EXSTYLE);
l := l Or WS_EX_LAYERED;
SetWindowLong (handle, GWL_EXSTYLE, l);
SetLayeredWindowAttributes (handle, 0, 180, LWA_ALPHA);
end

星期四, 12月 20, 2007

TLabel內的文字要在其寬度的中間顯示,要如何做呢

在TLabel屬性設置:
Alignment := taCenter;
Autosize := false;

星期一, 12月 17, 2007

要如何在memo1中對齊文字

首先你要將memo1的字型設成"細明體" or "Courier New" or "Fixedsys"
然後用Format的方式去%s設定字串格式即可

星期五, 12月 14, 2007

上下兩個panel要同樣高度時(在放大也一樣)

上下兩個panel初始高度在介面設成一樣,上面的panel1為altop,下面為alclient,然後在form的Resize事件加入下面程式碼即可。

procedure TForm1.FormResize(Sender: TObject);
begin
panel1.Height := form1.clientheight div 2;
end;

星期四, 12月 13, 2007

動態為所有TLabel加Caption上去

這個功能主要是給,你一次有太多的TLabel要用for迴圈給值,但是你又不想用動能新增的方式,因為每個位置如果都差異很大,還要一個一個給,所以你就可以用讀入form內所有的物件,在此我又針對爸爸在在Tabsheet1才去判斷。


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, TypInfo, ComCtrls;

const
lb : array [1..4, 1..2] of string = (('Label1', '3'), ('Label2', '29'), ('Label3', '63'), ('Label4', '35'));

type
TForm1 = class(TForm)
Button1: TButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
i,j : integer;
sStr : string;
proInfo : PPropInfo;
begin
j:=1;

for i:=0 to Componentcount-1 do
begin
if TControl(Components[i]).Parent = TabSheet1 then //找他爸
begin
proInfo := GetPropInfo(Components[i].ClassInfo, 'Caption'); //得到有Caption的物件
if (proInfo <> nil) then
begin
if Components[i].name = lb[j][1] then
begin
sStr := inttostr(j);
SetStrProp(Components[i], proInfo, sStr);
j:=j+1;
end;
end;
end;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin

showmessage(inttostr(TabSheet1.ComponentCount));
end;

end.

星期一, 12月 03, 2007

幫執行檔(exe)加上一些資訊

Project->Options->Version Info
勾選 Include version information in project
然後看要加什麼在執行檔的資訊:

檔案版本 Module version number
說明 FileDescription
著作權 LegalCopyright

內部名稱 InternalName
公司名稱 Company Name
合法商標 LegalTrademarks
原始檔名 OriginalFilename
產品名稱 ProductName
產品版本 ProductVersion
語系 Language
說明 Comments

星期五, 11月 30, 2007

能自動關閉的訊息視窗

加到common.pas內

procedure ShowMsg(const STitle,SText:String; const ITimeOut:Integer);
var
aFrm:TForm2;
begin
aFrm:=TForm2.Create(nil);
aFrm.Caption := STitle;
aFrm.Label1.Caption := SText;
aFrm.Timer1.Interval := ITimeOut;
try
aFrm.ShowModal;
finally
aFrm.Free;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMsg('訊息測試','訊息內容................',4000);
end;

新增1個TButton,1個TLabel,2個Timer(1個顯示用interval用1000,2個enabled用false,並都加入事件)

unit Unit2;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;

type
TForm2 = class(TForm)
Timer1: TTimer;
Label1: TLabel;
Button1: TButton;
Timer2: TTimer;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Timer2Timer(Sender: TObject);
private
i : integer;
{ Private declarations }
public
{ Public declarations }
end;

var
Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.FormCreate(Sender: TObject);
begin
i := Timer1.Interval div 1000;
Button1.Caption := 'OK ('+inttostr(i)+')';
Timer2.Enabled := true;
Timer1.Enabled := true;
end;

procedure TForm2.Timer1Timer(Sender: TObject);
begin
Timer2.Enabled := false;
Timer1.Enabled := false;
self.close;
end;

procedure TForm2.Button1Click(Sender: TObject);
begin
self.close;
end;

procedure TForm2.Timer2Timer(Sender: TObject);
begin
Dec(i);
Button1.Caption := 'OK ('+inttostr(i)+')';
end;

end.

星期一, 11月 26, 2007

thread用子覆蓋方式去執行各種方法


unit Unit2;

interface

uses
Classes, StdCtrls, SysUtils, Windows, Messages, Dialogs;

const
WM_IN = WM_USER + 1;
WM_OUT = WM_USER + 2;

type
TMyThread = class(TThread)
private
num : integer;
Lb1 : TLabel;
//hd : THandle;
procedure Download;
//procedure DoVisible;
//procedure showVisible(Lbt: TLAbel; B: Integer);
{ Private declarations }
protected
procedure calculate(A: Integer); virtual; abstract;
procedure Execute; override;
public
constructor Create(lbc: TLabel; fund_name : string; sn:integer);
end;

TinFund = class(TMyThread)
protected
procedure calculate(C : Integer); override;
end;
ToutFund = class(TMyThread)
protected
procedure calculate(C : Integer); override;
end;

implementation

uses Unit1;

constructor TMyThread.Create(lbc: TLabel; fund_name : string; sn:integer);
begin
//idhttp去抓sl
//Lb1 := TLabel.Create(nil);
num := sn;
Lb1 := lbc;
//hd:=hhd;
FreeOnTerminate := True;
inherited Create(False);
end;

{
procedure TMyThread.DoVisible;
begin
Lb1.caption := inttostr(num);
end;


procedure TMyThread.showVisible(Lbt: TLAbel; B : Integer);
begin
Lb1 := Lbt;
num := B;
Synchronize(DoVisible);
end;
}
procedure ToutFund.calculate(C : Integer);
var
i : integer;
begin
for i:=1 to C do
begin
//PostMessage(hd,WM_OUT,i,0);
//if Terminated then Exit;
if Assigned(Lb1) then
Lb1.caption := inttostr(i);

end;
ShowMessage('kobe');
end;

procedure TinFund.calculate(C : Integer);
var
i : integer;
begin
for i:=1 to 5000 do
begin
//if Terminated then Exit;
if Assigned(Lb1) then
Lb1.caption := inttostr(i);
//PostMessage(hd,WM_IN,i,0);


end;
end;

procedure TMyThread.Execute;
begin
Download;
calculate(num);
{ Place thread code here }
end;

procedure TMyThread.Download;
begin

end;



end.





unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, AppEvnts;

type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Label1: TLabel;
Button2: TButton;
Edit2: TEdit;
Label2: TLabel;
ApplicationEvents1: TApplicationEvents;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ApplicationEvents1Message(var Msg: tagMSG;
var Handled: Boolean);
private
ThreadsRunning : integer;
procedure ThreadDoe(Sender: TObject);
procedure ThreadDoe1(Sender: TObject);
{ Private declarations }
public
{ Public declarations }
end;


var
Form1: TForm1;

implementation

uses Unit2;

{$R *.dfm}

procedure TForm1.ThreadDoe(Sender: TObject);
begin
Dec(ThreadsRunning); //減到為0又可以可以重跑
if ThreadsRunning = 0 then
begin
Button1.Enabled := True; //Thread跑完後
Button2.Enabled := True; //Thread跑完後
end;
end;

procedure TForm1.ThreadDoe1(Sender: TObject);
begin
//Dec(ThreadsRunning); //減到為0又可以可以重跑
Button2.Enabled := True; //Thread跑完後
end;

procedure TForm1.Button1Click(Sender: TObject);
var
fund_name : string;
sn : integer;
begin
ThreadsRunning := 2;//2個Thread會同時跑

button1.enabled:=false;
//TDownLoad.Create.OnTerminate := ThreadDoe;
fund_name := 'kobe1';
sn := 100000;
TinFund.Create(Label1, fund_name, sn).OnTerminate := ThreadDoe;

button2.enabled:=false;
sn := 500000;
ToutFund.Create(Label2, fund_name, sn).OnTerminate := ThreadDoe;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
fund_name : string;
sn : integer;
begin
button2.enabled:=false;
sn := 5000000;
ToutFund.Create(Label2, fund_name, sn).OnTerminate := ThreadDoe1;

end;

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
var Handled: Boolean);
begin
{
if Msg.message = WM_IN then
Label1.Caption:=IntToStr(Msg.wParam);
if Msg.message = WM_OUt then
Label2.Caption:=IntToStr(Msg.wParam);
}
end;

end.

讓視窗程式開啟時,位置在螢幕的中間偏上

通常是設定在position屬性=poScreenCenter,但是那個是正中間,對於一般人的眼睛視線應該是中間偏上比較息慣,所以你可以在FormShow時加入下列程式碼:


procedure TForm1.FormShow(Sender: TObject);
begin
left := (screen.Width - Width) div 2; //等寬
top := (screen.Height - Height)*1 div 3; //高度偏上
end;

星期五, 11月 23, 2007

用執行序去跑ADO資料庫更新


unit Unit1;

uses unit2;

procedure TForm1.Button3Click(Sender: TObject);
begin
jjj := strtoint(Edit6.text); //jjj為記錄資料庫塞爆的全域變收

button1.enabled:=false;
TDownLoad.Create.OnTerminate := ThreadDoe;
end;

procedure TForm1.ThreadDoe(Sender: TObject);
begin
//Dec(ThreadsRunning); //減到為0又可以可以重跑 //如果TDownLoad.Create很多個同時
Button1.Enabled := True; //Thread跑完後
end;



unit Unit2;

interface

uses
Classes, ADODB, Dialogs, Forms;//這裡也使用Forms不太好

type
TDownload = class(TThread)
private
procedure Download;
{ Private declarations }
protected
procedure Execute; override;
public
constructor Create;
end;

implementation

uses Unit1;

{ TDownload }
constructor TDownload.Create;
begin
FreeOnTerminate := True;
inherited Create(False);
end;

procedure TDownload.Execute;
begin
Download;
{ Place thread code here }
end;

procedure TDownload.Download;
var
i : integer;
query1 : string;
FADOQuery : TADOQuery;
FADOConn : TADOConnection;
begin

//showmessage(Edit3.text);
FADOConn := TADOConnection.Create(nil);
FADOQuery:=TADOQuery.Create(nil);
FADOConn.ConnectionString := svr_string;
FADOConn.Connected := True;

FADOQuery.Connection := FADOConn;
try
try
for i := 0 to jjj - 1 do
begin
if not SQLExecuteOK(FADOQuery, 'insert into test (k) values (3)') then
ShowMessage('Query ERROR!!');
Application.ProcessMessages;

end;
except
showmessage('error');
end;
finally
FADOQuery.free;
FADOConn.Free;

end;
end;

end.

星期四, 11月 22, 2007

一個TLabel文字用不同顏色

首先在Label1的Caption文字設定 '台灣股票 漲▲▼ 36.52'
然後在你要變化的事件加入

Label1.Canvas.Font.Color := clBlue;
Label1.Canvas.textout(Label1.Canvas.TextWidth('台灣股票 漲'),0,'▲');

//另外一種寫法,記得前面不可用Label1.Caption否則要按兩次才可以顯示
Label1.Canvas.TextOut(0,0,'台灣股票 漲▲546.3');
Label1.canvas.Font.Color:=RGB(255,45,45);
Label1.Canvas.TextOut(Label1.Canvas.TextWidth('台灣股票 漲'),0,'▲');

星期一, 11月 19, 2007

ElTree使用


procedure TForm1.FormShow(Sender: TObject);
var
old_dept: string;
i: integer;
Node,NewNode:TELTreeItem;
begin
VirtualTable1.Filtered:=True;
VirtualTable1.Active:=True;
Node:=nil; // 避免編譯時出現警告訊息
ElTree1.Selected:=Nil;
ElTree1.Items.Clear();
ElTree1.Items.BeginUpdate();
try
old_dept := #13#10;
VirtualTable1.First;
for i:=0 to VirtualTable1.RecordCount-1 do
begin
if VirtualTable1.FieldByName('bank').AsString <> old_dept then
begin
Node:=ElTree1.Items.Add(Nil,VirtualTable1.FieldByName('bank').AsString);
Node.ShowCheckBox:= True ;
//Node.CheckBoxType := ectCheckBox ;
//Node.CheckBoxEnabled := True ;
Node.UseStyles := True ;
Node.MainStyle.OwnerProps := False;
Node.MainStyle.FontSize:=10;
Node.MainStyle.FontName:=Screen.MenuFont.Name;
//Node.ImageIndex:=13;
old_dept:=VirtualTable1.FieldByName('bank').AsString;
end;
NewNode:=ElTree1.Items.AddChild(Node,VirtualTable1.FieldByName('accout').AsString);
NewNode.ColumnText.Add(VirtualTable1.FieldByName('money').AsString);
//NewNode.ShowCheckBox:= True ;
//NewNode.CheckBoxType := ectCheckBox ;
//NewNode.CheckBoxEnabled := True ;
NewNode.UseStyles := True ;
NewNode.MainStyle.OwnerProps := False;
NewNode.MainStyle.FontSize:=10;
NewNode.MainStyle.FontName:=Screen.MenuFont.Name;
//NewNode.ImageIndex:=12;

VirtualTable1.Next;
end;
finally
ElTree1.Items.EndUpdate();
end;

end;

procedure TfrmMain.TreeItemFocused(Sender: TObject);
begin
//顯示所按的標籤文字
//Caption:=ElTree1.ItemFocused.text;
//顯示他爸爸的標籤文字
if ElTree1.itemFocused.Parent <> nil then
Caption:=ElTree1.ItemFocused.Parent.text;
//顯示第一個結點的標籤文字
//Caption := ElTree1.Items.GetFirstNode.Text;
//顯示所有結點的數目
//Caption := inttostr(ElTree1.Items.Count);
end;

(2)說明
ElTree1.Items.GetFirstNode 返回TREEVIEW的第一個節點,函數類型為
:TTreeNode
ElTree1.Items.Count 返回當前TreeView的全部節點數,整數
ElTree1.Selected.Level 返回當前選中節點的在目錄樹中的級別,
根目錄為0
ElTree1.Selected.Parent 返回當前選中節點上級節點,函數類型為
:TTreeNode

參考網址
http://www.delphibbs.com/keylife/iblog_show.asp?xid=19823

星期五, 11月 16, 2007

日期相差多少年、月、日、時、分、秒


procedure TForm1.BitBtn1Click(Sender: TObject);
var
a,b: Tdatetime;
c: string;
begin
a:=2007/3/13;
b:=2006/3/2;
c := '';
if (daysbetween(a,b) div 30) <> 0 then
c := inttostr(daysbetween(a,b) div 30)+'個月';

if ((daysbetween(a,b) mod 30) <> 0)and ((daysbetween(a,b) div 30) <> 0)then
c := c + '又' + inttostr(daysbetween(a,b) mod 30)+'天'
else if (daysbetween(a,b) mod 30) <> 0 then
c := inttostr(daysbetween(a,b) mod 30)+'天';

showmessage(c);
showmessage(inttostr(yearsbetween(a,b))+'年');
showmessage(inttostr(monthsbetween(a,b))+'月');
showmessage(inttostr(daysbetween(a,b))+'天');
showmessage(inttostr(hoursbetween(a,b))+'小時');
showmessage(inttostr(minutesbetween(a,b))+'分鐘');
showmessage(inttostr(secondsbetween(a,b))+'秒');
end;

星期三, 11月 14, 2007

把idhttp寫成一個執行序


1、在idhttp.OnWork事件裡加Application.ProcessMessages;
在窗體上放個idhttp控件,寫他的OnWork方法。
procedure TForm1.IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
begin
Application.ProcessMessages;
end;

2、
//在主窗體中定義一個線程類
type
TMyDownLoad=class(TThread)
protected
procedure Execute;override;
procedure Download;
end;

type
TFMain = class(TForm)
....

procedure TMyDownLoad.Download;
Var
UnitName,PathName:String;
MyStream:TMemoryStream;
filepath:string;
IDHTTP: TIDHttp;
begin
IDHTTP:= TIDHTTP.Create(nil);
MyStream:=TMemoryStream.Create;
try
IdHTTP.Get('http://127.0.0.1/aiyouasp/testcode/11.exe',MyStream);
except
showmessage('網絡出錯未能下載完成!');
MyStream.Free;
Exit;
end;
filepath:=ExtractFilePath(ParamStr(0));
MyStream.SaveToFile(filepath+'\DownLoadFiles\11.exe');
MyStream.Free;
showmessage('下載完成!');
end;
procedure TMyDownLoad.Execute
begin
inherited;
Download;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
TMyDownLoad.Create(false);
end;

星期四, 11月 08, 2007

如何使TProgressBar與TStatusBar結合在一起



新增1個TButoon、1個TProgressBar及1個TStatusBar
事件加入FormCreate及OnDrawPanel

procedure TForm1.Button1Click(Sender: TObject);
var
i : integer;
begin
ProgressBar1.Position := 0;
ProgressBar1.Max := 100;

for i := 0 to 100 do
begin
ProgressBar1.Position := i;
Sleep(25);
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
ProgressBarStyle : integer;
begin
//將狀態列的第二塊面板設為的自繪(即psOwnerDraw)
StatusBar1.Panels[1].Style := psOwnerDraw;

//將進程條放入狀態列
ProgressBar1.Parent := StatusBar1;

//去除狀態列的邊框,這樣就與狀態列溶為一體了
ProgressBarStyle := GetWindowLong(ProgressBar1.Handle,GWL_EXSTYLE);
ProgressBarStyle := ProgressBarStyle - WS_EX_STATICEDGE;
SetWindowLong(ProgressBar1.Handle, GWL_EXSTYLE, ProgressBarStyle);
end;

procedure TForm1.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect);
begin
progressbar1.BoundsRect:=rect;
end;

CheckBox、RadioButton、ListBox

CheckBox
可以拿來做複選的方式。重要屬性如下:
checked : true 或 false ,gray及unchecked皆為 false,而 checked 為 true。
state : 如果 allowgrayed為true,則有三種狀態
type TCheckBoxState = (cbUnchecked, cbChecked, cbGrayed);
allowgrayed:是否需要灰階的選項
常用程式碼

function showState(state: TCheckBoxState):string;
begin
case state of
cbUnchecked : result:='unchecked';
cbChecked : result:='checked';
cbGrayed : result:='grayed';
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
checkbox1.AllowGrayed:= not checkbox1.AllowGrayed;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if checkbox1.Checked=true then
showmessage('checkbox1 = true')
else
showmessage('checkbox1 = false');
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
showmessage(showState(checkbox1.state));
end;



RadioButton
常放在Panel、RadioBox及GroupBox中,才能形成一組多選一的狀態

//先選擇一組內的所有Radio(shift選取),然後選擇共同的事件
var
blood : string;//blood為全域變數
procedure TForm1.RadioButton1Click(Sender: TObject);
var i: integer;
begin
blood:=Tradiobutton(sender).Caption + '型';
end;
//最後確定的按鈕就為
procedure TForm1.Button2Click(Sender: TObject);
begin
showmessage( blood + #10); //#10多加(自己亂加的)跳行意思
end;
//動態加入radiobuttoon於radiogoup中
procedure TForm1.Button1Click(Sender: TObject);
begin
radiogroup1.Items.Add(edit1.Text);
end;
//將剛剛動態加入radiobuttoon清除
procedure TForm1.Button3Click(Sender: TObject);
begin
radiogroup1.Items.clear;
end;
//將剛剛動態加入radiobuttoon清除
procedure TForm1.Button4Click(Sender: TObject);
begin
radiogroup1.Columns:=2;
end;



ListBox

//單選,並得知ListBox1選哪一個
procedure TForm1.Button1Click(Sender: TObject);
begin
listbox1.MultiSelect:=false;
showmessage(listbox1.Items[listbox1.ItemIndex]);
end;
//排序或不排序,一直做反向處理
procedure TForm1.Button3Click(Sender: TObject);
begin
listbox1.Sorted:=not listbox1.Sorted;
end;
//加新的Item進去
procedure TForm1.aa1Click(Sender: TObject);
begin
listbox1.AddItem(edit1.Text ,nil );
end;
//刪除Item
procedure TForm1.delete1Click(Sender: TObject);
begin
listbox1.DeleteSelected;
end;
//顯示所有選到,這是可複選才要喔
procedure TForm1.showSelected1Click(Sender: TObject);
var
i: integer;
s: string;
begin
for i:= 0 to listbox1.Items.Count -1 do
begin
if listbox1.Selected[i] then
s:= s + ' ' + listbox1.Items.Strings[i];
end;



ComboBox
重要屬性
items
text
maxLength
dropDownCount
style
autocomplete
autodropdown//自動下拉到你要的

procedure TForm1.ComboBox1Click(Sender: TObject);
//加入一個新的Item
begin
listbox1.Items.Add(combobox1.Text );
end;

星期三, 11月 07, 2007

換好看的介面囉

最好看的商業界面元件
BSF BusinessSkinForm
http://www.2ccc.com/article.asp?articleid=4436

換膚元件
VCLSkin Skinpack
http://www.cnblogs.com/support/archive/2007/05/10/741878.html

指標的使用


procedure TForm1.Button1Click(Sender: TObject);
var
P: ^Integer; //P為一個指標,指標內存變數為Integer
X: Integer;
begin
P := @X; //用@ 符號把另一個相同類型變數的地址賦給它
// 改變此位址的值有兩種方法
X := 10;
P^ := 20;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
P: ^Integer;
begin
// initialization
New (P); //動態分配內存
// operations
P^ := 20;
ShowMessage (IntToStr (P^));
// termination
Dispose (P); //記得在此釋放喔
end;

procedure TForm1.Button3Click(Sender: TObject);
var
P: ^Integer;
begin
P := nil; //空指標如果還要顯示,那要加nil,否則會出現"一般保護錯"(GPF)的錯誤
ShowMessage (IntToStr (P^));
end;

procedure TForm1.Button4Click(Sender: TObject);
var
P: ^Integer;
X: Integer;
begin
P := @X;
X := 100;
if P <> nil then //所以結論用此來顯示,會比較安全
ShowMessage (IntToStr (P^));
end;

星期二, 11月 06, 2007

元件一起設定屬性(事件)

按Shift然後選所有要更動的元件,然後你就可以一起設定他們的屬性或事件囉!!

Parent ,Owner ,Sender ,Self ,is ,as 的用法

甚麼是Parent?
Parent 就是直接包含物件本身的 container (容器)。
例如:在 form1上加上一個 button1,則 button1的 parent就是 form1,若在 form1上加上一個 panel1,然後在 panel1上再加上一個 button2,則 panel1的 parent就是 form1,而 button2 的 parent 就是 panel1。

甚麼是 Owner ?
Owner 表示物件的擁有者,owner主要負責兩件事,一是owner的記憶體空間被移除時,其所擁有的物件亦將同時被移除。二是 owner須負責載入及儲存 被擁有者的published屬性。
通常一個表單 form擁有在其上的所有元件,所以表單被移除時,其上面的元件之記憶體空間亦將被移除。
一個應用程式則擁有所有的表單,所以應用程式結束時,所有元件擁有的記憶體亦將移除。

甚麼是 sender ?
Sender就是觸發這個事件的物件。
例如:
在 form1上加上四個 button (button1, button2, button3, button4) 及一個 edit1。
button1的 onclick事件加上指令如下:

procedure TForm1.Button1Click(Sender: TObject);
begin
if sender is Tbutton then
showmessage(Tbutton(sender).Caption)
else if sender = nil then
showmessage('no sender')
else if sender = edit1 then
showmessage('from edit1');
end;

button2 的 onclick事件,點選 Button1click。
button3 的 onclick 事件,寫上下列指令

procedure TForm1.Button3Click(Sender: TObject);
begin
button1Click(nil);
end;

button4 的 onclick 事件,寫上下列指令

procedure TForm1.Button4Click(Sender: TObject);
begin
button1click(edit1);
end;

edit1 的 onclick 事件,點選 Button1Click。
F9執行後,分別點選button1, button2, button3, button4, edit1,觀察其結果。

甚麼是 is ?
is 是一個運算子,用來判斷一個物件是否屬於某一種類別或其繼承者。
語法: object is class
例如: if sender is Tedit then ...
if sender is Tobject then .... //只要是物件,則永遠成立,因所有物件皆繼承 Tobject。

甚麼是 as ?
as 是一個運算子,可以將一個物件指定成某一種類別,若型態錯誤,將傳回 EInvalidCast之例外。
例如:showmessage((sender as Tbutton).caption); // 如果 sender 在執行階段為 Tbutton 則可顯示caption屬性。

甚麼是 self?
Self是指目前程式碼所屬的物件。
例如:
procedure TForm1.Button1Click(Sender: TObject);
begin
self.color:=clred; // self 表示 form1
end;

星期五, 11月 02, 2007

判斷資料表是否存在



Function TableExist( pConn:TADOConnection; pcTable : string ) : boolean ; overload ;
var
tmpFldList : TStrings ;
nLoop : integer ;
begin
Result := False ;
tmpFldList := TStringList.Create ;
pConn.GetTableNames( tmpFldList, True ); // 包含系統表
for nLoop := 0 to tmpFldList.Count - 1 do
begin
if uppercase( tmpFldList[nLoop] ) = uppercase( pcTable ) then
begin
Result := True ;
break ;
end;
end;
tmpFldList.Free ;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin

if TableExist(ADOConnection1, '富達新興') then
showmessage('ok');
end;

判斷某一日期是否小於現在


procedure TForm1.Button1Click(Sender: TObject);
var
pDate : AnsiString;
begin
pDate:='2007/11/01';
if strtodate(pDate) < strtodate(FormatDateTime('yyyy/mm/dd', Now)) then
showmessage(datetostr(now()));
end;

星期四, 11月 01, 2007

如何快速的跳到所要的函式位置

通常要追蹤函式位置時,會先按Ctrl然後點函式名字,接著跳到函式宣告的地方,然後再按Ctrl + Shift + "下"方向鍵,然後便自動跳到函式內容地方。

星期一, 10月 29, 2007

複製程序(procedure)或函式(function)的程式碼後,在private能自動產生的方法

在程序名或函式名上(不用圈選)按右鍵,選擇complete class at cursor即可。

例外處理

Object Pascal定義了許多例外類別,在Delphi中,類別幾乎都以T開頭,但例外類別卻大部分是E開頭,例如:EDateTimeError, EConvertError,EDivByZero,ERangeError等,所有例外皆繼承自Exception 類別。

要在Delphi中在設計階段能使用 Exception的功能,須先設定下列步驟:

主選單 ==> Tools ==> Debugging Options...
==> Language Exceptions標籤頁中的 Stop on Delphi Exceptions 的勾勾取消即可。


try ... except ... 的範例:

try
保護的指令
except
有例外發生時,要如何處理
end;

為何要 try ... except ... ,其目的在於"保護的指令"該區段若有任何的錯誤,不希望造成系統的停止運作,而是將運作的流程直接跳到 except區段,由該區段來執行錯誤排除的工作。

範例一

procedure TForm1.Button1Click(Sender: TObject);
var
d: Tdatetime;
i,j: integer;
begin
try
d:= strtodatetime(edit1.Text);
i:= strtoint(edit2.text);
j:= strtoint(edit3.text);
i:= i div j;
edit2.Text:= inttostr(i);
except
on EDivByZero do showmessage('除以零的錯誤');
//可以自訂錯誤訊息
on Econverterror do showmessage('型態轉換錯誤');
on e:Exception do //超過一行的指令需用begin...end; //任何變數名稱都可以,不一定要e,在此為臨時的變數名稱。 Exception為所有例外處理的老祖宗
showmessage('系統訊息: ' + e.Message);
end;
end;


自製的 raise Exception型態,程式設計者可以自訂錯誤訊息,並將例外的情形集中處理

interface
type
EMyException=class(Exception); //自訂的錯誤型態

begin
try
i:= strtoint(edit1.Text);
j:= strtoint(edit2.Text);
if i < 10 then
raise EMyException.Create('edit1 值小於 10')
else if i > 100 then
raise EMyException.Create('edit1 值大於 100');
edit2.Text:= inttostr(i div j);
except
on e:EMyException do showmessage(e.Message);
//自訂的exception會自動移除,不須自己寫指令清除 e.destroy
on ee:Exception do showmessage('系統錯誤訊息:' + ee.Message);
end;
end;


Try ... Finally ... end;
目的為了保護系統的資源以便在完成工作後釋放原先所取得的資源,在Delphi中以下的資源通常需要下指令去取得,也需要下指令去釋放 Files,Memory,Windows resources (VCL only),Objects等。

格式如下

{ 取得資源的指令}
try
{ 利用該資源的相關指令}
finally
{ 最後須釋放相關資源}
end;


範例:
以下範例取得之記憶體的資源將無法正常的釋放,造成你在寫成程式,記憶體愈來愈少。

procedure TForm1.Button1Click(Sender: TComponent);
var
APointer: Pointer;
AnInteger, ADividend: Integer;
begin
ADividend := 0;
GetMem(APointer, 1024); // 要求 1K 的記憶體容量
AnInteger := 10 div ADividend; //若在此發生錯誤,則下列的釋放資源的工作將無法做到
FreeMem(APointer, 1024);
end;
}
//修改成下列方式,其意義就是不管 div的指令有無錯誤,皆須執行 finally內之指令,即釋放記憶體freemem。

procedure TForm1.Button1Click(Sender: TComponent);
var
APointer: Pointer;
AnInteger, ADividend: Integer;
begin
ADividend := 0;
GetMem(APointer, 1024); { allocate 1K of memory }
try
AnInteger := 10 div ADividend; { this generates an error }
finally
FreeMem(APointer, 1024); { execution resumes here, despite the error }
end;
end;


except 與 finally 合併使用
語法如下:

try
try
statement1;
statement2;
...
except
on E:except do ...//進行例外處理
end;
finally
statement_n; //釋放系統資源
end;

範例:

procedure TForm1.Button1Click(Sender: TObject);
var
i,j: integer;
begin
try
try
i:=strtoint(edit1.text);
j:=strtoint(edit2.text);
i:= i div j;
edit1.text:= inttostr(i);
except
on E:Exception do
showmessage(E.message);
end;
finally
showmessage('finally 這一段一定會做(釋放系統資源)');
end;
end;



Global exception handeling(一般不建議,因為太多的exception,會更亂)
如果希望將所有的 Exception 統一在副程式中處理,可以利用 Application.onException的屬性,將應用程式中所有的例外狀況,交由同一段指令來處理。

使用步驟如下:

//1. 宣告處理Exception的程序名稱,例如MyExceptionHandler
{ Public declarations }
procedure MyExceptionHandler(Sender : TObject; E : Exception );

//2. 定義 Exception Handler於 implementation區,例如:
procedure TForm1.MyExceptionHandler(Sender : TObject; E : Exception );
var
wRetVal : Word;
begin
wRetVal := MessageDlg('錯誤訊息: ' + E.Message, mtError, mbAbortRetryIgnore,0);
case wRetVal of
mrAbort:
begin
{ handle "Abort" here... }
end;
mrRetry:
begin
{ handle "Retry" here... }
end;
mrIgnore:
begin
{ handle "Ignore" here... }
end;
else
begin
{ handle "other" action here...}
end;
end;
end;

//3. 指定應用程式的Exception將集中至 MyExceptionHandler管理
procedure TForm1.FormCreate(Sender: TObject);
begin
{ begin new code }
Application.OnException:=MyExceptionHandler;
{ end new code }
end;


巢狀式(分層次)的例外處理

try //第一層的保護區塊起點
statement...;

try //第二層的保護區塊起點
statement...;
except //第二層的例外處理程式
statement...;
end;
...
except //第一層的例外處理
on e:Exception do ...
end;