Jan Krynický > Win32-FileOp > Win32::FileOp

Download:
Win32-FileOp-0.16.02.tar.gz

Dependencies

Annotate this POD

Related Modules

Test::More
Win32::GUI
Win32::API
Archive::Zip
Tk::DirSelect
File::Find
Win32::OLE
WWW::Mechanize
File::Copy
Net::FTP
more...
By perlmonks.org

CPAN RT

New  4
Open  0
View/Report Bugs
Module Version: 0.16.02   Source  

NAME ^

Win32::FileOp - 0.16.02

DESCRIPTION ^

Module for file operations with fancy dialog boxes, for moving files to recycle bin, reading and updating INI files and file operations in general.

Unless mentioned otherwise all functions work under WinXP, Win2k, WinNT, WinME and Win9x. Let me know if not.

Version 0.16.02

Functions

GetDesktopHandle GetWindowHandle

Copy CopyConfirm CopyConfirmEach CopyEx

Move MoveConfirm MoveConfirmEach MoveEx

MoveFile MoveFileEx CopyFile MoveAtReboot

Recycle RecycleConfirm RecycleConfirmEach RecycleEx

Delete DeleteConfirm DeleteConfirmEach DeleteEx DeleteAtReboot

UpdateDir FillInDir

Compress Uncompress Compressed SetCompression GetCompression CompressDir UncompressDir

GetLargeFileSize GetDiskFreeSpace

AddToRecentDocs EmptyRecentDocs

WriteToINI WriteToWININI ReadINI ReadWININI

DeleteFromINI DeleteFromWININI

OpenDialog SaveAsDialog BrowseForFolder

Map Unmap Disconnect Mapped

Subst Unsubst Substed

ShellExecute ShellExecuteEx

To get the error message from most of these functions, you should not use $!, but $^E or Win32::FormatMessage(Win32::GetLastError())!

GetDesktopHandle
 use Win32::FileOp
 $handle = GetDesktopHandle()

Same as: $handle = $Win32::FileOp::DesktopHandle

Used to get desktop window handle when confirmation is used. The value of the handle can be gotten from $Win32::FileOp::DesktopHandle.

Returns the Desktop Window handle.

GetWindowHandle
 use Win32::FileOp;
 my $handle = GetWindowHandle();

Used to get the console window handle for operations that display dialog boxes.

If you are using Tk or any other GUI toolkit this is most probably not what you want. Even if the console is shown. You need to find the Windows handle of one of your windows and pass it to the functions.

If you use Tk you can get the handle like this:

        $windowHandle = hex ($windowobject->id);

Please let me know if you find out how to get the handle from the other toolkits.

Not all functions allow you to pass the handle so you can set the $Win32::FileOp::WindowHandle to the handle of the window you want to tie the dialog boxes to.

Copy
 Copy ($FileName => $FileOrDirectoryName [, ...])
 Copy (\@FileNames => $DirectoryName [, ...] )
 Copy (\@FileNames => \@FileOrDirectoryNames [, ...])

Copies the specified files. Doesn't show any confirmation nor progress dialogs.

It may show an error message dialog, because I had to omit FOF_NOERRORUI from its call to allow for autocreating directories.

You should end the directory names by backslash so that they are not mistaken for filenames. It is not necessary if the directory already exists or if you use Copy \@filenames => $dirname.

Returns true if successful.

Rem: Together with Delete, Move, DeleteConfirm, CopyConfirm, MoveConfirm, CopyEx, MoveEx, DeleteEx and Recycle based on Win32 API function SHFileOperation().

CopyConfirm
 CopyConfirm ($FileName => $FileOrDirectoryName [, ...])
 CopyConfirm (\@FileNames => $DirectoryName [, ...] )
 CopyConfirm (\@FileNames => \@FileOrDirectoryNames [, ...])

Copies the specified files. In case of a collision, shows a confirmation dialog. Shows progress dialogs.

Returns true if successful.

CopyConfirmEach

The same as CopyConfirm.

CopyEx
 CopyEx ($FileName => $FileOrDirectoryName, [...], $options)
 CopyEx (\@FileNames => $DirectoryName, [...], $options)
 CopyEx (\@FileNames => \@FileOrDirectoryNames, [...], $options)

Copies the specified files. See below for the available options (FOF_ constants).

Returns true if successful.

Move

Moves the specified files. Parameters as Copy

It may show an error message dialog, because I had to omit FOF_NOERRORUI from its call to allow for autocreating directories.

MoveConfirm

Moves the specified files. Parameters as CopyConfirm

MoveConfirmEach

The same as MoveConfirm

MoveEx

Moves the specified files. Parameters as CopyEx

MoveAtReboot
 MoveAtReboot ($FileName => $DestFileName, [...])

This function moves the file during the next start of the system.

MoveFile
 MoveFile ($FileName => $DestFileName [, ...])

Move files. This function uses API function MoveFileEx as well as MoveAtReboot. It may be a little quicker than Move, but it doesn't understand wildcards and the $DestFileName may not be a directory.

REM: Based on Win32 API function MoveFileEx().

