DELPHI编程技巧集锦3.docx
- 文档编号:9164912
- 上传时间:2023-02-03
- 格式:DOCX
- 页数:13
- 大小:19.41KB
DELPHI编程技巧集锦3.docx
《DELPHI编程技巧集锦3.docx》由会员分享,可在线阅读,更多相关《DELPHI编程技巧集锦3.docx(13页珍藏版)》请在冰豆网上搜索。
DELPHI编程技巧集锦3
DELPHI编程技巧集锦(3)
董占山
(中国农科院棉花研究所,河南安阳,455112)
五、操作系统相关的技巧
A如何决定Windows的版本
Windows具有多个版本,一个应用程序或者具有运行在多个Windows版本下的灵活性,或者通过条件编译指令,编译成只能在一个操作平台下工作。
下面介绍一种方法,可以使应用程序能动态地决定Windows操作系统的版本。
应用程序通过调用WindowsAPI函数GetVersionEx可以获得Windows的版本信息,该函数使用一个TOSVersionInfo类的变参,所有Windows版本信息就包含在其中,其结构如下:
typedefstruct_OSVERSIONINFO{
DWORDdwOSVersionInfoSize;//结构的大小
DWORDdwMajorVersion;//主版本
DWORDdwMinorVersion;//副版本
DWORDdwBuildNumber;//建立版本
DWORDdwPlatformId;//操作平台标识
TCHARszCSDVersion[128];//版本标识字符串
}OSVERSIONINFO;
下面是使用该函数的一个例子:
procedureTForm1.Button1Click(Sender:
TObject);
var
VersionInfo:
TOSVersionInfo;
begin
VersionInfo.dwOSVersionInfoSize:
=Sizeof(TOSVersionInfo);
GetVersionEx(VersionInfo);
caseVersionInfo.dwPlatformIDof
VER_PLATFORM_WIN32S:
Do_SomeThing;
VER_PLATFORM_WIN32_WINDOWS:
Do_SomeOtherThing;
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函数的一个例子:
procedureTForm1.Button1Click(Sender:
TObject);
var
MemoryStatus:
TMemoryStatus;
begin
MemoryStatus.dwLength:
=sizeof(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Label1.Caption:
='TotalPhysicalMemory:
'+IntToStr(MemoryStatus.dwTotalPhys);
end;
C获得消逝时间
在测试硬件或软件的效率时或跟踪用户的响应速度时,需要测定消逝的时间。
多数程序员使用一个TDateTime变量和Now函数来实现测定消逝时间的目的。
但是,一种更简单的方法是使用WindowsAPI函数GetTickCount。
GetTickCount函数返回从启动Windows后消逝的毫秒数。
如果函数成功地返回,返回值就是从启动Windows后消逝的毫秒数。
下面是一个使用实例:
procedureTForm1.Button1Click(Sender:
TObject);
var
i:
longint;
StartTime,EndTime:
Double;
const
CLOCK_TICK:
Double=1000;
begin
i:
=0;
StartTime:
=GetTickCount;
while(i<10000000)doi:
=i+1;
EndTime:
=GetTickCount-StartTime;
ShowMessage(Format('消逝时间:
%0.2f秒',[EndTime/CLOCK_TICK]));
end;
D隐藏/显示Windows95的任务栏
想不想让你编写的Delphi程序具有隐藏/显示Windows95任务栏的功能,在程序中使用下面的两个过程就可以实现这一功能。
procedurehideTaskbar;
varwndHandle:
THandle;
wndClass:
array[0..50]ofChar;
begin
StrPCopy(@wndClass[0],'Shell_TrayWnd');
wndHandle:
=FindWindow(@wndClass[0],nil);
//隐藏任务栏
ShowWindow(wndHandle,SW_HIDE);
end;
procedureshowTaskbar;
varwndHandle:
THandle;
wndClass:
array[0..50]ofChar;
begin
StrPCopy(@wndClass[0],'Shell_TrayWnd');
wndHandle:
=FindWindow(@wndClass[0],nil);
//显示任务栏
ShowWindow(wndHandle,SW_RESTORE);
end;
E捕获文件的日期和时间标志
希望显示文件的日期和时间标志吗?
Delphi中没有一个简单的函数来完成这项功能,但是我们可以将两个函数结合起来实现这一功能。
首先,FileGetDate函数返回文件的DOS日期和时间,然后,FileDateToDateTime函数将日期和时间转换为TDateTime类型的变量,最后,DateTimeToStr过程将TDateTime类型的变量转换为字符串。
实例如下:
procedureTForm1.Button1
var
TheFileDate:
string;
Fhandle:
integer;
begin
FHandle:
=FileOpen(YourFileName,0);
try
TheFileDate:
=
DateTimeToStr(FileDateToDateTime(FileGetDate(FHandle)));
finally
FileClose(FHandle);
end;
end;
使用DateTimeToStr的格式化参数可以调整输出结果的形式。
即使你不需要显示日期和时间,也可以使用这项技术比较和计算文件日期。
F避免驱动器A没有准备好错误(NotReadyerror)
当你的程序存取A驱动器时,可能会被'DriveNotReady'系统错误所中断,可以使用下面的函数来测试驱动器,以避免这种情况发生,代码如下:
functionDiskInDrive(Drive:
Char):
Boolean;
var
ErrorMode:
word;
begin
Drive:
=UpCase(Drive);
ifnot(Drivein['A'..'Z'])then
raiseEConvertError.Create('NotavaliddriveID');
ErrorMode:
=SetErrorMode(SEM_FailCriticalErrors);
try
ifDiskSize(Ord(Drive)-$40)=-1then
DiskInDrive:
=False
else
DiskInDrive:
=True;
finally
SetErrorMode(ErrorMode);
end;
end;
本函数的工作原理是:
首先将驱动器符转换为大写字母,然后关闭系统错误报告功能,执行磁盘操作,操作成功返回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',
'C:
\InputPut.txt',
'C:
\OutPut.txt',
'Please,recordthismessage')
------------------------------------------------------------------}
functionCreateDOSProcessRedirected(constCommandLine,InputFile,
OutputFile,ErrMsg:
string):
boolean;
const
ROUTINE_ID='[function:
CreateDOSProcessRedirected]';
var
OldCursor:
TCursor;
pCommandLine:
array[0..MAX_PATH]ofchar;
pInputFile,
pOutPutFile:
array[0..MAX_PATH]ofchar;
StartupInfo:
TStartupInfo;
ProcessInfo:
TProcessInformation;
SecAtrrs:
TSecurityAttributes;
hAppProcess,
hAppThread,
hInputFile,
hOutputFile:
THandle;
begin
Result:
=False;
{CheckforInputFileexistence}
ifnotFileExists(InputFile)
then
raiseException.CreateFmt(ROUTINE_ID+#10+#10+
'Inputfile*%s*'+#10+
'doesnotexist'+#10+#10+
ErrMsg,[InputFile]);
{Savethecursor}
OldCursor:
=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:
=True;
{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'+#10+
'fortheinputfile*%s*'+#10+#10+
ErrMsg,[InputFile]);
{Createtheappropriatehandlefortheoutputfile}
hOutputFile:
=CreateFile(
pOutPutFile,
pointertonameofthefile}
GENERIC_READorGENERIC_WRITE,
access(read-write)mode}
FILE_SHARE_READorFILE_SHARE_WRITE,
sharemode}
@SecAtrrs,
pointertosecurityattributes}
CREATE_ALWAYS,
{howtocreate}
FILE_ATTRIBUTE_NORMAL
orFILE_FLAG_WRITE_THROUGH,
fileattributes}
0);
handletofilewithattributestocopy}
{IshOutputFileavalidhandle?
}
ifhOutputFile=INVALID_HANDLE_VALUE
then
raiseException.CreateFmt(ROUTINE_ID+#10+#10+
'WinApifunctionCreateFilereturnedan'+
'invalidhandlevalue'+#10+
'fortheoutputfile*%s*'+#10+#10+
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}
nil,
{pointertothreadsecurityattributes}
True,
{handleinheritanceflag}
HIGH_PRIORITY_CLASS,
{creationflags}
nil,
{pointertonewenvironmentblock}
nil,
{pointertocurrentdirectoryname}
StartupInfo,
{pointertoSTARTUPINFO}
ProcessInfo);
{pointertoPROCESS_INF}
{waitfortheapptofinishitsjobandtakethe
handlestofreethemlater}
ifResult
then
begin
WaitforSingleObject(ProcessInfo.hProcess,INFINITE);
hAppProcess:
=ProcessInfo.hProcess;
hAppThread:
=ProcessInfo.hThread;
end
else
raiseException.Create(ROUTINE_ID+#10+#10+
'Functionfailure'+#10+#10+
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;
end;{CreateDOSProcessRedirected}
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- DELPHI 编程 技巧 集锦
![提示](https://static.bdocx.com/images/bang_tan.gif)