cwindowswinapi

Can I keep the handle open for the whole program lifetime


I have a class for my Windows application which controls the panel brightness.

        h = CreateFile(displayName,
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            0, NULL);

Can I keep it open for long time (as long as app is active), or maybe I should close it and open only when required?


Solution

  • You can leave a file handle open as long as you want. There is absolutely no need to close and reopen when required.

    That's typically what applications like MS Word do, the .docx (or whatever) file HANDLE stays open as as long as the user hasn't closed the document.

    This can be very useful when CreateFile is used with the dwShareMode parameter other than 0, for example to prevent other applications from writing into the file or deleting it while it is open.