Using Win32 functions in Visual FoxPro Image Gallery
Error Handling
..msdn
Beep
FatalAppExit
FlashWindow
FlashWindowEx
FormatMessage
GetErrorMode
GetLastError
MessageBeep
SetErrorMode
SetLastError
Code examples:
A class that encrypts and decrypts files using Cryptography API Functions
Adding printer to the list of supported printers for the specified server
Basic Volume information
Capturing keyboard activity of another application with the Raw Input API (VFP9)
Closing Windows
Compressing and decompressing files with Windows API Runtime Library routines
Converting command-line string to a set of Unicode argument strings (WinNT only)
Converting long file names to the short format and vice versa
Converting Unicode data from the Clipboard to a character string using a given code page
Copying files as a transacted operation (Vista)
Creating a console window for Visual FoxPro application
Creating a device context for the specified printer
Creating a folder
Creating a mailslot
CryptoAPI: Collection of Providers class
Custom FTP Class for Visual FoxPro application
Custom HttpRequest class (WinHTTP)
Custom HttpRequest class (WinINet)
Determining if an Active Network Connection is Available
DiskFreeSpace class
Displaying bitmap using the AlphaBlend function
Displaying dimmed window behind VFP top-level form
Encapsulating access to the Windows Services in a class
Enumerating forms supported by a specified printer
Enumerating ports that are available for printing on a specified server
Enumerating print jobs and retrieving information for default printer (JOB_INFO_1 structures)
Enumerating print processors and supporting data types installed on the specified server
Enumerating printer drivers installed
Enumerating Processes -- WinNT
Enumerating the subkeys of a user-specific key
Finding parameters for the region specified
GetFileOwner - Get the owner of an NTFS file
Getting a bit more than the _CLIPTEXT offers
How to access a file using not its name but an alias (hard link)
How to adjust monitor brightness (Vista, monitor with DDC support)
How to block the ALT+TAB shortcut (WinXP)
How to block the PrintScreen key
How to create a service object
How to create MD-5 and SHA-1 hash values from a string
How to delete a service object
How to delete all print jobs for a printer
How to delete IE cookies, clear IE history and delete files in Temporary Internet Files directory
How to display a user-defined icon in the MessageBox dialog
How to display the port-configuration dialog box for a port on the specified server
How to display the Properties dialog box for a file (ShellExecuteEx)
How to download this reference`s archive through WinInet functions using InternetOpenUrl
How to enable the SE_SHUTDOWN_NAME privilege for the application
How to enumerate cookies and URL History entries in the cache of the local computer
How to enumerate sessions and processes on a specified terminal server
How to enumerate terminal servers within the specified Windows domain
How to extract frames from AVI files
How to fill a buffer with random bytes using Cryptography API Functions
How to find the application associated with a file name
How to find when the application started
How to find which fonts Windows uses for drawing captions, menus and message boxes
How to initiate System shutdown
How to make application automatically close all documents it opened
How to ping a remote site using IP Helper API calls
How to play AVI file on the _screen
How to prevent users from accessing the Windows Desktop and from switching to other applications
How to retrieve configuration data for a specified printer stored in the registry (PrinterDriverData key)
How to retrieve information about a cache entry (Internet Explorer)
How to retrieve the number of print jobs queued for the printer
How to retrieve version information for the specified file
How to run FoxPro application under different user name (impersonating user)
How to save registry key including its subkeys and values to a file
How to set Creation Date/Time for a folder (WinNT)
How to Start a Process as Another User (NT/XP/2K)
How to test file attributes (key method for FileExists and DirectoryExists routines)
How to write and read Window Properties for the specified window
HOWTO: Use the Win32 API to Access File Dates and Times
Locking and unlocking file of a VFP table
Locking the workstation
Monitoring changes occurring within a directory
Obtaining I/O counts for the current process
Obtaining physical parameters for a drive: sectors, clusters, cylinders...
Peer-to-peer LAN messenger built with Mailslot API functions
Placing an arbitrary rectangular area of main VFP window on the Clipboard
Printing Image File, programmatically set print page orientation to landscape
Reading and setting system access privileges for the current process
Reading current hardware profile
Reading entries from Event logs
Reading security permissions for NTFS files and folders
Reading the structure of VFP main menu
Removing FTP directory
Retrieveing information about the active window (even if it is not owned by the calling process)
Retrieving a handle to DLL and address of an exported function in it
Retrieving graphic capabilities of default printer
Retrieving local computer and user names
Retrieving the name of the default printer for the current user on the local computer (Win NT/XP)
Retrieving the System Time adjustment
Scanning a hierarchy of child windows down from the Windows Desktop
Setting the date and time that a file was created
Setting the last-error code for the FoxPro
Setting the volume label
Setting the Window Region for a form
Simple printer queue monitor: deletes, pauses, resumes print jobs for local printer
Start an executable from VFP application by using the CreateProcess
Starting external program from VFP and waiting for its termination
Storing registration key in the resources of an executable file
Testing serial ports
The DetectAutoProxyUrl function identifies the auto-config script location
Using Change Notification Objects to monitor changes to the printer or print server
Using EnumPrinters function to enumerate locally installed printers
Using File Mapping for enumerating files opened by Visual FoxPro
Using FtpCommand
Using LoadLibrary
Using named pipes for interprocess communication
Using shared memory to exchange data between two FoxPro applications
Using the CreateFile
Using the NetMessageBufferSend to send messages on the network
Using the Semaphore object
Using the Semaphore object to allow only one instance of VFP application running
Validating the heap of the calling process
Wininet last error description
Winsock: retrieving information from a host database for a given host name
Writing entries to custom Event Log
Using File Mapping for enumerating files opened by Visual FoxPro

User rating: 9/10 (1 votes)
Rate this code sample:
  • ~
More code examples    Listed functions    Add comment     W32 Constants      Translate this page Printer friendly version of this code sample
Before you begin:
File mapping is the association of the contents of a file with a portion of the virtual address space of a process.

API function GetMappedFileName called in combination with CreateFileMapping and MapViewOfFile functions is able to retrieve the name for a given file handle.

The following code scans range of possible file handles from 1 to 1024 trying to obtain a file name from each of them.

 
#DEFINE PAGE_READONLY 2
#DEFINE PAGE_READWRITE 4
#DEFINE PAGE_WRITECOPY 8
#DEFINE PAGE_EXECUTE_READ 0x20
#DEFINE PAGE_EXECUTE_READWRITE 0x40
 
#DEFINE SECTION_QUERY 1
#DEFINE SECTION_MAP_WRITE 2
#DEFINE SECTION_MAP_READ 4
#DEFINE SECTION_MAP_EXECUTE 8
#DEFINE SECTION_EXTEND_SIZE 0x10
#DEFINE STANDARD_RIGHTS_REQUIRED 0xF0000
 
#DEFINE SECTION_ALL_ACCESS BITOR(STANDARD_RIGHTS_REQUIRED,;
    SECTION_QUERY, SECTION_MAP_WRITE, SECTION_MAP_READ,;
    SECTION_MAP_EXECUTE, SECTION_EXTEND_SIZE)
 
#DEFINE FILE_MAP_WRITE SECTION_MAP_WRITE
#DEFINE FILE_MAP_READ SECTION_MAP_READ
#DEFINE FILE_MAP_ALL_ACCESS SECTION_ALL_ACCESS
 
#DEFINE INVALID_HANDLE_VALUE -1
#DEFINE MAX_PATH 260
 
DO declare
DO ScanDevices
 
PRIVATE cFilename, nError, nFileSize, nFileType, hFileIndex, hProcess
cFilename=""
STORE 0 TO nError
* obtain (pseudo) handle for the current process
hProcess=GetCurrentProcess()
 
* try to open a file using FoxPro low-level file functions
LOCAL hFile1
hFile1 = FOPEN("MYFILE.TXT", 2)
? "hFile1:", hFile1
 
CREATE CURSOR cs (hfile I, errorcode I, filename C(250),;
    filesize I, filetype I)
 
FOR hFileIndex=1 TO 4096
    nError=0
    cFilename=""
    nFileSize = GetFileSize(hFileIndex)
    nFileType = GetFileType(hFileIndex)
 
    * both modes should match, for example:
    * PAGE_READONLY, SECTION_MAP_READ
    * PAGE_READWRITE, SECTION_MAP_WRITE
    = GetName(hFileIndex, PAGE_READONLY, SECTION_MAP_READ)
 
    INSERT INTO cs VALUES (m.hFileIndex, m.nError,;
        m.cFilename, m.nFilesize, m.nFileType)
NEXT
 
IF hFile1 <> INVALID_HANDLE_VALUE
    = FCLOSE(hFile1)
ENDIF
 
BROWSE NORMAL FOR errorcode=0 NOWAIT
* end of main
 
PROCEDURE GetName(hFile, nCreateFlag, nMapFlag)
    LOCAL hFileMap, hMem, cBuffer, nBufsize
 
    hFileMap = CreateFileMapping(hFile, 0, nCreateFlag, 0,1, Null)
    IF hFileMap <= 0
        nError=GetLastError()
        RETURN
    ENDIF
 
    hMem = MapViewOfFile(hFileMap, nMapFlag, 0,0,1)
    IF hMem = 0
        nError=GetLastError()
        cBuffer=""
    ELSE
        cBuffer = REPLICATE(CHR(0), MAX_PATH)
        nBufsize = GetMappedFileName(hProcess, hMem,;
            @cBuffer, MAX_PATH)
 
        IF nBufsize=0
            nError=GetLastError()
            cBuffer=""
        ELSE
            cBuffer = SUBSTR(cBuffer, 1, nBufsize)
        ENDIF
        = UnmapViewOfFile(hMem)
    ENDIF
    CloseHandle(hFileMap)
    cFilename=cBuffer
 
FUNCTION GetFileSize(hFile)
#DEFINE MAX_DWORD 0xffffffff
    LOCAL cBuffer
    cBuffer = REPLICATE(CHR(0), 8)
    IF GetFileSizeEx(hFile, @cBuffer) = 0
        RETURN 0
    ELSE
        RETURN buf2dword(SUBSTR(cBuffer,1,4)) +;
                buf2dword(SUBSTR(cBuffer,5,4)) * (MAX_DWORD+1)
    ENDIF
 
PROCEDURE ScanDevices
    CREATE CURSOR csDosDevices (drvletter C(2), targetpath C(250))
 
    LOCAL cDrives, nBufsize, cDrvLetter, ch, cTargetPath
    cDrives = REPLICATE(CHR(0), 250)
    nBufsize = GetLogicalDriveStrings(LEN(cDrives), @cDrives)
    cDrives = PADR(cDrives, nBufsize)
 
    cDrvLetter=""
    FOR nBufsize=1 TO LEN(cDrives)
        ch = SUBSTR(cDrives, nBufsize,1)
        IF ch = Chr(0)
            cDrvLetter=PADR(cDrvLetter,2)
            cTargetPath = REPLICATE(CHR(0), MAX_PATH)
 
            = QueryDosDevice(cDrvLetter, @cTargetPath,;
                LEN(cTargetPath))
 
            cTargetPath = STRTRAN(cTargetPath, CHR(0), "")
            INSERT INTO csDosDevices VALUES (;
                cDrvLetter, cTargetPath)
 
            cDrvLetter = ""
        ELSE
            cDrvLetter = cDrvLetter + m.ch
        ENDIF
    NEXT
 
PROCEDURE declare
    DECLARE INTEGER CloseHandle IN kernel32 INTEGER hObject
    DECLARE INTEGER GetLastError IN kernel32
    DECLARE INTEGER GetFileType IN kernel32 INTEGER hFile
    DECLARE INTEGER GetFileSizeEx IN kernel32;
        INTEGER hFile, STRING @lpFileSize
 
    DECLARE INTEGER CreateFileMapping IN kernel32;
        INTEGER hFile, INTEGER lpAttributes, INTEGER flProtect,;
        LONG dwMaximumSizeHi, LONG dwMaximumSizeLo, STRING lpName
 
    DECLARE LONG MapViewOfFile IN kernel32;
        INTEGER hFileMappingObject, INTEGER dwDesiredAccess,;
        LONG dwFileOffsetHi, LONG dwFileOffsetLo,;
        LONG dwNumberOfBytesToMap
 
    DECLARE INTEGER UnmapViewOfFile IN kernel32 LONG lpBaseAddress
    DECLARE INTEGER GetCurrentProcess IN kernel32
 
    DECLARE INTEGER GetMappedFileName IN psapi;
        INTEGER hProcess, INTEGER lpv,;
        STRING @lpFilename, INTEGER nSize
 
    DECLARE INTEGER OpenFile IN kernel32;
        STRING lpFileName, STRING @lpReOpenBuff, INTEGER wStyle 
 
    DECLARE INTEGER GetLogicalDriveStrings IN kernel32;
        INTEGER nBufferLength, STRING @lpBuffer
 
    DECLARE INTEGER QueryDosDevice IN kernel32;
        STRING lpDeviceName, STRING @lpTargetPath, LONG ucchMax
 
FUNCTION buf2dword(lcBuffer)
RETURN Asc(SUBSTR(lcBuffer, 1,1)) + ;
    BitLShift(Asc(SUBSTR(lcBuffer, 2,1)),  8) +;
    BitLShift(Asc(SUBSTR(lcBuffer, 3,1)), 16) +;
    BitLShift(Asc(SUBSTR(lcBuffer, 4,1)), 24)
 
 
 

User rating: 9/10 (1 votes)
Rate this code sample:
  • ~
4666 bytes  
Created: 2004-11-02 13:03:12  
Modified: 2009-02-03 15:26:42  
Visits in 7 days: 207  
Listed functions:
CloseHandle
CreateFileMapping
GetCurrentProcess
GetFileSizeEx
GetFileType
GetLastError
GetLogicalDriveStrings
GetMappedFileName
MapViewOfFile
OpenFile
QueryDosDevice
UnmapViewOfFile
Printer friendly API declarations
My comment:
The file handles are scanned in the context of current FoxPro application -- GetCurrentProcess API function is used to obtain the process handle.

Some file handles can not be accessed -- browse records with errorcode=5 (ERROR_ACCESS_DENIED).

Filenames are returned in \Device\HarddiskVolume..\ format.

As you can see, there are four handles per each open file. In Visual FoxPro, SYS(2010) always returns 255 -- these two values may be logically linked.

Visual FoxPro hides real file handle values. The FOPEN() returns the value from internal FoxPro table, not the value assigned by the OS.

Technically you may try to call the CloseHandle API for some handles on this list.

* * *

\Device\HarddiskVolume1 is the name of an object in the Windows kernel object hierarchy. It represents a device with the name HarddiskVolume1, which is the first volume of the hard disk. This device is normally mounted under the file-system name "c:", so the path is equivalent to c:\...

In the code sample above, the QueryDosDevice function is used to find the drive letters corresponding to the names like \Device\HarddiskVolume1 -- open cursor csDosDevices to see all.

* * *
Some links:
  • File Mapping, an article on MSDN
  • Obtaining a File Name From a File Handle, an article on MSDN
  • File Mapping Class Module on FreeVBcode.com
  • Faster File Access With File Mapping, an article written by Hernαn Moraldo
  • Low Level File Functions on FoxPro Wiki
  • Word Index links for this example:
    Translate this page:
      Spanish    Portuguese    German    French    Italian  
    FreeTranslation.com offers instant, free translations of text or web pages.
    User Contributed Notes:
    There are no notes on this subject.


    Copyright © 2001-2013 News2News, Inc. Before reproducing or distributing any data from this site please ask for an approval from its owner. Unless otherwise specified, this page is for your personal and non-commercial use. The information on this page is presented AS IS, meaning that you may use it at your own risk. Microsoft Visual FoxPro and Windows are trade marks of Microsoft Corp. All other trademarks are the property of their respective owners. 

    Privacy policy
    Credits: PHP (4.4.9), an HTML-embedded scripting language, MySQL (5.1.55-log), the Open Source standard SQL database, AceHTML Freeware Version 4, freeware HTML Editor of choice.   Hosted by Korax Online Inc.
    Last Topics Visited (107.21.186.38)
    3.28 hrs.Example: 'Writing to INI file'
     Function: 'RegDeleteValue'
     Example: 'Peer-to-peer LAN messenger built with Mailslot API functions'
    9.99 hrs.Example: 'Monitoring changes occurring within a directory'
    Language: 'C#'
     Example: 'Verifying a file using the Authenticode policy provider'
    10.1 hrs.Example: 'Retrieving list of Global Atom names'
    10.11 hrs.Function: 'gethostbyaddr'
    Function group: 'Windows Sockets 2 (Winsock)'
     Function: 'OpenInputDesktop'
    12.86 hrs.Function: 'GdipRotateWorldTransform'
    Function group: 'GDI+ Graphics'
    14.38 hrs.Function: 'PathCompactPathEx'
    Function group: 'Shell Lightweight Utility APIs -- Path Functions'
    Google
    Advertise here!