借花献佛:
function IsFileInUse(fName : string) : boolean;
var
HFileRes : HFILE;
begin
Result := false;
if not FileExists(fName) then
exit;
HFileRes := CreateFile(pchar(fName), GENERIC_READ or GENERIC_WRITE,
0 {this is the trick!}, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
end;
BCB中的例子如下:
if(FileExists(sFileName)) //判断报表文件是否已被打开,测试过程中要独占它
{
HANDLE hFile=CreateFile(sFileName,
GENERIC_READ|GENERIC_WRITE,
0, //独占方式
NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
if(hFile==INVALID_HANDLE_VALUE)
{
Application->MessageBoxA("您已经打开了测试报表,进入测试前请先关闭它.",
"错误",MB_ICONSTOP);
Cursor=crDefault;
Application->ProcessMessages();
ButtonOK->Enabled=true;
CloseHandle(hFile);
return;
}
CloseHandle(hFile);
}