MoveFileEx
 MoveFileEx ($FileName => $DestFileName [, ...], $options)

This is a simple wrapper around the API function MoveFileEx, it calls the function for every pair of files with the $options you specify. See below for the available options (FOF_... constants).

REM: Based on Win32 API function MoveFileEx().

CopyFile
 CopyFile ($FileName => $DestFileName [, $FileName2 => $DestFileName2 [, ...]])

Copy a file somewhere. This function is not able to copy directories!

REM: Based on Win32 API function CopyFile().

Recycle
 Recycle @filenames

Send the files into the recycle bin. You will not get any confirmation dialogs.

Returns true if successful.

RecycleConfirm
 RecycleConfirm @filenames

Send the files into the recycle bin. You will get a confirmation dialog if you have "Display delete confirmation dialog" turned on in your recycle bin. You will confirm the deletion of all the files at once.

Returns true if successful. Please remember that this function is successful even if the user chose [No] on the confirmation dialog!

RecycleConfirmEach
 RecycleConfirmEach @filenames

Send the files into the recycle bin. You will get a separate confirmation dialog for each file if you have "Display delete confirmation dialog" turned on in your recycle bin. You will confirm the deletion of all the files at once.

Returns the number of files that were successfully deleted.

RecycleEx
 RecycleEx @filenames, $options

Send the files into the recycle bin. You may specify the options for deleting, see below. You may get a confirmation dialog if you have "Display delete confirmation dialog" turned on in your recycle bin, if so, you will confirm the deletion of all the files at once.

Returns true if successful. Please remember that this function is successful even if the user chose [No] on the confirmation dialog!

The $options may be constructed from FOF_... constants.

Delete
 Delete @filenames

Deletes the files. You will not get any confirmation dialogs.

Returns true if successful.

DeleteConfirm
 DeleteConfirm @filenames

Deletes the the files. You will get a confirmation dialog to confirm the deletion of all the files at once.

Returns true if successful. Please remember that this function is successful even if the user selected [No] on the confirmation dialog!

DeleteConfirmEach
 DeleteConfirmEach @filenames

Deletes the files. You will get a separate confirmation dialog for each file.

Returns the number of files that were successfully deleted.

DeleteEx
 DeleteEx @filenames, $options

Deletes the files. You may specify the options for deleting, see below. You may get a confirmation dialog if you have "Display delete confirmation dialog" turned on in your recycle bin.

Returns true if successful. Please remember that this function is successful even if the user selected [No] on the confirmation dialog!

DeleteAtReboot
 DeleteAtReboot @files

This function moves the file during the next start of the system.

UpdateDir
 UpdateDir $SourceDirectory, $DestDirectory [, \&callback]

Copy the newer or updated files from $SourceDir to $DestDir. Processes subdirectories! The &callback function is called for each file to be copied. The parameters it gets are exactly the same as the callback function in File::Find. That is $_, $File::Find::dir and $File::Find::name.

If this function returns a false value, the file is skipped.

 Ex.

  UpdateDir 'c:\dir' => 'e:\dir', sub {print '.'};
  UpdateDir 'c:\dir' => 'e:\dir', sub {if (/^s/i) {print '.'}};
FillInDir
 FillInDir $SourceDirectory, $DestDirectory [, \&callback]

Copy the files from $SourceDir not present in $DestDir. Processes subdirectories! The &callback works the same as in UpdateDir.

Compress
 Compress $filename [, ...]

Compresses the file(s) or directories using the transparent WinNT compression (The same as checking the "Compressed" checkbox in Explorer properties fo the file).

It doesn't compress all files and subdirectories in a directory you specify. Use ComressDir for that. Compress($directory) only sets the compression flag for the directory so that the new files are compressed by default.

WinNT only!

REM: Together with other compression related functions based on DeviceIoControl() Win32 API function.

Uncompress
 Uncompress $filename [, ...]

Uncompresses the file(s) using the transparent WinNT compression (The same as unchecking the "Compressed" checkbox in Explorer properties fo the file).

WinNT only!

Compressed
 Compressed $filename

Checks the compression status for a file.

SetCompression
 SetCompression $filename [, $filename], $value

Sets the compression status for file(s). The $value should be either 1 or 0.

GetCompression
 GetCompression $filename

Checks the compression status for a file.

CompressDir
 CompressDir $directory, ... [, \&callback]

Recursively descends the directory(ies) specified and compresses all files and directories within. If you specify the \&callback, the specified function gets executed for each of the files and directories. If the callback returns false, no compression is done on the file/directory.

The parameters the callback gets are exactly the same as the callback function in File::Find. That is $_, $File::Find::dir and $File::Find::name.

UncompressDir
 UncompressDir $directory, ... [, \&callback]

The counterpart of CompressDir.

GetLargeFileSize
        ($lo_word, $hi_word) = GetLargeFileSize( $path );
        # or
        $file_size = GetLargeFileSize( $path );

This gives you the file size for too big files (over 4GB). If called in list context returns the two 32 bit words, in scalar context returns the file size as one number ... if the size is too big to fit in an Integer it'll be returned as a Float. This means that if it's above cca. 10E15 it may get slightly rounded.

