تعریف آرایه های ثابت (Constant) در Delphi
با این روش:
type
TShopItem = record
Name : string;
Price : currency;
end;
const
Days : array[0..6] of string =
(
'Sun', 'Mon', 'Tue', 'Wed',
'Thu', 'Fri', 'Sat'
) ;
CursorMode : array[boolean] of TCursor =
(
crHourGlass, crSQLWait
) ;
Items : array[1..3] of TShopItem =
(
(Name : 'Clock'; Price : 20.99),
(Name : 'Pencil'; Price : 15.75),
(Name : 'Board'; Price : 42.96)
) ;
2 ضمیمه
دو کد نمونه برای کار با آرایه هایی از کامپوننتها
تشخیص اتصال (connection) به اینترنت (internet)
procedure TForm1.Button1Click(Sender: TObject) ;
function FuncAvail(_dllname, _funcname: string;
var _p: pointer): boolean;
{return True if _funcname exists in _dllname}
var _lib: tHandle;
begin
Result := false;
if LoadLibrary(PChar(_dllname)) = 0 then exit;
_lib := GetModuleHandle(PChar(_dllname)) ;
if _lib <> 0 then begin
_p := GetProcAddress(_lib, PChar(_funcname)) ;
if _p <> NIL then Result := true;
end;
end;
{
Call SHELL32.DLL for Win < Win98
otherwise call URL.dll
}
{button code:}
var
InetIsOffline : function(dwFlags: DWORD):
BOOL; stdcall;
begin
if FuncAvail('URL.DLL', 'InetIsOffline',
@InetIsOffline) then
if InetIsOffLine(0) = true
then ShowMessage('Not connected')
else ShowMessage('Connected!') ;
end;
دانلود (download) فایل از اینترنت با نمایش درصد پیشرفت (progress indicator)
uses ExtActns, ...
type
TfrMain = class(TForm)
...
private
procedure URL_OnDownloadProgress
(Sender: TDownLoadURL;
Progress, ProgressMax: Cardinal;
StatusCode: TURLDownloadStatus;
StatusText: String; var Cancel: Boolean) ;
...
implementation
...
procedure TfrMain.URL_OnDownloadProgress;
begin
ProgressBar1.Max:= ProgressMax;
ProgressBar1.Position:= Progress;
end;
function DoDownload;
begin
with TDownloadURL.Create(self) do
try
URL:='http://z.about.com/6/g/delphi/b/index.xml';
FileName := 'c:\ADPHealines.xml';
OnDownloadProgress := URL_OnDownloadProgress;
ExecuteTarget(nil) ;
finally
Free;
end;
end;
خواندن (Get) لیست favorites از IE
function GetIEFavourites
(const favpath: string):TStrings;
var
searchrec:TSearchrec;
str:TStrings;
path,dir,filename:String;
Buffer: array[0..2047] of Char;
found:Integer;
begin
str:=TStringList.Create;
try
path:=FavPath+'\*.url';
dir:=ExtractFilepath(path) ;
found:=FindFirst(path,faAnyFile,searchrec) ;
while found=0 do begin
SetString(filename, Buffer,
GetPrivateProfileString('InternetShortcut',
PChar('URL'), NIL, Buffer, SizeOf(Buffer),
PChar(dir+searchrec.Name))) ;
str.Add(filename) ;
found:=FindNext(searchrec) ;
end;
found:=FindFirst(dir+'\*.*',faAnyFile,searchrec) ;
while found=0 do begin
if ((searchrec.Attr and faDirectory) > 0)
and (searchrec.Name[1]<>'.') then
str.AddStrings(GetIEFavourites
(dir+'\'+searchrec.name)) ;
found:=FindNext(searchrec) ;
end;
FindClose(searchrec) ;
finally
Result:=str;
end;
end;
procedure TForm1.Button1Click(Sender: TObject) ;
var pidl: PItemIDList;
FavPath: array[0..MAX_PATH] of char;
begin
SHGetSpecialFolderLocation(Handle, CSIDL_FAVORITES, pidl) ;
SHGetPathFromIDList(pidl, favpath) ;
ListBox1.Items:=GetIEFavourites(StrPas(FavPath)) ;
end;
تغییر صفحه Home Page در IE
uses Registry;
...
function SetIEHomePage(PageName: string): Boolean;
begin
with TRegistry.Create do
try
RootKey := HKEY_CURRENT_USER;
OpenKey('Software\Microsoft\Internet Explorer\Main', False) ;
try
WriteString('Start Page', PageName) ;
Result := True;
except
Result := False;
end;
CloseKey;
finally
Free;
end;
end;
//Usage:
SetIEHomePage('http://delphi.about.com')
بدست آوردن لیست NetWork Drive ها
function GetNetworkDriveMappings (SList: TStrings): integer;
var
c: Char;
ThePath: string;
MaxNetPathLen: DWord;
begin
SList.Clear;
MaxNetPathLen := MAX_PATH;
SetLength(ThePath, MAX_PATH) ;
for c := 'A' to 'Z' do
if WNetGetConnection(PChar('' + c + ':'), PChar(ThePath),MaxNetPathLen) = NO_ERROR then sList.Add(c + ': ' + ThePath) ;
Result := SList.Count;
end;
تعیین زمان در حال اجرا بودن windows
در این کد، از تابع GetTickCount که از توابع API می باشد، استفاده شده است. این تابع میلی ثانیه های سپری شده از زمان اجرای ویندوز را بر می گرداند. این کد این زمان را به فرمت مناسب تری تبدیل می کند. هدف از گذاشتن این کدها بیشتر آشنایی با چگونگی کار با توابع مختلف دلفی و API می باشد.
function WindowsUpTime : string ;
function MSecToTime(mSec: Integer): string;
const
secondTicks = 1000;
minuteTicks = 1000 * 60;
hourTicks = 1000 * 60 * 60;
dayTicks = 1000 * 60 * 60 * 24;
var
D, H, M, S: string;
ZD, ZH, ZM, ZS: Integer;
begin
ZD := mSec div dayTicks;
Dec(mSec, ZD * dayTicks) ;
ZH := mSec div hourTicks;
Dec(mSec, ZH * hourTicks) ;
ZM := mSec div hourTicks;
Dec(mSec, ZM * minuteTicks) ;
ZS := mSec div secondTicks;
D := IntToStr(ZD) ;
H := IntToStr(ZH) ;
M := IntToStr(ZM) ;
S := IntToStr(ZS) ;
Result := D + '.' + H + ':' + M + ':' + S;
end;
begin
result := MSecToTime(GetTickCount) ;
end;
تشخیص Administrator بودن کاربر (user)
unit WindowsUser;
interface
uses Windows;
//returns True if the currently logged Windows user has Administrator rights
function IsWindowsAdmin: Boolean;
implementation
const
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)) ;
const
SECURITY_BUILTIN_DOMAIN_RID = $00000020;
DOMAIN_ALIAS_RID_ADMINS = $00000220;
function IsWindowsAdmin: Boolean;
var
hAccessToken: THandle;
ptgGroups: PTokenGroups;
dwInfoBufferSize: DWORD;
psidAdministrators: PSID;
g: Integer;
bSuccess: BOOL;
begin
Result := False;
bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken) ;
if not bSuccess then
begin
if GetLastError = ERROR_NO_TOKEN then
bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken) ;
end;
if bSuccess then
begin
GetMem(ptgGroups, 1024) ;
bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize) ;
CloseHandle(hAccessToken) ;
if bSuccess then
begin
AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators) ;
for g := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[g].Sid) then
begin
Result := True;
Break;
end;
FreeSid(psidAdministrators) ;
end;
FreeMem(ptgGroups) ;
end;
end;
end.
یافتن MyDouments برای کاربر جاری
uses shlobj, ...
function GetMyDocuments: string;
var
r: Bool;
path: array[0..Max_Path] of Char;
begin
r := ShGetSpecialFolderPath(0, path, CSIDL_Personal, False) ;
if not r then raise Exception.Create('Could not find MyDocuments folder location.') ;
Result := Path;
end;
procedure TMyForm.FormCreate(Sender: TObject) ;
var
myDocFolder : string;
begin
myDocFolder := GetMyDocuments;
ShowMessage(Format('MyDocuments folder for the current user: "%s"',[myDocFolder])) ;
end;
how Can I Read a unicode text file in Delphi?
procedure TForm1.Button1Click(Sender: TObject);
var
F: TStream;
UnicodeString: WideString;
UnicodeSign: Word;
FileName: string;
FileSize: Cardinal;
begin
FileName := 'SchedLgU.Txt';
F := TFileStream.Create(FileName, fmOpenRead);
try
FileSize := F.Size;
if FileSize >= SizeOf(UnicodeSign) then
begin
F.ReadBuffer(UnicodeSign, SizeOf(UnicodeSign));
if UnicodeSign = $FEFF then
begin
Dec(FileSize, SizeOf(UnicodeSign));
SetLength(UnicodeString, FileSize div SizeOf(WideChar));
F.ReadBuffer(UnicodeString[1], FileSize);
// now UnicodeString contains Unicode string read from stream
Memo1.Lines.Text := UnicodeString;
end
else
// not a Unicode format;
Memo1.Lines.LoadFromFile(FileName);
end;
finally
F.Free;
end;
end;
تابعی جهت بدست آوردن ولوم سریالِ دیسک
با این تابع می توانید ولوم سریالِ دیسک را بدست آوردید
Function GetDiscVolSerialID(cDriveName : char) :DWORD;
var
dwtemp1,dwtemp2 : DWORD;
begin
GetVolumeInformation(PChar(cDriveName + ':\'),Nil,0,@Result , dwtemp1 ,dwtemp2,Nil, 0);
end;
چگونه برنامه مان فقط یک نسخه اجرا شود
برای اینکه بعد از اجرای برنامه اگر کاربر روی آیکن برنامه کلیک کرد ، همزمان چند نسخه از اون اجرا نشه می تونیم فایل DPR پروژه رو بصورت زیر تغییر بدیم
uses
windows;
var
hmutex : THandle;
begin
hmutex := CreateMutex(nil,false,'OneCopyMutex');
if waitforsingleobject(hmutex, 0) <> wait_timeout then
begin
Application.Initialize;
.
.
.
Application.Run;
end;
end.