DELPHI编程技巧集锦3Word格式.docx
《DELPHI编程技巧集锦3Word格式.docx》由会员分享,可在线阅读,更多相关《DELPHI编程技巧集锦3Word格式.docx(13页珍藏版)》请在冰豆网上搜索。
VER_PLATFORM_WIN32_NT:
Do_SomeThingElse;
end;
end;
B内存知多少?
下面介绍一种方法可以决定系统内存的多少、使用状态等信息。
更重要的是,应用程序可以利用这项技术来决定客户机的可用内存的大小,利用这些信息,应用程序可以动态地优化程序的性能。
例如,如果有足够的内存可以利用双缓存优化位图的操作。
利用WindowsAPI函数GlobalMemoryStatus可以完成上述功能。
GlobalMemoryStatus接收一个类型为TMemoryStatus的变参,通过这个参数就可以获得Windows当前的内存状态。
TMemoryStatus的结构如下:
typedefstruct_MEMORYSTATUS{//mst
DWORDdwLength;
//sizeof(MEMORYSTATUS),该记录结构的大小
DWORDdwMemoryLoad;
//使用内存所占百分比
DWORDdwTotalPhys;
//物理内存的字节数
DWORDdwAvailPhys;
//自由物理可用内存字节数
DWORDdwTotalPageFile;
//页文件字节数
DWORDdwAvailPageFile;
//页文件的自由字节数
DWORDdwTotalVirtual;
//地址空间的用户字节数
DWORDdwAvailVirtual;
//自由用户字节数
}MEMORYSTATUS,*LPMEMORYSTATUS;
下面是使用GlobalMemoryStatus函数的一个例子:
MemoryStatus:
TMemoryStatus;
MemoryStatus.dwLength:
=sizeof(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Label1.Caption:
='
TotalPhysicalMemory:
'
+IntToStr(MemoryStatus.dwTotalPhys);
C获得消逝时间
在测试硬件或软件的效率时或跟踪用户的响应速度时,需要测定消逝的时间。
多数程序员使用一个TDateTime变量和Now函数来实现测定消逝时间的目的。
但是,一种更简单的方法是使用WindowsAPI函数GetTickCount。
GetTickCount函数返回从启动Windows后消逝的毫秒数。
如果函数成功地返回,返回值就是从启动Windows后消逝的毫秒数。
下面是一个使用实例:
i:
longint;
StartTime,EndTime:
Double;
const
CLOCK_TICK:
Double=1000;
i:
=0;
StartTime:
=GetTickCount;
while(i<
10000000)doi:
=i+1;
EndTime:
=GetTickCount-StartTime;
ShowMessage(Format('
消逝时间:
%0.2f秒'
[EndTime/CLOCK_TICK]));
D隐藏/显示Windows95的任务栏
想不想让你编写的Delphi程序具有隐藏/显示Windows95任务栏的功能,在程序中使用下面的两个过程就可以实现这一功能。
procedurehideTaskbar;
varwndHandle:
THandle;
wndClass:
array[0..50]ofChar;
StrPCopy(@wndClass[0],'
Shell_TrayWnd'
);
wndHandle:
=FindWindow(@wndClass[0],nil);
//隐藏任务栏
ShowWindow(wndHandle,SW_HIDE);
procedureshowTaskbar;
//显示任务栏
ShowWindow(wndHandle,SW_RESTORE);
E捕获文件的日期和时间标志
希望显示文件的日期和时间标志吗?
Delphi中没有一个简单的函数来完成这项功能,但是我们可以将两个函数结合起来实现这一功能。
首先,FileGetDate函数返回文件的DOS日期和时间,然后,FileDateToDateTime函数将日期和时间转换为TDateTime类型的变量,最后,DateTimeToStr过程将TDateTime类型的变量转换为字符串。
实例如下:
procedureTForm1.Button1
TheFileDate:
string;
Fhandle:
integer;
FHandle:
=FileOpen(YourFileName,0);
try
TheFileDate:
=
DateTimeToStr(FileDateToDateTime(FileGetDate(FHandle)));
finally
FileClose(FHandle);
使用DateTimeToStr的格式化参数可以调整输出结果的形式。
即使你不需要显示日期和时间,也可以使用这项技术比较和计算文件日期。
F避免驱动器A没有准备好错误(NotReadyerror)
当你的程序存取A驱动器时,可能会被'
DriveNotReady'
系统错误所中断,可以使用下面的函数来测试驱动器,以避免这种情况发生,代码如下:
functionDiskInDrive(Drive:
Char):
Boolean;
ErrorMode:
word;
Drive:
=UpCase(Drive);
ifnot(Drivein['
A'
..'
Z'
])then
raiseEConvertError.Create('
NotavaliddriveID'
ErrorMode:
=SetErrorMode(SEM_FailCriticalErrors);
ifDiskSize(Ord(Drive)-$40)=-1then
DiskInDrive:
=False
else
=True;
SetErrorMode(ErrorMode);
本函数的工作原理是:
首先将驱动器符转换为大写字母,然后关闭系统错误报告功能,执行磁盘操作,操作成功返回True,表明驱动器里存在磁盘;
操作失败返回False,表明发生错误,函数结束时打开系统错误报告功能。
G隐藏应用程序
假如你不仅想让应用程序隐藏窗体,同时不想让应用程序在任务栏上显示,可以使用如下命令:
ShowWindow(Application.handle,SW_HIDE);
这条命令对使用托盘区(SystemTray)图标来激活的应用程序十分有用。
H重定向DOS应用程序
有时,你需要重定向一个DOS应用程序。
下面的代码可以帮助你完成这项工作:
{---------------------CreateDOSProcessRedirected------------------
Description:
executesa(DOS!
)appdefinedintheCommandLine
parameterredirectedtotakeinputfromInputFile
andgiveoutputtoOutputFile
Result:
Trueonsuccess
Parameters:
CommandLine:
thecommandlinefortheapp,
includingitsfullpath
InputFile:
theasciifilewherefromtheapp
takesinput
OutputFile:
theasciifiletowhichtheapp'
s
outputisredirected
ErrMsg:
additionalerrormessagestring.
Canbeempty
Errorchecking:
YES
Target:
Delphi2,3,4
Author:
TheodorosBebekis,emailbebekis@otenet.gr
Notes:
Examplecall:
CreateDOSProcessRedirected('
C:
\MyDOSApp.exe'
\InputPut.txt'
\OutPut.txt'
Please,recordthismessage'
)
------------------------------------------------------------------}
functionCreateDOSProcessRedirected(constCommandLine,InputFile,
OutputFile,ErrMsg:
string):
boolean;
ROUTINE_ID='
[function:
CreateDOSProcessRedirected]'
;
OldCursor:
TCursor;
pCommandLine:
array[0..MAX_PATH]ofchar;
pInputFile,
pOutPutFile:
StartupInfo:
TStartupInfo;
ProcessInfo:
TProcessInformation;
SecAtrrs:
TSecurityAttributes;
hAppProcess,
hAppThread,
hInputFile,
hOutputFile:
=False;
{CheckforInputFileexistence}
ifnotFileExists(InputFile)
then
raiseException.CreateFmt(ROUTINE_ID+#10+#10+
Inputfile*%s*'
+#10+
doesnotexist'
+#10+#10+
ErrMsg,[InputFile]);
{Savethecursor}
=Screen.Cursor;
Screen.Cursor:
=crHourglass;
{CopytheparameterPascalstringstonullterminated
strings}
StrPCopy(pCommandLine,CommandLine);
StrPCopy(pInputFile,InputFile);
StrPCopy(pOutPutFile,OutputFile);
TRY
{PrepareSecAtrrsstructurefortheCreateFilecalls.
ThisSecAttrsstructureisneededinthiscasebecause
wewantthereturnedhandlecanbeinheritedbychild
process.ThisistruewhenrunningunderWinNT.
AsforWin95,thedocumentationisquiteambiguous}
FillChar(SecAtrrs,SizeOf(SecAtrrs),#0);
SecAtrrs.nLength:
=SizeOf(SecAtrrs);
SecAtrrs.lpSecurityDescriptor:
=nil;
SecAtrrs.bInheritHandle:
{Createtheappropriatehandlefortheinputfile}
hInputFile:
=CreateFile(
pInputFile,
pointertonameofthefile}
GENERIC_READorGENERIC_WRITE,
access(read-write)mode}
FILE_SHARE_READorFILE_SHARE_WRITE,
sharemode}
@SecAtrrs,
pointertosecurityattributes}
OPEN_ALWAYS,
{howtocreate}
FILE_ATTRIBUTE_NORMAL
orFILE_FLAG_WRITE_THROUGH,
{fileattributes}
0);
handletofilewithattributestocopy}
{IshInputFileavalidhandle?
}
ifhInputFile=INVALID_HANDLE_VALUE
then
raiseException.CreateFmt(ROUTINE_ID+#10+#10+
WinApifunctionCreateFilereturnedan'
+
invalidhandlevalue'
fortheinputfile*%s*'
{Createtheappropriatehandlefortheoutputfile}
hOutputFile:
pOutPutFile,
GENERIC_READorGENERIC_WRITE,
FILE_SHARE_READorFILE_SHARE_WRITE,
@SecAtrrs,
CREATE_ALWAYS,
{howtocreate}
orFILE_FLAG_WRITE_THROUGH,
fileattributes}
{IshOutputFileavalidhandle?
ifhOutputFile=INVALID_HANDLE_VALUE
+
fortheoutputfile*%s*'
ErrMsg,[OutputFile]);
{PrepareStartupInfostructure}
FillChar(StartupInfo,SizeOf(StartupInfo),#0);
StartupInfo.cb:
=SizeOf(StartupInfo);
StartupInfo.dwFlags:
=STARTF_USESHOWWINDOWor
STARTF_USESTDHANDLES;
StartupInfo.wShowWindow:
=SW_HIDE;
StartupInfo.hStdOutput:
=hOutputFile;
StartupInfo.hStdInput:
=hInputFile;
{Createtheapp}
Result:
=CreateProcess(nil,
{pointertonameofexecutablemodule}
pCommandLine,
{pointertocommandlinestring}
nil,
{pointertoprocesssecurityattributes}
{pointertothreadsecurityattributes}
True,
{handleinheritanceflag}
HIGH_PRIORITY_CLASS,
{creationflags}
{pointertonewenvironmentblock}
{pointertocurrentdirectoryname}
StartupInfo,
{pointertoSTARTUPINFO}
ProcessInfo);
{pointertoPROCESS_INF}
{waitfortheapptofinishitsjobandtakethe
handlestofreethemlater}
ifResult
begin
WaitforSingleObject(ProcessInfo.hProcess,INFINITE);
hAppProcess:
=ProcessInfo.hProcess;
hAppThread:
=ProcessInfo.hThread;
end
else
raiseException.Create(ROUTINE_ID+#10+#10+
Functionfailure'
ErrMsg);
FINALLY
{Closethehandles.
Kernelobjects,liketheprocessandthefiles
wecreatedinthiscase,aremaintainedbyausage
count.So,forcleaninguppurposes,wehaveto
closethehandlestoinformthesystemthatwedon'
t
needtheobjectsanymore}
ifhOutputFile<
>
0thenCloseHandle(hOutputFile);
ifhInputFile<
0thenCloseHandle(hInputFile);
ifhAppThread<
0thenCloseHandle(hAppThread);
ifhAppProcess<
0thenCloseHandle(hAppProcess);
{Restoretheoldcursor}
Screen.Cursor:
=OldCursor;
END;
{CreateDOSProcessRedirected}