本程序演示如何通過程序來清空回收站。
向窗體上添加一個TButton組件,它用於激活清空回收站的操作。設計完成的主界面如圖1所示。
圖1 主界面
首先在程序的implementation段中定義3個常數和一個類型聲明,代碼如下:
const
SHERB_NOCONFIRMATION = $00000001 ;
SHERB_NOPROGRESSUI = $00000002 ;
SHERB_NOSOUND = $00000004 ;
type
TSHEmptyRecycleBin=function(Wnd:HWND;LPCTSTR:PChar;DWORD:Word):Integer;stdcall;
程序運行初期,程序首先會通過LoadLibrary函數加載動態鏈接庫Shell32.dll,並且把加載後的操作句柄存儲在LibHandle中。然後通過@SHEmptyRecycleBin:=GetProcAddress (LibHandle, 'SHEmptyRecycleBinA')語句讀取SHEmptyRecycleBinA函數的地址,如果以上語句能夠正確執行(也就是@SHEmptyRecycleBin不等於nil),那麼就調用SHEmptyRecycleBin完成清空回收站的操作。最後釋放動態鏈接庫。響應代碼如下:
procedure TForm1.Button1Click(Sender: TObject);
var
SHEmptyRecycleBin:TSHEmptyRecycleBin;
LibHandle:THandle;
begin
LibHandle := LoadLibrary(PChar('Shell32.dll')) ;
if LibHandle <> 0 then
begin
@SHEmptyRecycleBin := GetProcAddress(LibHandle, 'SHEmptyRecycleBinA');
end
else
begin
MessageDlg('Failed to load Shell32.dll.', mtError, [mbOK], 0);
Exit ;
end ;
if @SHEmptyRecycleBin <> nil then
begin
SHEmptyRecycleBin(Application.Handle,'',SHERB_NOCONFIRMATION or SHERB_NOPROGRESSUI or SHERB_NOSOUND) ;
end;
FreeLibrary(LibHandle);
@SHEmptyRecycleBin := nil ;
end;
程序代碼如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
const
SHERB_NOCONFIRMATION = $00000001 ;
SHERB_NOPROGRESSUI = $00000002 ;
SHERB_NOSOUND = $00000004 ;
type
TSHEmptyRecycleBin=function(Wnd:HWND;LPCTSTR:PChar;DWORD:Word):Integer;stdcall;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
SHEmptyRecycleBin:TSHEmptyRecycleBin;
LibHandle:THandle;
begin
LibHandle := LoadLibrary(PChar('Shell32.dll')) ;
if LibHandle <> 0 then
begin
@SHEmptyRecycleBin := GetProcAddress(LibHandle, 'SHEmptyRecycleBinA');
end
else
begin
MessageDlg('Failed to load Shell32.dll.', mtError, [mbOK], 0);
Exit ;
end ;
if @SHEmptyRecycleBin <> nil then
begin
SHEmptyRecycleBin(Application.Handle,'',SHERB_NOCONFIRMATION or SHERB_NOPROGRESSUI or SHERB_NOSOUND) ;
end;
FreeLibrary(LibHandle);
@SHEmptyRecycleBin := nil ;
end;
end.
保存文件,然後按F9鍵運行程序,程序運行的初始畫面如圖2所示。
圖2 程序運行的初始畫面
單擊“清空回收站”按鈕就會將操作系統回收站中的文件徹底刪除。
本程序同時也演示了如何調用一個.dll文件中的函數。