GetDiskFreeSpace
        $freeSpaceForUser = GetDiskFreeSpace $path;
        # or
        ($freeSpaceForUser, $totalSize, $totalFreeSpace) = GetDiskFreeSpace $path;

In scalar context returns the amount of free space available to current user (respecting quotas), in list context returns the free space for current user, the total size of disk and the total amount of free space on the disk.

Works OK with huge disks.

Requires at least Windows 95 OSR2 or WinNT 4.0.

AddToRecentDocs
 AddToRecentDocs $filename [, ...]

Add a shortcut(s) to the file(s) into the Recent Documents folder. The shortcuts will appear in the Documents submenu of Start Menu.

The paths may be relative.

REM: Based on Win32 API function SHAddToRecentDocs().

EmptyRecentDocs
 EmptyRecentDocs;

Deletes all shortcuts from the Recent Documents folder.

REM: Based on Win32 API function SHAddToRecentDocs(). Strange huh?

WriteToINI
 WriteToINI $INIfile, $section, $name1 => $value [, $name2 => $value2 [, ...]]

Copies a string into the specified section of the specified initialization file. You may pass several name/value pairs at once.

Returns 1 if successful, undef otherwise. See Win32::GetLastError & Win32::FormatMessage(Win32::GetLastError) if failed for the error code and message.

REM: Based on Win32 API function WritePrivateProfileString().

WriteToWININI
 WriteToWININI $section, $name1 => $value1 [, $name2 => $value2 [, ...]]

Copies a string into the specified section of WIN.INI. You may pass several name/value pairs at once.

Please note that some values or sections of WIN.INI and some other INI files are mapped to registry so they do not show up in the INI file even if they were successfully written!

REM: Based on Win32 API function WriteProfileString().

ReadINI
    $value = ReadINI $INIfile, $section, $name [, $defaultvalue]

Reads a value from an INI file. If you do not specify the default and the value is not found you'll get undef.

REM: Based on Win32 API function GetPrivateProfileString().

ReadWININI
    $value = ReadWININI $section, $name [, $defaultvalue]

Reads a value from WIN.INI file. If you do not specify the default and the value is not found you'll get undef.

Please note that some values or sections of WIN.INI and some other INI files are mapped to registry so even that they do not show up in the INI file this function will find and read them!

REM: Based on Win32 API function GetProfileString().

DeleteFromINI
 DeleteFromINI $INIfile, $section, @names_to_delete

Delete a value from an INI file.

REM: Based on Win32 API function WritePrivateProfileString().

DeleteFromWININI
 DeleteFromWININI $section, @names_to_delete

Delete a value from WIN.INI.

REM: Based on Win32 API function WriteProfileString().

ReadINISections
 @sections = ReadINISections($inifile);
 \@sections = ReadINISections($inifile);
 ReadINISections($inifile,\@sections);

Enumerate the sections in a INI file. If you do not specify the INI file, it enumerates the contents of win.ini.

REM: Based on Win32 API function GetPrivateProfileString().

ReadINISectionKeys
 @sections = ReadINISectionKeys($inifile, $section);
 \@sections = ReadINISectionKeys($inifile, $section);
 ReadINISectionKeys($inifile, $section, \@sections);

Enumerate the keys in a section of a INI file. If you do not specify the INI file, it enumerates the contents of win.ini.

REM: Based on Win32 API function GetPrivateProfileString().

OpenDialog
 $filename = OpenDialog \%parameters [, $defaultfilename]
 @filenames = OpenDialog \%parameters [, $defaultfilename]

 $filename = OpenDialog %parameters [, $defaultfilename]
 @filenames = OpenDialog %parameters [, $defaultfilename]

Creates the standard Open dialog allowing you to select some files.

Returns a list of selected files or undef if the user pressed [Escape]. It also sets two global variables :

 $Win32::FileOp::ReadOnly = the user requested a readonly access.
 $Win32::FileOp::SelectedFilter = the id of filter selected in the dialogbox

 %parameters
  title => the title for the dialog, default is 'Open'
        'Open file'
  filters => definition of file filters
        { 'Filter 1' => '*.txt;*.doc', 'Filter 2' => '*.pl;*.pm'}
        [ 'Filter 1' => '*.txt;*.doc', 'Filter 2' => '*.pl;*.pm']
        [ 'Filter 1' => '*.txt;*.doc', 'Filter 2' => '*.pl;*.pm' , $default]
        "Filter 1\0*.txt;*.doc\0Filter 2\0*.pl;*.pm"
  defaultfilter => the number of the default filter counting from 1.
                   Please keep in mind that hashes do not preserve
                   ordering!
  dir => the initial directory for the dialog, default is the current directory
  filename => the default filename to be showed in the dialog
  handle => the handle to the window which will own this dialog
            Default is the console of the perl script.
            If you do not want to tie the dialog to any window use
            handle => 0
  options => options for the dialog, see bellow OFN_... constants

There is a little problem with the underlying function. You have to preallocate a buffer for the selected filenames and if the buffer is too smallyou will not get any results. I've consulted this with the guys on Perl-Win32-Users and there is not any nice solution. The default size of buffer is 256B if the options do not include OFN_ALLOWMULTISELECT and 64KB if they do. You may change the later via variable $Win32::FileOp::BufferSize.

