比较两个对象句柄以确定它们是否引用同一个基础内核对象。

语法

BOOL CompareObjectHandles(

[in] HANDLE hFirstObjectHandle,

[in] HANDLE hSecondObjectHandle

);

参数

[in] hFirstObjectHandle

要比较的第一个对象句柄。

[in] hSecondObjectHandle

要比较的第二个对象句柄。

返回值

一个布尔值,指示两个句柄是否引用同一个基础内核对象。 如果相同,则为 TRUE,否则为 FALSE。

注解

CompareObjectHandles 函数可用于确定两个内核句柄是否引用同一内核对象,而不要求向任一句柄授予特定访问权限以执行比较。 例如,如果进程需要确定进程句柄是否是当前进程的句柄,则调用 CompareObjectHandles (GetCurrentProcess () ,可以使用 hProcess) 来确定 hProcess 是否引用当前进程。 值得注意的是,这不需要使用特定于对象的访问权限,而在此示例中,调用 GetProcessId 以检查两个进程句柄的进程 ID 施加了句柄授予PROCESS_QUERY_LIMITED_INFORMATION访问权限的要求。 但是,进程句柄不授予该访问权限是合法的,具体取决于句柄的使用方式。

示例

下面的代码示例创建三个句柄,其中两个句柄引用同一对象,然后比较它们以显示相同的基础内核对象将返回 TRUE,而不相同的对象将返回 FALSE。

#include

#include

#include

HANDLE Event1;

HANDLE Event2;

HANDLE Event3;

// Create a handle to a named event.

Event1 = CreateEventW (NULL, TRUE, FALSE, L"{75A520B7-2C11-4809-B43A-0D31FB1FDD19}");

if (Event1 == NULL) { ExitProcess (0); }

// Create a handle to the same event.

Event2 = CreateEventW (NULL, TRUE, FALSE, L"{75A520B7-2C11-4809-B43A-0D31FB1FDD19}");

if (Event2 == NULL) { ExitProcess (0); }

// Create a handle to an anonymous, unnamed event.

Event3 = CreateEventW (NULL, TRUE, FALSE, NULL);

if (Event3 == NULL) { ExitProcess (0); }

// Compare two handles to the same kernel object.

if (CompareObjectHandles (Event1, Event2) != FALSE)

{ // This message should be printed by the program.

wprintf (L"Event1 and Event2 refer to the same underlying event object.\n");

}

// Compare two handles to different kernel objects.

if (CompareObjectHandles (Event1, Event3) == FALSE)

{ // This message should be printed by the program.

wprintf (L"Event1 and Event3 refer to different underlying event objects. (Error %lu)\n", GetLastError ());

}

// Compare two handles to different kernel objects, each of a different type of kernel object.

// The comparison is legal to make, though the function will always return FALSE and indicate

// a last error status of ERROR_NOT_SAME_OBJECT.

if (CompareObjectHandles (Event1, GetCurrentProcess ()) == FALSE)

{ // This message should be printed by the program.

wprintf (L"Event1 and the current process refer to different underlying kernel objects. (Error %lu)\n", GetLastError ());

}

要求

要求

最低受支持的客户端

Windows 10 [桌面应用 |UWP 应用]

最低受支持的服务器

Windows Server 2016 [桌面应用 |UWP 应用]

目标平台

Windows

标头

handleapi.h (包括 Windows.h)

Library

Kernelbase.lib

DLL

Kernelbase.dll

另请参阅

句柄和对象函数

2025-12-25 20:10:34