如,一个excel文件,为str.xls,delphi 如果判断str.xls已经打开

解决方案 »

  1.   

    判断一个文件是否正在被使用 
     
    关键词:Tfilestream 文件状态  
    {
    函数功能:检查文件是否正在被使用
    参数fname:被检查的文件名
    返回值:True正在被使用
            false没有被使用
     }
    function IsFileInUse(fName : string ) : boolean;
    var
    HFileRes : Tfilestream;
    begin
    Result := false;
    if not FileExists(fName) then
    exit;
    try
    hfileres:=Tfilestream.create(fname,fmShareExclusive);
    result:=false;
    except
    result:=true;
    end;
    try
    hfileres.Free;
    except
    end;
    end;
     
      

  2.   

    还是这样吧,还更好些,刚试验了一下可以
    uses 添加 StrUtils,windows
    声明全局变量:
    var hExcel,hBook:integer;
    //**************回调函数(枚举顶层窗口)
    function FindExcel(Hwnd:HWND;lParam:integer):boolean;stdcall
    var
      strTitle:array[0..255] of char;
      strText:string;
      intLen:integer;
    begin
      result:=true;
      intLen:=getwindowtext(Hwnd,strTitle,255);
      strText:=leftstr(strTitle,intlen);
      if pos('Microsoft Excel',strText)>0 then
      begin
        hExcel:=Hwnd;
        result:=false;
      end;
    end;
    //**************回调函数(枚举子窗口)
    function FindBook(Hwnd:HWND;lParam:integer):boolean;stdcall
    var
      strTitle:array[0..255] of char;
      strText,strBook:string;
      intLen:integer;
    begin
      result:=true;
      strBook:='成绩单';//要查找的文件,不用包括路径名
      intLen:=getwindowtext(Hwnd,strTitle,255);
      strText:=leftstr(strTitle,intlen);
      if pos(strBook,strText)>0 then
      begin
        hBook:=hWnd;
        result:=false;
      end;  
    end;
    //一定要在上边两个函数之后写
    procedure Tform1.Button1Click(Sender: TObject);
    begin
    //查找EXCEL窗口
    hExcel:=0;
    hBook:=0;
    enumwindows(@FindExcel,0);
    if hExcel=0 then
    begin
      showmessage('Excel 未运行!');
      exit;
    end;
    EnumChildWindows(hExcel,@FindBook,0);
    if hBook=0 then
      showmessage('该文件未打开!')
    else
      showmessage('该文件已打开!');
    end;