NOTE: I have been notified about a strange behaviour under Win98. If you use UNCs you should always use backslashes in the paths. \\server/share doesn't work at all under Win98 and //server/share works only BEFORE calling the Win32::FileOp::OpenDialog(). I have no idea what is the cause of this behaviour.

REM: Based on Win32 API function GetOpenFileName().

SaveAsDialog

Creates the Save As dialog box, parameters are the same as for OpenDialog.

REM: Based on Win32 API function GetSaveFileName().

BrowseForFolder
 BrowseForFolder [$title [, $rootFolder [, $options [, $window_handle ]]]]

Creates the standard "Browse For Folder" dialog. The $title specifies the text to be displayed below the title of the dialog. The $rootFolder may be one of the CSIDL_... constants. For $options you should use the BIF_... constants. The $window_handle (if specified) is the handle of the window to which the dialog will be modal. If not specified, the dialog will be modal to the console. If this parameter is 0 the dialog will not be modal. Description of the constants is bellow.

(MSDN says) You must initialize Component Object Model (COM) using CoInitializeEx with the COINIT_APARTMENTTHREADED flag set in the dwCoInit parameter prior to calling SHBrowseForFolder. You can also use CoInitialize or OleInitialize, which always use apartment threading. If COM is initialized using CoInitializeEx with the COINIT_MULTITHREADED flag, SHBrowseForFolder fails if the caller uses the BIF_USENEWUI or BIF_NEWDIALOGSTYLE flag in the BROWSEINFO structure.

REM: Based on Win32 API function SHBrowseForFolder().

Map
 Map $drive => $share;
 $drive = Map $share;
 Map $drive => $share, \%options;
 $drive = Map $share, \%options;

Map a drive letter or LTPx to a network resource. If successfull returns the drive letter/LPTx.

If you do not specify the drive letter, the function uses the last free letter, if you specify undef or empty string as the drive then the share is connected, but not assigned a letter.

Since the function doesn't require the ':' in the drive name you may use the function like this:

 Map H => '\\\\server\share';
 as well as
 Map 'H:' => '\\\\server\share';

 Options:
  persistent => 0/1
          should the connection be restored on next logon?

  user => $username
          username to be used to connect the device
  passwd => $password
          password to be used to connect the device
  overwrite => 0/1
          should the drive be remapped if it was already connected?
  force_overwrite => 0/1
          should the drive be forcefully disconnected and
          remapped if it was already connected?
  interactive = 0 / 'yes' / $WindowHandle
          if necessary displays a dialog box asking the user
          for the username and password.
  prompt = 0/1
          if used with interactive=> the user is ALWAYS asked for the username
          and password, even if you supplied them in the call. If you did not specify
          interactive=> then prompt=> is ignored.
  redirect = 0/1
          forces the redirection of a local device when making the connection

 Example:
  Map I => '\\\\servername\share', {persistent=>1,overwrite=>1};

Notes: 1) If you use the interactive option the user may Cancel that dialog. In that case the Map() fails, returns undef and Win32::GetLastError() returns 1223 and $^E is equals to 1223 in numerical context and to "The operation was canceled by the user." in string context.

2) You should only check the Win32::GetLastError() or $^E if the function failed. If you do check it even if it succeeded you may get error 997 "Overlapped I/O operation is in progress.". This means that it worked all right and you should not care about this bug!

REM: Based on Win32 API function WNetAddConnection3().

Connect
        Connect $share
        Connect $share, \%options

Connects a share without assigning a drive letter to it.

REM: Based on Win32 API function WNetAddConnection3().

Disconnect
 Disconnect $drive_or_share;
 Disconnect $drive_or_share, \%options;

Breaks an existing network connection. It can also be used to remove remembered network connections that are not currently connected.

$drive_or_share specifies the name of either the redirected local device or the remote network resource to disconnect from. If this parameter specifies a redirected local resource, only the specified redirection is broken; otherwise, all connections to the remote network resource are broken.

 Options:
  persistent = 0/1, if you do not use persistent=>1, the connection will be closed, but
               the drive letter will still be mapped to the device
  force      = 0/1, disconnect even if there are some open files

 See also: Unmap

REM: Based on Win32 API function WNetCancelConnection2().

Unmap
 Unmap $drive_or_share;
 Unmap $drive_or_share, \%options;

The only difference from Disconnect is that persistent=>1 is the default.

REM: Based on Win32 API function WNetCancelConnection2().

Mapped
 %drives = Mapped;
 $share = Mapped $drive;
 $drive = Mapped $share; # currently not implemented !!!

This function retrieves the name of the network resource associated with a local device. Or vice versa.

If you do not specify any parameter, you get a hash of drives and shares.

To get the error message from most of these functions, you should not use $!, but Win32::FormatMessage(Win32::GetLastError()) or $^E !

REM: Based on Win32 API function WNetGetConnection().

Subst
 Subst Z => 'c:\temp';
 Subst 'Z:' => '\\\\servername\share\subdir';

