> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 初始化 GDK

> 将作品从 Steamworks 移植到 GDK 时,设置 MicrosoftGame.config,初始化 Gaming Runtime 与 XSAPI,并将用户登录到 XBOX Live。

将 Steamworks 添加到游戏项目后,只需调用 `SteamAPI_Init` 函数即可初始化 API。可选地,你可以调用 `SteamAPI_RestartAppIfNecessary`,如有必要通过 Steam 重启应用。而初始化 XBOX Game Development Kit(GDK)略复杂一些,因为不存在一个统一的应用用来启动游戏并与不同游戏服务通信,像 Steam 那样。

要开始使用 XBOX Game Development Kit(GDK)中的 API,请按以下步骤操作。

1. 将 *MicrosoftGame.config* 文件添加到你的项目中。
2. 初始化 Gaming Runtime 服务。
3. 初始化 XBOX Services API,以便调用 XBOX Live 获取用户身份、云存档、成就等。
4. 将用户登录到 XBOX Live。保存成功登录后返回的句柄与 XBOX 用户 ID(XUID),以备后用。

<Note>
  在 Steam 上,你在加载时就可以访问用户的 Steam ID 与所有 API,因为通过 Steam 启动器启动游戏时,它会自动注入用户的账号信息。XBOX Live API 会被多个启动器上的游戏使用,因此不会自动获得这些信息 —— 你需要在启动时手动登录用户。
</Note>

关于如何完成第 1 步,参见 [MicrosoftGame.config 概览](/build/core-features/common/game-config/MicrosoftGameConfig-Overview)。

第 2–4 步的信息可在 [XBOX Live API 入门](/services/xbox-services/index) 中找到(以下也做了简要汇总),并请务必按该主题“清理 XSAPI”一节所描述的行为实现。Gaming Runtime 与 XBOX Services API 初始化完成后,你就可以将用户登录到 XBOX Live。如果留空,系统会自动为你创建 `XTaskQueue`,你无需自行创建。

```cpp theme={null}
#include <XGameRuntimeInit.h>
#include <XTaskQueue.h>
#include <xsapi-c/services_c.h>

// ...

void InitializeXboxLive()
{
    // ...
    HRESULT hr = XGameRuntimeInitialize();
    if (FAILED(hr))
    {
        // handle error: couldn't initialize the Gaming Runtime service.
    }

    XblInitArgs xblArgs = {};
    xblArgs.scid = "00000000-0000-0000-0000-000000000000"; // Add your SCID here that you got from the Partner Center web portal.

    HRESULT hr = XblInitialize(&xblArgs);
    if (FAILED(hr))
    {
        // handle error: couldn't initialize XBOX Live.
    }
    // ...
}
```

## 将用户登录到 XBOX Live

使用 [XUserAddAsync API](/build/core-features/common/user/xuser_howto_best_practice_signing_in) 将用户登录到 XBOX Live。如果是玩家第一次在你的游戏中登录,会显示一份你的游戏请求的权限清单。他们需要显式授权这些权限,以便访问其 XBOX Live 账号。

登录成功后,你可以使用传入 [`XUserAddResult`](/reference/system/xuser/xuser_members) 函数的 `XUserHandle` 引用。它可用于获取该 XBOX Live 用户的信息,例如 gamertag、玩家头像、登录状态、年龄组以及权限等。

用户第一次登录之后,只要在他们上次启动游戏后不需要处理 UI 提示(例如新的隐私协议),他们应该能够静默登录成功(即无需玩家操作)。不过,你仍然需要发起这些 API 调用来获取身份访问权限。

调用 XBOX Live API 需要 `XblContextHandle`。你可以使用 [XblContextCreateHandle](/reference/live/xsapi-c/xbox_live_context_c/xbox_live_context_c_members) 函数,通过 `XUserHandle` 获取 `XblContextHandle`。
