本例包含用 TFileStream 复制文件和用 ShellAPI.ShellExecute 打开文件夹的方法.

本例效果图:



代码文件:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Edit2: TEdit;
    Button1: TButton;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses ShellAPI;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Edit1.Text := ExtractFileName(Application.ExeName);
  Edit2.Text := 'New.exe';
  Button1.Caption := '复制';
  Button2.Caption := '看看';
end;

{复制当前程序文件}
procedure TForm1.Button1Click(Sender: TObject);
var
  NewFileName, OldFileName: string;
  Msg: string;
  NewFile: TFileStream;
  OldFile: TFileStream;
begin
  OldFileName := ExtractFilePath(Application.ExeName) + ExtractFileName(Edit1.Text);
  NewFileName := ExtractFilePath(Application.ExeName) + ExtractFileName(Edit2.Text);
  Msg := Format('是否把' + #13#10 + '%s' + #13#10 + '复制为' + #13#10 + '%s?', [OldFileName, NewFileName]);
  if MessageDlg(Msg, mtCustom, mbOKCancel, 0) = mrOK then
  begin
    OldFile := TFileStream.Create(OldFileName, fmOpenRead or fmShareDenyWrite);
    try
      NewFile := TFileStream.Create(NewFileName, fmCreate or fmShareDenyRead);
      try
        NewFile.CopyFrom(OldFile, OldFile.Size);
      finally
        FreeAndNil(NewFile);
      end;
    finally
      FreeAndNil(OldFile);
    end;
  end;
end;

{打开文件夹看看}
procedure TForm1.Button2Click(Sender: TObject);
begin
  ShellExecute(Handle, 'open', 'Explorer.exe', PChar(GetCurrentDir), nil, SW_NORMAL);
end;

end.

窗体文件:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 174
  ClientWidth = 172
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 48
    Top = 95
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
    OnClick = Button1Click
  end
  object Edit1: TEdit
    Left = 24
    Top = 23
    Width = 121
    Height = 21
    TabOrder = 1
    Text = 'Edit1'
  end
  object Edit2: TEdit
    Left = 24
    Top = 58
    Width = 121
    Height = 21
    TabOrder = 2
    Text = 'Edit2'
  end
  object Button2: TButton
    Left = 48
    Top = 134
    Width = 75
    Height = 25
    Caption = 'Button2'
    TabOrder = 3
    OnClick = Button2Click
  end
end

posted on 2008-06-19 10:48  万一  阅读(5023)  评论(3编辑  收藏  举报