Rafe
Rafe

Reputation: 9275

windows api - detect when file of certain type is opened

Is it possible to have certain code executed whenever a file of a certain type is opened? In my case, I want to "listen" for when video files (".avi, mp4, etc.") are opened (either via the windows file explorer shell, or maybe directly from a video player?), so that I can store a history of played videos.

An hour's worth of googling turned up nothing, so I turn to you stackoverflow. Please point me in the right direction.

Thanks.

Upvotes: 2

Views: 2658

Answers (2)

Bukes
Bukes

Reputation: 3708

The best (and only reasonable way) to capture file system events (open/read/write) from arbitrary processes is by writing a File System MiniFilter

If you're developing a commercial product, please refrain from "hooking" Usermode APIs like CreateFile. Doing so requires numerous, platform-specific hacks, and is a compatibility nightmare.

Upvotes: 5

Jerry Coffin
Jerry Coffin

Reputation: 490108

I wouldn't hook CreateFile for this job. Windows has mechanisms built-in to handle jobs like this much more cleanly.

The easy way to handle this would be with ReadDirectoryChangesW with the FILE_NOTIFY_CHANGE_LAST_ACCESS flag. Any time a file is opened, its last-access time will be updated, so this tells you any time the file was opened.

Although it's pretty rare, that can "miss" changes under rare circumstances1. If you must have 100% accuracy (instead of, say, 99.9%), you can read change journals instead, but it's a fair amount of extra work for an advantage you may not care about.


1. There is one circumstance that isn't (necessarily) rare that you might care about though: ReadDirectoryChangesW will only work when/if your program is running. Change journals will let you know about things that happened even when your code isn't running at all.

Upvotes: 1

Related Questions