This function substitutes a drive letter for a directory, both local and UNC.

Be very carefull with this, cause it'll allow you to change the substitution even for C:. ! Which will most likely be lethal !

Works only on WinNT.

REM: Based on DefineDosDevice()

 =item SubstDev

 SubstDev F => 'Floppy0';
 SubstDev G => 'Harddisk0\Partition1';

Allows you to make a substitution to devices. For example if you want to make an alias for A: ...

To get the device mapped to a drive letter use Substed() in list context.

Works only on WinNT.

REM: Based on DefineDosDevice()

Unsubst
 Unsubst 'X';

Deletes the substitution for a drive letter. Again, be very carefull with this!

Works only on WinNT.

REM: Based on DefineDosDevice()

Substed
 %drives = Substed;
 $substitution = Substed $drive;
 ($substitution, $device) = Substed $drive;

This function retrieves the name of the resource(s) associated with a drive letter(s).

If used with a parameter :

In scalar context you get the substitution. If the drive is the root of a local device you'll get an empty string, if it's not mapped to anything you'll get undef.

In list context you'll get both the substitution and the device/type of device :

 Substed 'A:' => ('','Floppy0')
 Substed 'B:' => undef
 Substed 'C:' => ('','Harddisk0\Partition1')
 Substed 'H:' => ('\\\\servername\homes\username','UNC')
  # set by subst H: \\servername\homes\username
 Substed 'S:' => ('\\\\servername\servis','LanmanRedirector')
  # set by net use S: \\servername\servis
 Substed 'X:' => ()
  # not mapped to anything

If used without a parameter gives you a hash of drives and their corresponding sunstitutions.

Works only on WinNT.

REM: Based on Win32 API function QueryDosDevice().

ShellExecute
        ShellExecute $filename;
        ShellExecute $operation => $filename;
        ShellExecute $operation => $filename, $params, $dir, $showOptions, $handle;
        ShellExecute $filename,
                {params => $params, dir => $dir, show => $showOptions, handle => $handle};
        ShellExecute $operation => $filename,
                {params => $params, dir => $dir, show => $showOptions, handle => $handle};

This function instructs the system to execute whatever application is assigned to the file type as the specified action in the registry.

        ShellExecute 'open' => $filename;
 or
        ShellExecute $filename;

is equivalent to doubleclicking the file in the Explorer,

        ShellExecute 'edit' => $filename;

is equivalent to rightclicking it and selecting the Edit action.

Parameters:

$operation : specifies the action to perform. The set of available operations depends on the file type. Generally, the actions available from an object's shortcut menu are available verbs.

Since version 0.17 you can specify more operations. The first operation that is defined for that type of file will be used.

        ShellExecute ['edit', 'open'] => $filename;

For executables there are two interesting werbs. "runas" allows you to run the application as an administrator and "runasuser" allowing you to run the aplication as a different user.

$filename : The file to execute the action for.

$params : If the $filename parameter specifies an executable file, $params is a string that specifies the parameters to be passed to the application. The format of this string is determined by the $operation that is to be invoked. If $filename specifies a document file, $params should be undef.

$dir : the default directory for the invoked program.

$showOptions : one of the SW_... constants that specifies how the application is to be displayed when it is opened.

$handle : The handle of the window that gets any message boxes that may be invoked by this. Be default the handle of the console that this script runs in.

You can either find the list of actions if you manualy rightclick a file of that type in Windows Explorer (the topmost section of the menu except "Open With") or go to the registry (regedit.exe) go to HKEY_CLASSES_ROOT\.ext, look at the default value (the type of the file), then go to HKEY_CLASSES_ROOT\<the_type>\Shell and the subkeys are the different available actions. ShellExecute lets you use either the name of the subkeys or the title specified in the default value in that subkey.

If you need to find the list of actions programaticaly you just use Win32::Registry or Tie::Registry to do the same. Find the type from HKEY_CLASSES_ROOT\.ext, go to HKEY_CLASSES_ROOT\<the_type>\Shell and list the subkeys.

REM: Based on Win32 API function ShellExecute

ShellExecuteEx
        ShellExecuteEx $filename;
        ShellExecuteEx $operation => $filename;
        ShellExecuteEx $operation => $filename, $params, $dir, $showOptions, $handle, $expand, $unicode;
        ShellExecuteEx $filename,
                {params => $params, dir => $dir, show => $showOptions, handle => $handle, expand => $expand, unicode => $unicode};
        ShellExecuteEx $operation => $filename,
                {params => $params, dir => $dir, show => $showOptions, handle => $handle, expand => $expand, unicode => $unicode};

This function instructs the system to execute whatever application is assigned to the file type as the specified action in the registry.

        ShellExecuteEx 'open' => $filename;
 or
        ShellExecuteEx $filename;

is equivalent to doubleclicking the file in the Explorer,

        ShellExecuteEx 'edit' => $filename;

is equivalent to rightclicking it and selecting the Edit action.

Parameters:

$operation : specifies the action to perform. The set of available operations depends on the file type. Generally, the actions available from an object's shortcut menu are available verbs.

