This example prompts the user for a file to delete (using the Common Dialog Control), asks whether they want to delete it or send it to the recycle bin, and then performs the appropriate action
Note: If all you want to do is delete a file, then simply useKill Filename
First, add a common dialog control to your form, a command button called cmdDelete, and then insert the following code into the form.
Private Sub cmdDelete_Click()
' Set filter to show all files
CommonDialog1.Filter = "All Files (*.*)|*.*"
' Only allow user to select files that exist (ie not type the
name)
CommonDialog1.Flags = cdlOFNFileMustExist
' Set the dialog title
CommonDialog1.DialogTitle = "Select file to delete"
On Error GoTo DialogCancelled
CommonDialog1.ShowOpen
' Delete the selected file
Select Case MsgBox("Do you want to send this file to the
recycle bin? (Clicking no will delete it permamently, and Cancel will cancel the
action)", vbDefaultButton1 + vbYesNoCancel)
Case vbYes
DeleteFile CommonDialog1.filename,
True 'recycle
Case vbNo
DeleteFile CommonDialog1.filename,
False 'delete
End Select
Exit Sub
DialogCancelled:
' Exit procedure
End Sub
Next, add this code to a module:
Option Explicit
Public Type SHFILEOPSTRUCT
hWnd As Long
wFunc As Long
pFrom As String
pTo As String
fFlags As Integer
fAnyOperationsAborted As Long
hNameMappings As Long
lpszProgressTitle As Long ' only used if
FOF_SIMPLEPROGRESS
End Type
Public Declare Function SHFileOperation Lib "shell32.dll" Alias
"SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
Public Const FO_COPY = &H2
Public Const FO_DELETE = &H3
Public Const FO_MOVE = &H1
Public Const FO_RENAME = &H4
Public Const FOF_ALLOWUNDO = &H40
Public Const FOF_NOCONFIRMATION = &H10 ' No Confirmation
Public Const FOF_NOCONFIRMMKDIR = &H200
Public Const FOF_SIMPLEPROGRESS = &H100
Public Sub DeleteFile(gFile As String, bAllowUndo As Boolean)
Dim op As SHFILEOPSTRUCT
With op
.wFunc = FO_DELETE
.pFrom = gFile
If bAllowUndo = True Then
.fFlags =
FOF_ALLOWUNDO + FOF_NOCONFIRMATION
End If
End With
SHFileOperation op
End Sub
'
'not used in this example
'
Public Sub CopyFile(sFileSource As String, NewLoc As String)
Dim op As SHFILEOPSTRUCT
If sFileSource = "" Or NewLoc = "" Then
Exit Sub
With op
.wFunc = FO_COPY
.pTo = NewLoc
.pFrom = sFileSource
.fFlags = FOF_ALLOWUNDO '+
FOF_SIMPLEPROGRESS
End With
SHFileOperation op
End Sub
Public Sub MoveFile(sFileSource As String, NewLoc As String)
Dim op As SHFILEOPSTRUCT
If sFileSource = "" Or NewLoc = "" Then
Exit Sub
With op
.wFunc = FO_MOVE
.pTo = NewLoc
.pFrom = sFileSource
.fFlags = FOF_ALLOWUNDO
End With
SHFileOperation op
End Sub
Comments