WatchFileSystem – Surveillance des fichiers et répertoires Windows en temps réel
Module PureBasic de surveillance des répertoires Windows. Détecte en temps réel les ajouts, suppressions, modifications et renommages de fichiers et dossiers grâce à l'API native ReadDirectoryChangesW.
WatchFileSystem – Surveillance des répertoires Windows
WatchFileSystem est un module PureBasic permettant de surveiller automatiquement les modifications apportées au contenu d'un ou plusieurs répertoires sous Windows. Basé sur l'API native Windows ReadDirectoryChangesW, il détecte les événements liés aux fichiers et aux dossiers, puis transmet les informations à l'application principale sous forme d'événements personnalisés.
Le module fonctionne en arrière-plan grâce à un thread dédié pour chaque répertoire surveillé, permettant ainsi de suivre plusieurs emplacements simultanément sans bloquer l'interface de l'application.
Événements détectés :
- ADDED : ajout d'un fichier ou dossier.
- REMOVED : suppression d'un fichier ou dossier.
- MODIFIED : modification d'un fichier.
- RENAMED_OLDNAME : ancien nom lors d'un renommage.
- RENAMED_NEWNAME : nouveau nom après renommage.
Filtres de surveillance :
Il est possible de choisir les types de modifications à détecter : noms de fichiers, noms de répertoires, attributs, taille, date de modification, date de dernier accès, création et sécurité.
Intégration :
Le module est conçu pour être facilement intégré dans un projet PureBasic. Il suffit d'initialiser la surveillance d'un répertoire, de récupérer les événements générés et de fermer le thread lorsque la surveillance n'est plus nécessaire.
Le code source
; +======================================================+
; | |
; +------------------------------------------------------+
; | COPYRIGHT(C)2025-2026, ALL RIGHT RESERVED KOAKDESIGN |
; +--------------+---------------------------------------+
; | Program type | PUREBASIC 5.71 LTS (MODULE) |
; +--------------+---------------------------------------+
; | VER & REV | 0.0.1 |
; +--------------+---------------------------------------+
; | Program name | |
; +======================================================+
; +======================================================+
; | Original Version: 0.0.1 |
; +--------------+---------------------------------------+
; | Created by | GallyHomeCorp |
; | Graphix by | GallyHomeCorp |
; +--------------+---------------------------------------+
; | Comments: | |
; +--------------+ |
; | |
; | |
; | |
; +======================================================+
; +==========================+===========================+
; | Operating System | Gestion Compilation |
; +----------------------+---+-----------------------+---+
; | Window | X | Gestion Thread | X |
; | Linux | | Gestion OnError | |
; | MacOS | | | - |
; +----------------------+---+-----------------------+---+
; | x32 | X | Droit Administrateur | |
; | X64 | X | Droit particulier | |
; +======================+===+=======================+===+
;
; ****************************************************************************
DisableASM
CompilerIf #PB_Compiler_EnableExplicit
EnableExplicit
CompilerEndIf
; ****************************************************************************
;-DeclareModule
DeclareModule WatchFileSystem
#FILE_NOTIFY_CHANGE_FILE_NAME = 1
#FILE_NOTIFY_CHANGE_DIR_NAME = 2
#FILE_NOTIFY_CHANGE_ATTRIBUTES = 4
#FILE_NOTIFY_CHANGE_SIZE = 8
#FILE_NOTIFY_CHANGE_LAST_WRITE = $10
#FILE_NOTIFY_CHANGE_LAST_ACCESS = $20
#FILE_NOTIFY_CHANGE_CREATION = $40
#FILE_NOTIFY_CHANGE_SECURITY = $100
#FILE_NOTIFY_CHANGE_ALL = $17F
#EVENT_WATCHFILESYSTEM = $7A01
Structure WatchFSEvent_t
Path.s
Filename.s
Action.i
label.s
Handle.i
EndStructure
Declare.i WatchFileSystem (DirectoryName.s, NotifyFilter.i = #FILE_NOTIFY_CHANGE_FILE_NAME)
Declare.i CloseWatchFileSystem (Handle.i)
EndDeclareModule
; ****************************************************************************
;-Module
Module WatchFileSystem
DisableASM
CompilerIf #PB_Compiler_EnableExplicit = 0
EnableExplicit
CompilerEndIf
; ****************************************************************************
#FILE_SHARE_DELETE = 4
Enumeration 1 Step 1
#FILE_ACTION_ADDED
#FILE_ACTION_REMOVED
#FILE_ACTION_MODIFIED
#FILE_ACTION_RENAMED_OLD_NAME
#FILE_ACTION_RENAMED_NEW_NAME
EndEnumeration
; ****************************************************************************
Structure WatchFSParam_t
NotifyFilter.i
Path.s
Filter.s
IncludeSubdirectories.b
WindowID.i
ThreadHandle.i
EndStructure
Structure FILE_NOTIFY_INFORMATION
NextEntryOffset.l
Action.l
FileNameLength.l
EndStructure
; ****************************************************************************
; Import "ReadDirectoryChangesW" de la DLL "kernel32.lib"
Import "kernel32.lib"
ReadDirectoryChangesW(hDirectory.i, *lpBuffer, nbBufferLen.l, bWatchSubTree.b, dwNotifyFilter.i, *lpBytesReturned, *lpOverlapped.OVERLAPPED, lpCompletitionRoutine)
EndImport
; ****************************************************************************
; Méthode de vérification si un répertoire change.
;
; @author GallyHomeCorp
; @param *params.WatchFSParam_t
; @return
Procedure.i WatchDirOrFile(*params.WatchFSParam_t)
Protected.i bytesRead, dwOffset = 0
Protected *buffer = AllocateMemory(32 * 1024)
Protected *ovlp.OVERLAPPED = AllocateMemory(SizeOf(OVERLAPPED))
Protected *pInfo.FILE_NOTIFY_INFORMATION
Protected *evt.WatchFSEvent_t
Protected.i action
Protected.s filename, label
Protected.i hDir = CreateFile_(*params\Path, #FILE_LIST_DIRECTORY, #FILE_SHARE_READ | #FILE_SHARE_WRITE | #FILE_SHARE_DELETE, #Null, #OPEN_EXISTING, #FILE_FLAG_BACKUP_SEMANTICS, #Null)
While ReadDirectoryChangesW(hDir, *buffer, MemorySize(*buffer), #True, *params\NotifyFilter, bytesRead, *ovlp, #Null)
dwOffset = 0
Repeat
*pInfo = *buffer + dwOffset
filename = PeekS(*pInfo + 12, *pInfo\FileNameLength >> 1, #PB_Unicode)
label = #Null$
action = *pInfo\Action
Select *pInfo\Action
Case #FILE_ACTION_ADDED
label = "ADDED"
Case #FILE_ACTION_MODIFIED
label = "MODIFIED"
Case #FILE_ACTION_REMOVED
label = "REMOVED"
Case #FILE_ACTION_RENAMED_OLD_NAME
label = "RENAMED_OLDNAME"
Case #FILE_ACTION_RENAMED_NEW_NAME
label = "RENAMED_NEWNAME"
EndSelect
*evt = AllocateMemory(SizeOf(WatchFSEvent_t))
*evt\Path = *params\Path
*evt\Filename = filename
*evt\Action = action
*evt\label = label
*evt\Handle = *params\ThreadHandle
PostEvent(#EVENT_WATCHFILESYSTEM, *params\WindowID, 0, 0, *evt)
dwOffset + *pInfo\NextEntryOffset
Until *pInfo\NextEntryOffset = 0
Wend
EndProcedure
; ****************************************************************************
; Méthode d'initialisation du système "WatchFileSystem".
;
; @author GallyHomeCorp
; @param DirectoryName.s
; @param NotifyFilter.i
; @return
Procedure.i WatchFileSystem(DirectoryName.s, NotifyFilter.i = #FILE_NOTIFY_CHANGE_FILE_NAME)
If FileSize(DirectoryName) = -2
Protected *watcherparams.WatchFSParam_t = AllocateMemory(SizeOf(WatchFSParam_t))
*watcherparams\Path = DirectoryName
*watcherparams\NotifyFilter = NotifyFilter
*watcherparams\IncludeSubdirectories = #True
*watcherparams\ThreadHandle = CreateThread(@WatchDirOrFile(), *watcherparams)
ProcedureReturn *watcherparams\ThreadHandle
Else
Debug "Not directory -> " + DirectoryName
EndIf
EndProcedure
; Méthode de fermeture du système "WatchFileSystem".
;
; @author GallyHomeCorp
; @param DirectoryName.s
; @param NotifyFilter.i
; @return
Procedure.i CloseWatchFileSystem(Handle.i)
If Handle
KillThread(Handle)
EndIf
EndProcedure
EndModule
; ****************************************************************************
CompilerIf #PB_Compiler_IsMainFile = 1
If OpenWindow(0, 0, 0, 900, 900, "WatchFileSystem", #PB_Window_SystemMenu|#PB_Window_ScreenCentered)
ListViewGadget(0, 10, 10, 880, 880)
Define.i ThreadeA = WatchFileSystem::WatchFileSystem("C:\temp\")
Define.i ThreadeB = WatchFileSystem::WatchFileSystem("C:\Users\")
Define.i event
Define *evtData.WatchFileSystem::WatchFSEvent_t
Repeat
event = WaitWindowEvent()
Select event
Case WatchFileSystem::#EVENT_WATCHFILESYSTEM
*evtData = EventData()
Select *evtData\Handle
Case ThreadeA
AddGadgetItem(0, -1, "[A] " + *evtData\Filename + " -> " + *evtData\Path + " -> " + *evtData\label)
Case ThreadeB
AddGadgetItem(0, -1, "[B] " + *evtData\Filename + " -> " + *evtData\Path + " -> " + *evtData\label)
EndSelect
FreeMemory(*evtData)
*evtData = #Null
EndSelect
Until event = #PB_Event_CloseWindow
WatchFileSystem::CloseWatchFileSystem(ThreadeA)
WatchFileSystem::CloseWatchFileSystem(ThreadeB)
EndIf
CompilerEndIf