For executables there are two interesting werbs. "runas" allows you to run the application as an administrator and "runasuser" allowing you to run the aplication as a different user.

$filename : The file to execute the action for.

$params : If the $filename parameter specifies an executable file, $params is a string that specifies the parameters to be passed to the application. The format of this string is determined by the $operation that is to be invoked. If $filename specifies a document file, $params should be undef.

$dir : the default directory for the invoked program.

$showOptions : one of the SW_... constants that specifies how the application is to be displayed when it is opened.

$handle : The handle of the window that gets any message boxes that may be invoked by this. Be default the handle of the console that this script runs in.

$expand: Expand any environment variables specified in the string given by the $dir or $filename parameter.

$unicode : Use this flag to indicate a Unicode application.

You can either find the list of actions if you manualy rightclick a file of that type in Windows Explorer (the topmost section of the menu except "Open With") or go to the registry (regedit.exe) go to HKEY_CLASSES_ROOT\.ext, look at the default value (the type of the file), then go to HKEY_CLASSES_ROOT\<the_type>\Shell and the subkeys are the different available actions. ShellExecute lets you use either the name of the subkeys or the title specified in the default value in that subkey.

If you need to find the list of actions programaticaly you just use Win32::Registry or Tie::Registry to do the same. Find the type from HKEY_CLASSES_ROOT\.ext, go to HKEY_CLASSES_ROOT\<the_type>\Shell and list the subkeys.

REM: Based on Win32 API function ShellExecuteEx

Options

FOF_
 FOF_SILENT = do not show the progress dialog
 FOF_RENAMEONCOLLISION = rename the file in case of collision
            ('file.txt' -> 'Copy of file.txt')
 FOF_NOCONFIRMATION = do not show the confirmation dialog
 FOF_ALLOWUNDO = send file(s) to RecycleBin instead of deleting
 FOF_FILESONLY = skip directories
 FOF_SIMPLEPROGRESS = do not show the filenames in the process dialog
 FOF_NOCONFIRMMKDIR = do not confirm creating directories
 FOF_NOERRORUI = do not report errors
 FOF_NOCOPYSECURITYATTRIBS = do not copy security attributes
OFN_
 OFN_ALLOWMULTISELECT

Specifies that the File Name list box allows multiple selections. If you also set the OFN_EXPLORER flag, the dialog box uses the Explorer-style user interface; otherwise, it uses the old-style user interface.

 OFN_CREATEPROMPT

If the user specifies a file that does not exist, this flag causes the dialog box to prompt the user for permission to create the file. If the user chooses to create the file, the dialog box closes and the function returns the specified name; otherwise, the dialog box remains open.

 OFN_EXPLORER

Since I cannot implement hook procedures through Win32::API (AFAIK), this option in not necessary.

 OFN_FILEMUSTEXIST

Specifies that the user can type only names of existing files in the File Name entry field. If this flag is specified and the user enters an invalid name, the dialog box procedure displays a warning in a message box. If this flag is specified, the OFN_PATHMUSTEXIST flag is also used.

 OFN_HIDEREADONLY

Hides the Read Only check box.

 OFN_LONGNAMES

For old-style dialog boxes, this flag causes the dialog box to use long filenames. If this flag is not specified, or if the OFN_ALLOWMULTISELECT flag is also set, old-style dialog boxes use short filenames (8.3 format) for filenames with spaces. Explorer-style dialog boxes ignore this flag and always display long filenames.

 OFN_NOCHANGEDIR

Restores the current directory to its original value if the user changed the directory while searching for files.

 OFN_NODEREFERENCELINKS

Directs the dialog box to return the path and filename of the selected shortcut (.LNK) file. If this value is not given, the dialog box returns the path and filename of the file referenced by the shortcut

 OFN_NOLONGNAMES

For old-style dialog boxes, this flag causes the dialog box to use short filenames (8.3 format). Explorer-style dialog boxes ignore this flag and always display long filenames.

 OFN_NONETWORKBUTTON

Hides and disables the Network button.

 OFN_NOREADONLYRETURN

Specifies that the returned file does not have the Read Only check box checked and is not in a write-protected directory.

 OFN_NOTESTFILECREATE

Specifies that the file is not created before the dialog box is closed. This flag should be specified if the application saves the file on a create-nonmodify network sharepoint. When an application specifies this flag, the library does not check for write protection, a full disk, an open drive door, or network protection. Applications using this flag must perform file operations carefully, because a file cannot be reopened once it is closed.

 OFN_NOVALIDATE

Specifies that the dialog boxes allow invalid characters in the returned filename.

 OFN_OVERWRITEPROMPT

Causes the Save As dialog box to generate a message box if the selected file already exists. The user must confirm whether to overwrite the file.

 OFN_PATHMUSTEXIST

Specifies that the user can type only valid paths and filenames. If this flag is used and the user types an invalid path and filename in the File Name entry field, the dialog box function displays a warning in a message box.

 OFN_READONLY

Causes the Read Only check box to be checked initially when the dialog box is created. If the check box is checked when the dialog box is closed $Win32::FileOp::ReadOnly is set to true.

 OFN_SHAREAWARE

