# AppCallbacks 类参考

> Call the AppCallbacks class in your UWP application.

您可以使用 `AppCallbacks` 类将主应用程序连接到 Unity 引擎。

## 示例：如何使用 `AppCallbacks` 类##example:-how-to-use-the-appcallbacks-class

### `App.xaml.cpp` 文件##app.xaml.cpp-file

```
App::App()
{
    InitializeComponent();
    SetupOrientation();
    m_AppCallbacks = ref new AppCallbacks();
}

void App::OnLaunched(LaunchActivatedEventArgs^ e)
{
    m_SplashScreen = e->SplashScreen;
    InitializeUnity(e->Arguments);
}

void App::InitializeUnity(String^ args)
{
    ApplicationView::GetForCurrentView()->SuppressSystemOverlays = true;

    m_AppCallbacks->SetAppArguments(args);
    auto rootFrame = safe_cast<Frame^>(Window::Current->Content);

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == nullptr && !m_AppCallbacks->IsInitialized())
    {
        rootFrame = ref new Frame();
        Window::Current->Content = rootFrame;
#if !UNITY_HOLOGRAPHIC
        Window::Current->Activate();
#endif

        rootFrame->Navigate(TypeName(MainPage::typeid ));
    }

    Window::Current->Activate();
}
```

### `MainPage.xaml.cpp` 文件##mainpage.xaml.cpp-file

```
MainPage::MainPage()
{
    m_SplashScreenRemovalEventToken.Value = 0;
    m_OnResizeRegistrationToken.Value = 0;

    InitializeComponent();
    NavigationCacheMode = ::NavigationCacheMode::Required;

    auto appCallbacks = AppCallbacks::Instance;

    bool isWindowsHolographic = false;

#if UNITY_HOLOGRAPHIC
    // If application was exported as Holographic check if the device actually supports it
    // Otherwise, we treat this as a normal XAML application
    isWindowsHolographic = AppCallbacks::IsMixedRealitySupported();
#endif

    if (isWindowsHolographic)
    {
        appCallbacks->InitializeViewManager(Window::Current->CoreWindow);
    }
    else
    {
        m_SplashScreenRemovalEventToken = appCallbacks->RenderingStarted += ref new RenderingStartedHandler(this, &MainPage::RemoveSplashScreen);

        appCallbacks->SetSwapChainPanel(m_DXSwapChainPanel);
        // Subscribes to all needed system events
        appCallbacks->SetCoreWindowEvents(Window::Current->CoreWindow);

        // This is the main initialization function for Unity
        // Initializes engine graphics, DirectX, and gamepad and joystick input
        // Loads IL2CPP and all engine subsystems except graphics
        appCallbacks->InitializeD3DXAML();
        // At this point, when Unity finishes loading the first level, it enters the main loop.

        m_SplashScreen = safe_cast<App^>(App::Current)->GetSplashScreen();

        auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
        ThreadPool::RunAsync(ref new WorkItemHandler([this, dispatcher](IAsyncAction^)
        {
            GetSplashBackgroundColor(dispatcher);
        }));

        OnResize();

        m_OnResizeRegistrationToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler([this](Object^, WindowSizeChangedEventArgs^)
        {
            OnResize();
        });
    }
}
```

## 创建应用程序线程##create-an-app-thread

