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

May I point to the WindowsFolderChangeMBS class in MBS Xojo Win Plugin to do this?

It does the watching on a preemptive thread to not miss an even and root them to the main thread for you to pick up.

1 Like

WaitForSingleObject is intended to be used from a preemptive background thread. Xojo apps don’t (yet) support preemptive threads, so waiting affects your whole app.

Try changing -1 (infinite wait) to 1 (shortest wait) and perform the loop on a regular Xojo thread.
In other words call WaitForSingleObject to poll for changes rather than wait for them. This should keep the GUI responsive.

1 Like

Is there a way to make a Declare accessible to the whole class ? or module ? and if yes, then how ? as so far it seems that XOJO keeps on complaining about those if i separate them

Take a look at external methods.

Thanks Kevin, found it and finally made it work.

Thanks all of you, works great so far and does what i need.