CloseHandle Function

Closes an open object handle.

Syntax


BOOL CloseHandle(
  HANDLE hObject
);
                

Parameters

Parameter Type Description
hObject HANDLE A handle to an open object. The handle must have been created by an appropriate function, such as CreateFile, CreateEvent, CreateMutex, and so on.

Return Value

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

  • Nonzero: The handle was successfully closed.
  • Zero: The handle could not be closed. Call GetLastError to determine the reason.

Remarks

The CloseHandle function closes a single open object handle. The type of object is determined by the handle itself. This function works for most kernel objects, including files, directories, processes, threads, and synchronization objects.

It is crucial to close handles when they are no longer needed to free up system resources and prevent resource leaks. Failure to close handles can lead to performance degradation or application instability.

When a process terminates, the system automatically closes all handles that were opened by that process.

Note: Do not call CloseHandle on a handle that has already been closed. Doing so may result in undefined behavior.

Warning: If you are working with a handle to a file opened with CreateFile, it is generally recommended to use the CloseHandle function. However, for I/O operations, ensure that all pending I/O operations associated with the handle have completed before calling CloseHandle to avoid unexpected behavior.

Example

The following example demonstrates how to open a file, write some data to it, and then close the file handle.


#include <windows.h>
#include <stdio.h>

int main() {
    HANDLE hFile;
    DWORD dwBytesWritten;
    const char* dataToWrite = "Hello, Windows API!\n";

    // Open a file for writing
    hFile = CreateFile(
        "example.txt",            // File name
        GENERIC_WRITE,            // Desired access
        0,                        // Share mode
        NULL,                     // Security attributes
        CREATE_ALWAYS,            // Creation disposition
        FILE_ATTRIBUTE_NORMAL,    // Flags and attributes
        NULL                      // Template file
    );

    if (hFile == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "Error opening file: %lu\n", GetLastError());
        return 1;
    }

    // Write data to the file
    if (!WriteFile(
        hFile,                    // Handle to file
        dataToWrite,              // Data to write
        strlen(dataToWrite),      // Number of bytes to write
        &dwBytesWritten,          // Number of bytes written
        NULL                      // Overlapped structure
    )) {
        fprintf(stderr, "Error writing to file: %lu\n", GetLastError());
        CloseHandle(hFile); // Close the handle even if write fails
        return 1;
    }

    printf("Successfully wrote %lu bytes to example.txt.\n", dwBytesWritten);

    // Close the file handle
    if (CloseHandle(hFile)) {
        printf("File handle closed successfully.\n");
    } else {
        fprintf(stderr, "Error closing file handle: %lu\n", GetLastError());
        return 1;
    }

    return 0;
}