在网上找到一个如下函数:
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;结合SDK中对CreateFile函数的定义,该函数的似乎是可以实现判断文件在被使用的功能的,然而却没有。有没有其他方法?50分哦:)

解决方案 »

  1.   

    这个函数完全可以判断出程序是否正被使用,测了一下procedure TForm1.FormCreate(Sender: TObject);
    var
      bool:boolean;
    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;
    begin
      bool:=isfileinuse('C:\windows\system32\mmc.exe');
      if bool then
        showmessage('in useing')
      else
        showmessage('not in useing');
    end;
      

  2.   

    以写方式打开文件也不行。
    是否系统通常是以共享方式(或者是以操作取副本的方式)打开一个文件的,还是决定于应用程序?
    因为我试过:
    1:新建一个文本文件“Test.txt";
    2:打开该文本文件,写入一些字符,例如‘aaa’,保存修改;
    3:不关闭该文件,启动自己编写的程序,该程序中使用IsFileInUse()测试‘Test.txt'是否在被使用,如果测试返回值为假,删除该文件;
    4:回到Notepad,重新点击保存,Notepad响应为“另存为”,说明“Test.txt”已经被删除了。
    IsFileInUse对程序(.EXT文件)使用情况判断是正确的,谢谢Wslashy,u2m!
      

  3.   

    用于判断txt文件是否在被“记事本”打开的函数:
    function TForm1.NotepadRun(FileName:string):boolean;
    var
    ExeTitle: string;
    HWndCalculator : HWnd;
    begin
        Result := False;
        ExeTitle := FileName + ' - 记事本'
        HWndCalculator := FindWindow(nil, ExeTitle); // close the exist Calculator
        if HWndCalculator <> 0 then
        begin        
            Result := True;
        end;        
    end;
      

  4.   

    The OpenFile function creates, opens, reopens, or deletes a file.
    HFILE OpenFile(
        LPCSTR lpFileName, // pointer to filename 
        LPOFSTRUCT lpReOpenBuff, // pointer to buffer for file information  
        UINT uStyle // action and attributes 
       );
    one value of Parameters uStyle is "OF_SHARE_EXCLUSIVE",the following is the definition:
    Opens the file with exclusive mode, denying both read and write access to other processes. If the file has been opened in any other mode for read or write access, even by the current process, the function fails.but it doesn't work.