Quantcast
Viewing all articles
Browse latest Browse all 3773

Folder change monitor - Windows and possible MacOS

Hello Guys,

Is there a way to have something running on windows that would monitor a folder for changes and then notify the app ?

I did managed to find some code but it seems that no matter where i put it, the app becomes unresponsive and then i need to kill it.

Declare Function FindFirstChangeNotification Lib "Kernel32" Alias "FindFirstChangeNotificationA" (lpPathName As CString, bWatchSubtree As Integer, dwNotifyFilter As Integer) As Integer
Declare Function FindNextChangeNotification Lib "Kernel32" (hChangeHandle As Integer) As Integer
Declare Function WaitForSingleObject Lib "Kernel32" (hHandle As Integer, dwMilliseconds As Integer) As Integer
Declare Function CloseHandle Lib "Kernel32" (hObject As Integer) As Integer

Const FILE_NOTIFY_CHANGE_FILE_NAME = &H1
Const FILE_NOTIFY_CHANGE_DIR_NAME = &H2
Const FILE_NOTIFY_CHANGE_ATTRIBUTES = &H4
Const FILE_NOTIFY_CHANGE_SIZE = &H8
Const FILE_NOTIFY_CHANGE_LAST_WRITE = &H10
Const FILE_NOTIFY_CHANGE_SECURITY = &H100

Sub MonitorFolder(folderPath As String)
  Dim handle As Integer
  handle = FindFirstChangeNotification(folderPath, 1, FILE_NOTIFY_CHANGE_LAST_WRITE)
  
  If handle = -1 Then
    MsgBox("Error starting folder monitoring.")
    Return
  End If
  
  While True
    Dim result As Integer
    result = WaitForSingleObject(handle, -1) ' Wait indefinitely for changes
    
    If result = 0 Then ' Change occurred
      ' Process the file change here
      ' For example, update your UI or trigger some action
      
      ' Continue monitoring
      If FindNextChangeNotification(handle) = 0 Then
        MsgBox("Error continuing folder monitoring.")
        Exit While
      End If
    ElseIf result = &H102 Then ' Timeout
      ' No changes occurred within the timeout period
      ' You can handle this case if needed
    Else
      MsgBox("Error waiting for folder changes.")
      Exit While
    End If
  Wend
  
  ' Cleanup
  CloseHandle(handle)
End Sub

Thanks

6 posts - 4 participants

Read full topic


Viewing all articles
Browse latest Browse all 3773

Trending Articles