Specifies that if a call to the OpenFile function fails because of a network sharing violation, the error is ignored and the dialog box returns the selected filename.

 OFN_SHOWHELP

Causes the dialog box to display the Help button. The hwndOwner member must specify the window to receive the HELPMSGSTRING registered messages that the dialog box sends when the user clicks the Help button.

BIF_
 BIF_DONTGOBELOWDOMAIN

Does not include network folders below the domain level in the tree view control.

 BIF_RETURNONLYFSDIRS

Only returns file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.

 BIF_RETURNFSANCESTORS

Only returns file system ancestors. If the user selects anything other than a file system ancestor, the OK button is grayed.

This option is strange, cause it seems to allow you to select only computers. I don't know the definition of a filesystem ancestor, but I didn't think it would be a computer. ?-|

 BIF_BROWSEFORCOMPUTER

Only returns computers. If the user selects anything other than a computer, the OK button is grayed.

 BIF_BROWSEFORPRINTER

Only returns printers. If the user selects anything other than a printer, the OK button is grayed.

 BIF_STATUSTEXT

Since it is currently impossible to define callbacks, this options is useless.

 BIF_EDITBOX

Include an edit control in the browse dialog box that allows the user to type the name of an item.

 BIF_VALIDATE

insist on valid result (or CANCEL)

 BIF_NEWDIALOGSTYLE

Use the new user interface. Setting this flag provides the user with a larger dialog box that can be resized. The dialog box has several new capabilities including: drag and drop capability within the dialog box, reordering, shortcut menus, new folders, delete, and other shortcut menu commands. To use this flag, you must call OleInitialize or CoInitialize before calling SHBrowseForFolder.

 BIF_USENEWUI

BIF_NEWDIALOGSTYLE and BIF_EDITBOX combined

 BIF_BROWSEINCLUDEURLS

The browse dialog box can display URLs. The BIF_USENEWUI and BIF_BROWSEINCLUDEFILES flags must also be set. If these three flags are not set, the browser dialog box will reject URLs. Even when these flags are set, the browse dialog box will only display URLs if the folder that contains the selected item supports them.

 BIF_UAHINT

Add a UA hint to the dialog, in place of the edit box. May not be combined with BIF_EDITBOX

 BIF_NONEWFOLDERBUTTON

Do not add the "New Folder" button to the dialog. Only applicable with BIF_NEWDIALOGSTYLE.

 BIF_NOTRANSLATETARGETS

Don't traverse target as shortcut

 BIF_SHAREABLE

The browse dialog box can display shareable resources on remote systems. It is intended for applications that want to expose remote shares on a local system. The BIF_NEWDIALOGSTYLE flag must also be set.

CSIDL_

This is a list of available options for BrowseForFolder().

CSIDL_BITBUCKET

Recycle bin --- file system directory containing file objects in the user's recycle bin. The location of this directory is not in the registry; it is marked with the hidden and system attributes to prevent the user from moving or deleting it.

CSIDL_CONTROLS

Control Panel --- virtual folder containing icons for the control panel applications.

CSIDL_DESKTOP

Windows desktop --- virtual folder at the root of the name space.

CSIDL_DESKTOPDIRECTORY

File system directory used to physically store file objects on the desktop (not to be confused with the desktop folder itself).

CSIDL_DRIVES

My Computer --- virtual folder containing everything on the local computer: storage devices, printers, and Control Panel. The folder may also contain mapped network drives.

CSIDL_FONTS

Virtual folder containing fonts.

CSIDL_NETHOOD

File system directory containing objects that appear in the network neighborhood.

CSIDL_NETWORK

Network Neighborhood --- virtual folder representing the top level of the network hierarchy.

CSIDL_PERSONAL

File system directory that serves as a common repository for documents.

CSIDL_PRINTERS

Printers folder --- virtual folder containing installed printers.

CSIDL_PROGRAMS

File system directory that contains the user's program groups (which are also file system directories).

CSIDL_RECENT

File system directory that contains the user's most recently used documents.

CSIDL_SENDTO

File system directory that contains Send To menu items.

CSIDL_STARTMENU

File system directory containing Start menu items.

CSIDL_STARTUP

File system directory that corresponds to the user's Startup program group.

CSIDL_TEMPLATES

File system directory that serves as a common repository for document templates.

Not all options make sense in all functions!

SW_

SW_HIDE

Hides the window and activates another window.

SW_MAXIMIZE

Maximizes the specified window.

SW_MINIMIZE

Minimizes the specified window and activates the next top-level window in the z-order.

SW_RESTORE

Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.

SW_SHOW

Activates the window and displays it in its current size and position.

SW_SHOWDEFAULT

Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window.

SW_SHOWMAXIMIZED

Activates the window and displays it as a maximized window.

SW_SHOWMINIMIZED

Activates the window and displays it as a minimized window.

SW_SHOWMINNOACTIVE

Displays the window as a minimized window. The active window remains active.

SW_SHOWNA

Displays the window in its current state. The active window remains active.

SW_SHOWNOACTIVATE

Displays a window in its most recent size and position. The active window remains active.

SW_SHOWNORMAL

Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

