User global hook to monitor the Open/Read/Modify operations of a file.

Zhu Jeremy 1 Reputation point
2020-12-11T05:36:05.013+00:00

Hi,

I have a question about Windows API during the development of desktop app. I want to monitor the operation of files, and get the operation information of a target file in the system.
I have already known that it can be achieved by FileSystemWatcher, it can monitor Created/Deleted/Changed/Renamed file operation of target file or target directory. But I also want to investigate whether there is a mothod like global hook.

Are there any suggestions?
Thank you very much.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,670 questions
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
322 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. DaisyTian-1203 11,616 Reputation points
    2020-12-11T07:21:54.593+00:00

    HwndSource.AddHook(HwndSourceHook) Method can add event handler that receives all window messages, is it what you want? If it is, you can use it like below.

    public MainWindow()  
            {  
                InitializeComponent();  
                //SourceInitialized += WSInitialized;  
                SourceInitialized += HandleInitialized;  
            }  
    
        public void HandleInitialized(object o, EventArgs e)  
        {  
            IntPtr wptr = new WindowInteropHelper(this).Handle;  
            HwndSource hs = HwndSource.FromHwnd(wptr);  
            hs.AddHook(new HwndSourceHook(WpfHandleWinowMsg));  
        }  
    
        public IntPtr WpfHandleWinowMsg(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)  
        {  
            switch (msg)  
            {  
                case 1:  
                    break;  
                case 2:  
                    break;  
                default:  
    
                    break;  
            }  
            return IntPtr.Zero;  
        }  
    

    By the way, if I misunderstand, please point out.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Castorix31 81,636 Reputation points
    2020-12-15T09:27:24.997+00:00

    You can use API hooking on APIs like NtCreateFile, but it is complex
    Otherwise, you can also use SHChangeNotifyRegister