sub/function as datatype

Forum for discussion about the documentation project.
grindstone
Posts: 862
Joined: May 05, 2015 5:35
Location: Germany

Re: sub/function as datatype

Post by grindstone »

Tourist Trap wrote:If someone knew how this has to be done it would be really interesting.
Here you are:

Code: Select all

 'this example would be useful to poll a change from inside a folder
'but would require its async version in order to be really useful -> implies callback

#Include "windows.bi"

'https://docs.microsoft.com/fr-fr/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw

Var hDir = CreateFile ( _
    "E:\Temp\WATCHTEST",_   'enter a directory here
    GENERIC_READ, _
    FILE_SHARE_READ + FILE_SHARE_WRITE + FILE_SHARE_DELETE, _
    NULL, _
    OPEN_EXISTING, _
    FILE_FLAG_BACKUP_SEMANTICS, _
    NULL _
)

? "watching dir num ..."; hDir

Dim As FILE_NOTIFY_INFORMATION Ptr  fNIptr
fNIptr = Allocate(SizeOf(FILE_NOTIFY_INFORMATION))

Dim As LPDWORD  outbuffer
outbuffer = Allocate(SizeOf(DWORD))

Dim r As Integer
Dim As OVERLAPPED ol

Sub FileIOCompletionRoutine(dwErrorCode As DWORD, _
	                          dwNumberOfBytesTransfered As DWORD, _
	                          lpOverlapped As OVERLAPPED Ptr)
	?
	? "Hello, I'm the FileIOCompletionRoutine"                           
	?	                          
End Sub

Do
    r = ReadDirectoryChangesW( _
      hDir, _
      fNIptr, _ 'LPVOID lpBuffer :: pointer to a FILE_NOTIFY_INFORMATION, _
      SizeOf(fNIptr), _ 'DWORD nBufferLength, _
      0, _ 'BOOL bWatchSubtree, _
      FILE_NOTIFY_CHANGE_FILE_NAME Or FILE_NOTIFY_CHANGE_DIR_NAME	, _ 'DWORD dwNotifyFilter, _
      outbuffer, _ 'LPDWORD lpBytesReturned, _
      @ol, _ 'LPOVERLAPPED lpOverlapped, _
      @FileIOCompletionRoutine _ 'LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine _
    )
   
    ? r 'this shows nothing because we are not in the insynchronous case, which would require callback
    SleepEx(10000, TRUE)
Loop Until r<>0 Or InKey()=Chr(27)

? "you created or deleted a file in the folder"

Sleep
Tourist Trap
Posts: 2958
Joined: Jun 02, 2015 16:24

Re: sub/function as datatype

Post by Tourist Trap »

grindstone wrote:Here you are
Thanks. The SleepEx function is quite interesting. It breaks the sleep as soon as the event is created IF there is a callback. Otherwise the event is triggered and the readdirectory stuff breaks its polling for event loop, but the sleep keeps going - until the delay has passed.

So SleepEx reacts to the existence of a callback, and also to the alertable state set TRUE.

I need now to add some threading to this. Thanks again.
Post Reply