本指南介绍如何在 Electron 应用中创建使用 Windows App SDK 通知 API 的 C++ 本机加载项。 在深入了解更复杂的方案之前,这是了解原生插件的一个很好的起点。
先决条件
- 已完成 开发环境设置
- Windows 11
步骤 1:创建 C++ 本机加载项
使用 winapp CLI 生成 C++ 加载项模板:
npx winapp node create-addon --template cpp --name nativeWindowsAddon
这将创建一个 nativeWindowsAddon/ 文件夹,其中包含:
-
addon.cc- 将调用 Windows API 的 C++ 代码 -
binding.gyp- 本地编译的构建配置
该命令还会将脚本添加到你的 build-addonpackage.json。
生成加载项:
npm run build-addon
步骤 2:添加通知代码
打开 nativeWindowsAddon/addon.cc 并将其更新为使用Windows App SDK通知 API。 生成的模板包括必要的 Windows SDK 和Windows App SDK标头。
添加通知 API 的导入:
#include <winrt/Microsoft.Windows.AppNotifications.h>
#include <winrt/Microsoft.Windows.AppNotifications.Builder.h>
添加显示 Windows 通知的函数:
Napi::Value ShowNotification(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
try {
std::string title = info[0].As<Napi::String>().Utf8Value();
std::string message = info[1].As<Napi::String>().Utf8Value();
winrt::Microsoft::Windows::AppNotifications::Builder::AppNotificationBuilder builder;
builder.AddText(winrt::to_hstring(title));
builder.AddText(winrt::to_hstring(message));
auto notification = builder.BuildNotification();
winrt::Microsoft::Windows::AppNotifications::AppNotificationManager::Default().Show(notification);
return Napi::Boolean::New(env, true);
} catch (const winrt::hresult_error& e) {
Napi::Error::New(env, winrt::to_string(e.message())).ThrowAsJavaScriptException();
return env.Null();
}
}
在 Init 方法中注册函数:
exports.Set("showNotification", Napi::Function::New(env, ShowNotification));
步骤 3:生成加载项
npm run build-addon
步骤 4:测试通知
打开 src/index.js 并加载该加载项:
const addon = require('../nativeWindowsAddon/build/Release/nativeWindowsAddon.node');
添加测试调用:
addon.showNotification('Hello from Electron!', 'This notification uses the Windows App SDK.');
运行应用:
npm start
此时会显示 Windows 通知。
步骤 5:更新调试标识
每当修改 appxmanifest.xml时,请运行:
npx winapp node add-electron-debug-identity
后续步骤
- 创建 Phi Silica 加载项 - 使用设备上的多个 AI API
- 创建 WinML 加载项 - 运行machine learning模型
- 分发打包 - 创建签名的 MSIX 包