CloseHandle

BOOL CloseHandle(HANDLE hObject);

Description

The CloseHandle function closes a single open object handle. This is the most basic way to close a handle.

The specific type of object is determined by the handle. For example, a handle can refer to a file, a directory, a process, a thread, a synchronization object, or a registry key.

Closing a handle reduces the object's reference count. When the reference count reaches zero, the object is destroyed.

Syntax


BOOL CloseHandle(
  [in] HANDLE hObject
);
                

Parameters

Parameter Type Description
hObject [in] HANDLE A handle to an open object.

Return Value

BOOL

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.

Remarks

It is important to close handles when they are no longer needed to free up system resources. Failure to do so can lead to resource leaks, potentially causing performance degradation or application instability.

For specific object types, there may be more specialized functions to close their handles (e.g., CloseServiceHandle for service control manager handles). However, CloseHandle is a general-purpose function that works for most object types.

If you close a handle to a process or thread, the handle becomes invalid, but the associated process or thread continues to execute. When the last handle to a process or thread is closed, the system discards the process or thread's entry in the process table, freeing the virtual memory the process or thread used.

Example


// Example of creating a file and then closing its handle
#include <windows.h>
#include <iostream>

int main() {
    HANDLE hFile = CreateFile(
        L"mytestfile.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) {
        std::cerr << "Error creating file: " << GetLastError() << std::endl;
        return 1;
    }

    std::cout << "File created successfully." << std::endl;

    // Close the file handle
    if (CloseHandle(hFile)) {
        std::cout << "File handle closed successfully." << std::endl;
    } else {
        std::cerr << "Error closing file handle: " << GetLastError() << std::endl;
    }

    return 0;
}
                

Requirements

Minimum supported client: Windows 2000 Professional

Minimum supported server: Windows 2000 Server

Header: windows.h

Library: Kernel32.lib

DLL: Kernel32.dll

See Also

Related Topics