tags:

views:

314

answers:

5

I need to generate an event when a file is closed by another app.

Unfortunately, ReadDirectoryChangesW doesn't report the close event. It would be possible for me to poll (with a TTimer) any file that reported by ReadDirectoryChangesW as modified, waiting for it to be closed (using CreateFile to detect this).

However, what I'd prefer is a completely event driven solution.

Is there a way to hook system calls and detect all file closing events? I simply want to know the path & name of any file that has just been closed.

+7  A: 

There is no good simple solution to your problem in Delphi alone - the real solution is to write a filter driver to monitor file closing events.

Serg
+5  A: 

You should take a look at Mathias Rauens madCodeHook:

madCodeHook offers everything you need to hook code (mostly APIs) in all 32 and 64 bit Windows operating systems from Windows 95 to Windows 7. You can choose whether you want to hook APIs in your own process, or in a specific target process, or system wide.

Vegar
A: 

Inside Jedi Code LIbrary (JCL), you have a component named 'TJvChangeNotify' where you can get notification when a change has been detected in a monitored directory :

  • Changed 'Last write' => So it seems to be the exact thing you wanted to do !

Other things it can do :

  • Changed file size
  • Changed file name ...

And best of all, it search inside a folder with subdirectories if you want. Here is a link to (part of) help file for this component: http://help.delphi-jedi.org/item.php?Id=172982

Hope this will help.

TridenT
The question mentions specifically why this isn't what OP is after.
mghie
-1: clearly stated this was not an option.
Ritsaert Hornstra
TridenT
A: 

If change notifications wo't work you might use a very crude and lame method: polling. Every second or so, try to open the file with some incompatible share options. The moment this succeesds, you know that the other application has closed it down.

Not the cleanest option by far, but it will work. This is only an option if you need to monitor a limited number of files and their names are known in advance.

Ritsaert Hornstra
That is mentioned in the question as a possible (lame) solution, so why repeat it?
mghie
I just stated the obvious perhaps, but I think the pro's cons and impossibilities havan't been mentioned. That's why.
Ritsaert Hornstra
You don't mention any impossibility. It's possible to monitor an unlimited number of files this way, whose names need not be known in advance, and the OP says so in his question. You don't mention the real limitation, namely that this will possibly interfere with other programs (it can cause their reopening of watched files to fail).
mghie
+1  A: 

If you choose to go the filter driver route, Eldos has the CallbackFilter component:

http://www.eldos.com/cbflt/spec.php

Mick