Unity 不会在 UI 线程上运行应用程序，因为加载大型应用程序时，UI 可能会变得无响应。有关 UI 线程的更多信息，请参阅 Microsoft 文档“[保持 UI 线程响应](https://learn.microsoft.com/en-gb/windows/uwp/debug-test-perf/keep-the-ui-thread-responsive)”。

使用 `m_AppCallbacks = ref new AppCallbacks();` 创建 `AppCallbacks` 类时，Unity 会创建一个名为 `App Thread` 的新线程。Unity 由于 Microsoft 的限制而创建了此新线程：如果应用程序在 5 秒后没有响应，您将无法通过 Windows 应用程序认证工具包测试。有关更多信息，请参阅 Microsoft 关于 [Windows 应用程序认证工具包](https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/windows-app-certification-kit)的文档。

\*\*注意：\*\*位于 `App.xaml.cpp` 和 `MainPage.xaml.cpp` 文件中的代码始终在 UI 线程上运行，除非从 `InvokeOnAppThread` 函数调用。

## 命令行参数##command-line-arguments

您还可以将自定义命令行参数作为字符串数组传递到 AppCallbacks 构造函数中。请参阅 [UWP 命令行参数](https://docs.unity3d.com/2023.1/Documentation/Manual/windowsstore-commandlinearguments.html)以了解更多信息。

## AppCallbacks 函数##appcallbacks-functions

| **函数**                                                             | **描述**                                                                                                                                                                                                                               |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `appCallbacks->InitializeD3DXAML();`                               | 初始化 DirectX 11 设备并加载第一个关卡。                                                                                                                                                                                                           |
| `appCallbacks->SetCoreWindowEvents(Window::Current->CoreWindow);`  | 设置 Unity 的核心窗口。Unity 订阅以下系统事件：- VisibilityChanged- Closed- PointerCursor- SizeChanged- Activated- CharacterReceived- PointerPressed- PointerReleased- PointerMoved- PointerCaptureLost- PointerWheelChanged- AcceleratorKeyActivated |
| `appCallbacks->SetSwapChainPanel(m_DXSwapChainPanel);`             | 将 XAML 控件传递给 Unity，此控件将用作 DirectX 11 的渲染目标。                                                                                                                                                                                          |
| `void GetSwapChainPanel()`                                         | 返回 SwapChainPanel 对象，可通过 SetSwapChainPanel 方法进行设置。                                                                                                                                                                                   |
| `void Initialized()`                                               | 返回引擎是否已初始化到足以运行主游戏循环的程度。                                                                                                                                                                                                             |
| `void InitializeD3DWindow()`                                       | 初始化 D3D 应用程序的引擎图形、DirectX 以及游戏手柄和游戏杆输入。                                                                                                                                                                                              |
| `void Instance()`                                                  | 检索先前创建的 AppCallbacks 对象的单例实例。                                                                                                                                                                                                        |
| `void InvokeOnAppThread(AppCallbackItem item, bool waitUntilDone)` | 在应用程序线程上调用委托。当您要从 UI 线程执行脚本函数时，此函数很有用。                                                                                                                                                                                               |
| `void InvokeOnUIThread(AppCallbackItem item, bool waitUntilDone)`  | 在 UI 线程上调用委托。当您要从脚本中调用特定于 XAML 的 API 时，此函数很有用。                                                                                                                                                                                       |
| `bool IsInitialized()`                                             | 当应用程序的第一个关卡完全加载时，返回 true。                                                                                                                                                                                                            |
| `void RenderingStarted()`                                          | 在 Unity 渲染其第一帧后开始。                                                                                                                                                                                                                   |
| `void Run()`                                                       | 使 D3D 应用程序能够进入主循环。                                                                                                                                                                                                                   |
| `bool RunningOnAppThread()`                                        | 如果当前在应用程序线程中运行，返回 true。                                                                                                                                                                                                              |
| `bool RunningOnUIThread()`                                         | 如果当前在 UI 线程中运行，返回 true。                                                                                                                                                                                                              |
| `void SetAppArguments(string arg)` / `string GetAppArguments()`    | 设置应用程序参数，然后可从 [UnityEngine.WSA.Application.arguments](/engine/6000.0/script-reference/unity-engine-wsa/application/arguments.md) 访问。                                                                                                 |
| `void SetCoreApplicationViewEvents()`                              | 订阅 CoreApplicationView::Activated 事件，并加载 IL2CPP 脚本后端和除图形之外的所有引擎子系统。                                                                                                                                                                  |
| `bool UnityGetInput()`                                             | 如果 Unity 处理传入的输入，返回 true。                                                                                                                                                                                                            |
| `void UnitySetInput(bool enabled)`                                 | 启用或禁用输入处理。                                                                                                                                                                                                                           |
| `bool UnityPause(int pause)`                                       | 如果传递 1，则暂停 Unity，如果传递 0，则取消暂停。如果要临时冻结游戏，此函数很有用。                                                                                                                                                                                      |

## 其他资源##additional-resources

* [关于保持 UI 线程响应的 Microsoft 文档](https://learn.microsoft.com/en-gb/windows/uwp/debug-test-perf/keep-the-ui-thread-responsive)
* [UWP 命令行参数](/engine/6000.0/manual/platform-specific/windows-store/uwp-developing/windowsstore-commandlinearguments.md)
* [命令行参数](/engine/6000.0/manual/unity-editor/editor-features/command-line-arguments/player.md)
