一个小程序,打开一个文件,然后将这个文件删除到回收站里。Debugger Exception Notification Project Project1.exe rased exception class EAccessViolation with message 'Access violation at address 77EB00E9 in moudule 'kernel32.dll' , Read of address 12350012.Process stopped.Use Step or Run to continue. ok help
代码
unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
SHELLAPI;type
TForm1 = class(TForm)
Label1: TLabel;
Edit1: TEdit;
Button1: TButton;
Button2: TButton;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
Edit1.Text:=OpenDialog1.FileName;
end;procedure TForm1.Button2Click(Sender: TObject);
var
OpStruc:TSHFileOPStruct;
begin
with OpStruc do
begin
Wnd:=Form1.Handle;
wFunc:=FO_DELETE;
pFrom:=PChar(Edit1.Text);
fFlags:=FOF_ALLOWUNDO;
end;
SHFILEOPERATION(OpStruc);
end;end.
代码
unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
SHELLAPI;type
TForm1 = class(TForm)
Label1: TLabel;
Edit1: TEdit;
Button1: TButton;
Button2: TButton;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
Edit1.Text:=OpenDialog1.FileName;
end;procedure TForm1.Button2Click(Sender: TObject);
var
OpStruc:TSHFileOPStruct;
begin
with OpStruc do
begin
Wnd:=Form1.Handle;
wFunc:=FO_DELETE;
pFrom:=PChar(Edit1.Text);
fFlags:=FOF_ALLOWUNDO;
end;
SHFILEOPERATION(OpStruc);
end;end.
var
SHFileOpStruct:TSHFileOpStruct;
DirName: PChar;
BufferSize: Cardinal;
begin
// 调用shFileOperation函数可以实现对目录的拷贝、移动、重命名或删除操作
BufferSize := length(ADirName) + 2;
GetMem(DirName,BufferSize);
try
FIllChar(DirName^, BufferSize, 0);
StrCopy(DirName,PChar(ADirName));
with SHFileOpStruct do
begin
Wnd := AHandle;
WFunc := FO_DELETE;
pFrom := DirName;
pTO := nil;
fFlags := FOF_ALLOWUNDO; fAnyOperationsAborted := false;
hNameMappings := nil;
lpszProgressTitle := nil;
end;
if SHFileOperation(SHFileOpStruct) <> 0 then
Raiselastwin32Error;
finally
FreeMem(DirName,BufferSize);
end;
end;
var
SHF: TSHFileOpStruct;
begin
FillChar(SHF, sizeof(SHF), 0);
with SHF do
begin
Wnd:= Application.Handle;
wFunc:= FO_Delete;
pFrom:= PChar (FileName+#0#0);
pTo := PChar (#0#0);
fFlags:=
FOF_Silent or
FOF_AllowUndo or
FOF_NoConfirmation;
end;
result:= SHFileOperation (SHF) = 0;
end;
begin .....
//加了一个
pTo:=nil;
...end;ok 正常运行了。
谢谢两位