Variables

 $Win32::FileOp::ProgressTitle

This variable (if defined) contains the text to be displayed on the progress dialog if using FOF_SIMPLEPROGRESS. This allows you to present the user with your own message about what is happening to his computer.

If the options for the call do not contain FOF_SIMPLEPROGRESS, this variable is ignored.

Examples

    use Win32::FileOp;

    CopyConfirm ('c:\temp\kinter.pl' => 'c:\temp\copy\\',
                 ['\temp\kinter1.pl', 'temp\kinter2.pl']
                 => ['c:\temp\copy1.pl', 'c:\temp\copy2.pl']);

    $Win32::FileOp::ProgressTitle = "Moving the temporary files ...";
    MoveEx 'c:\temp\file.txt' => 'd:\temp\\',
           ['c:\temp\file1.txt','c:\temp\file2.txt'] => 'd:\temp',
           FOF_RENAMEONCOLLISION | FOF_SIMPLEPROGRESS;
    undef $Win32::FileOp::ProgressTitle;

    Recycle 'c:\temp\kinter.pl';

Handles

All the functions keep Win32::API handles between calls. If you want to free the handles you may undefine them, but NEVER EVER set them to anything else than undef !!! Even "$handlename = $handlename;" would destroy the handle without repair! See docs for Data::Lazy.pm for explanation.

List of handles and functions that use them:

 $Win32::FileOp::fileop : Copy, CopyEx, CopyConfirm, Move, MoveEx, MoveConfirm
  Delete, DeleteEx, DeleteConfirm, Recycle, RecycleEx, RecycleConfirm
 $Win32::FileOp::movefileex : MoveFileEx MoveFile MoveAtReboot
 $Win32::FileOp::movefileexDel : DeleteAtReboot
 $Win32::FileOp::copyfile : CopyFile
 $Win32::FileOp::writeINI : WriteToINI MoveAtReboot DeleteAtReboot
 $Win32::FileOp::writeWININI : WriteToWININI
 $Win32::FileOp::deleteINI : DeleteFromINI
 $Win32::FileOp::deleteWININI : DeleteFromWININI
 $Win32::FileOp::readINI : ReadINI
 $Win32::FileOp::readWININI : ReadWININI
 $Win32::FileOp::GetOpenFileName : OpenDialog
 $Win32::FileOp::GetSaveFileName : SaveAsDialog
 $Win32::FileOp::SHAddToRecentDocs : AddToRecentDocs EmptyRecentDocs
 $Win32::FileOp::DesktopHandle
 $Win32::FileOp::WindowHandle : OpenDialog SaveDialog
 $Win32::FileOp::WNetAddConnection3 : Map
 $Win32::FileOp::WNetGetConnection : Mapped
 $Win32::FileOp::WNetCancelConnection2 : Unmap Disconnect Map
 $Win32::FileOp::GetLogicalDrives : FreeDriveLetters Map

Notes ^

By default all functions are exported! If you do not want to polute your namespace too much import only the functions you need. You may import either single functions or whole groups.

The available groups are :

 BASIC = Move..., Copy..., Recycle... and Delete... functions plus constants
 _BASIC = FOF_... constants only
 HANDLES = DesktopHandle GetDesktopHandle WindowHandle GetWindowHandle
 INI = WriteToINI WriteToWININI ReadINI ReadWININI ReadINISectionKeys
       DeleteFromINI DeleteFromWININI
 DIALOGS = OpenDialog, SaveAsDialog and BrowseForFolder plus OFN_...,
           BIF_... and CSIDL_... constants
 _DIALOGS = only OFN_..., BIF_... and CSIDL_... constants
 RECENT = AddToRecentDocs, EmptyRecentDocs
 DIRECTORY = UpdateDir, FillInDir
 COMPRESS => Compress Uncompress Compressed SetCompression GetCompression
             CompressedSize CompressDir UncompressDir
 MAP => Map Unmap Disconnect Mapped
 SUBST => Subst Unsubst Substed SubstDev

Examples:

 use Win32::FileOp qw(:BASIC GetDesktopHandle);
 use Win32::FileOp qw(:_BASIC MoveEx CopyEx);
 use Win32::FileOp qw(:INI :_DIALOGS SaveAsDialog);

This module contains all methods from Win32::RecycleBin. The only change you have to do is to use this module instead of the old Win32::RecycleBin. Win32:RecycleBin is not supported anymore!

TO-DO ^

WNetConnectionDialog, WNetDisconnectDialog

COPYRIGHT

Copyright (c) 1997-2013 Jan Krynicky <Jenda@Krynicky.cz>, $Bill Luebkert <dbe@wgn.net> and Mike Blazer <blazer@peterlink.ru>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

AUTHORS ^

 Module built by :
  Jan Krynicky <Jenda@Krynicky.cz>
  $Bill Luebkert <dbe@wgn.net>
  Mike Blazer <blazer@peterlink.ru>
  Aldo Calpini <a.calpini@romagiubileo.it>
  Michael Yamada <myamada@gj.com>
  "Steve Waring" <stephenwaring@btopenworld.com>
syntax highlighting: