CreateEvent Function

Creates or opens a named or unnamed event object.

Syntax


HANDLE CreateEvent(
  LPSECURITY_ATTRIBUTES lpEventAttributes,
  BOOL                bManualReset,
  BOOL                bInitialState,
  LPCSTR              lpName
);
            

Parameters

Parameter Type Description
lpEventAttributes LPSECURITY_ATTRIBUTES A pointer to a SECURITY_ATTRIBUTES structure that specifies the security descriptor for the event object. If this parameter is NULL, the event object gets a default security descriptor that has access to the calling process.
bManualReset BOOL If this parameter is TRUE, the function creates a manual-reset event. A manual-reset event requires the use of the ResetEvent function to set the event state to signaled. If this parameter is FALSE, the function creates an auto-reset event. After one or more threads are released, the system automatically resets the event state to nonsignaled.
bInitialState BOOL If this parameter is TRUE, the initial state of the event object is signaled. Otherwise, it is nonsignaled.
lpName LPCSTR The name of the event object. The name is limited to 256 characters. The name is case sensitive. If lpName is NULL, the event object is created without a name. If lpName is the name of an existing event object, the function opens the existing object.

Return Value

If the function succeeds, the return value is a handle to the newly created or opened event object. If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Event objects provide a way to signal one or more threads that something has happened. Named event objects can be used to share state between processes. Unnamed event objects can be used to share state between threads within the same process.

Note: If an application calls CreateEvent to create an event object that already exists, the function returns a handle to the existing event object and GetLastError returns ERROR_ALREADY_EXISTS.
Important: You must close the handle to the event object when you are finished with it, using the CloseHandle function.

Example

The following code example demonstrates how to create a manual-reset event that is initially signaled.


#include <windows.h>
#include <iostream>

int main() {
    HANDLE hEvent;

    hEvent = CreateEvent(
        NULL,  // default security attributes
        TRUE,  // manual-reset event
        TRUE,  // initial state signaled
        TEXT("MyEventObject") // event name
    );

    if (hEvent == NULL) {
        std::cerr << "CreateEvent failed: " << GetLastError() << std::endl;
        return 1;
    }

    std::cout << "Event object created successfully." << std::endl;

    // ... use the event object ...

    // Close the event handle when done
    CloseHandle(hEvent);
    std::cout << "Event handle closed." << std::endl;

    return 0;
}
                

See Also