Wednesday, May 14, 2008

Working with the recycling bin

Now, if you've ever tried to interact with the recycling bin in VBA (or VB6) you probably know it can get a bit complicated at times. pIDLs, IShellFolder interfaces, lots of fun stuff. Did you know you can do some basic tasks without using any of that? Some examples:

Send a file to the recycling bin rather than just deleting it

Option Explicit
Private Type SHFILEOPTSTRUCT
hWnd As Long
wFunc As Long
pFrom As String
pTo As String
fFlags As Integer
fAnyOperationsAborted As Long
hNameMappings As Long
lpszProgressTitle As Long
End Type
Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" ( _
lpFileOp As SHFILEOPTSTRUCT) As Long
Private Const FO_DELETE = &H3
Private Const FOF_ALLOWUNDO = &H40
Public Sub DeleteFileToRecycleBin(vFilename As String)
Dim vFileOp As SHFILEOPTSTRUCT
With vFileOp
.wFunc = FO_DELETE
.pFrom = vFilename
.fFlags = FOF_ALLOWUNDO
End With
SHFileOperation vFileOp
End Sub


Empty the recycling bin
Option Explicit
Private Declare Function SHEmptyRecycleBin Lib "shell32.dll" Alias "SHEmptyRecycleBinA" _
(ByVal hWnd As Integer, ByVal pszRootPath As String, ByVal dwFlags As Integer) As Integer
Private Declare Function SHUpdateRecycleBinIcon Lib "shell32.dll" () As Long
Private Const SHERB_NOCONFIRMATION = &H1
Private Const SHERB_NOPROGRESSUI = &H2
Private Const SHERB_NOSOUND = &H4
Private Sub EmptyRecycleBin()
SHEmptyRecycleBin 0, vbNullString, SHERB_NOCONFIRMATION
SHUpdateRecycleBinIcon
End Sub


Restore from the recycling bin
Option Explicit
Sub RestoreFromRecyclingBin()
Dim vShell As Object, vRecycler As Object
Const ssfBITBUCKET As Long = 10 'the BitBucket is the recycling bin
Set vShell = CreateObject("Shell.Application")
Set vRecycler = vShell.NameSpace(ssfBITBUCKET)
RestoreRecycledItems vRecycler
Set vRecycler = Nothing
Set vShell = Nothing
End Sub
Private Sub RestoreRecycledItems(vObj As Object)
Dim vItem As Object
For Each vItem In vObj.Items
'Remove this next line if you don't want to iterate through a deleted folder
If vItem.IsFolder Then Call RestoreRecycledItems(vItem)

'You can use vObj.GetDetailsOf(vItem, x) where x is a number from 0 to 4, to return
' string information about the recycled item. Definition of x:
' 0 = Filename
' 1 = Path
' 2 = Deleted Date/Time
' 3 = File type (long name, not extension)
' 4 = Size (in KB, or whatever your windows explorer uses as default size)

'Here I will check the deleted date, and if it was deleted today, restore it
' Since .GetDetailsOf(vItem ,2) returns deleted date and time, I cut off the time
If Int(CDate(vObj.GetDetailsOf(vItem, 2))) = Date Then
'use the folderitem's InvokeVerb method to restore it
Call vItem.InvokeVerb("R&estore")
End If
Next
Set vItem = Nothing
Set vObj = Nothing
End Sub


Fun, huh?

No comments: