이 가이드에서는 Electron 앱에서 Windows 앱 SDK 알림 API를 호출하는 C++ 네이티브 추가 기능을 만드는 방법을 보여 줍니다. 이것은 더 복잡한 시나리오를 살펴보기 전에 네이티브 추가 기능을 이해하기 위한 좋은 시작점입니다.
필수 조건
이 가이드를 시작하기 전에 다음을 수행했는지 확인합니다.
- 개발 환경 설정 완료
1단계: C++ 네이티브 추가 기능 만들기
C++ 및 node-addon-api를 사용하여 네이티브 추가 기능을 만들어 보겠습니다. 이렇게 하면 최대 성능으로 Windows API에 직접 액세스할 수 있습니다.
npx winapp node create-addon
메모
이 명령은 아직 설치하지 않은 경우 Python 또는 필요한 Visual Studio 도구를 설치하라는 메시지를 표시할 수 있습니다.
nativeWindowsAddon/ 폴더를 만듭니다.
-
nativeWindowsAddon.cc- Windows API를 호출하는 C++ 코드 -
binding.gyp- node-gyp에 대한 빌드 구성
또한 이 명령은 필요한 개발 종속성(nan, node-addon-api, node-gyp)을 설치하고 build-nativeWindowsAddon 스크립트를 package.json에 추가합니다.
{
"scripts": {
"build-nativeWindowsAddon": "node-gyp clean configure build --directory=nativeWindowsAddon"
}
}
생성된 템플릿에는 Windows SDK 알림 API를 사용하는 샘플 ShowNotification 함수가 포함되어 있습니다. 추가 기능을 빌드하여 모든 것이 올바르게 설정되었는지 확인해 보겠습니다.
# Build the C++ addon
npm run build-nativeWindowsAddon
메모
을 사용하여 npx winapp node create-addon --template csC# 추가 기능을 만들 수도 있습니다. C# 추가 기능은 node-api-dotnet을 사용합니다. 추가 기능을 만드는 다른 가이드 또는 전체 명령 설명서 에서 추가 옵션을 참조하세요.
2단계: 생성된 추가 기능 테스트
생성된 추가 기능이 주 프로세스에서 호출하여 작동하는지 확인해 보겠습니다. 열기 src/index.js:
- 맨 위에 다른
require문과 함께 애드온 임포트를 추가하세요.
const nativeWindowsAddon = require('../nativeWindowsAddon/build/Release/nativeWindowsAddon.node');
- 함수의 끝에서 알림 함수를 호출합니다.
createWindow()
const createWindow = () => {
// ... existing window creation code ...
// Test the Windows SDK notification
nativeWindowsAddon.showNotification(
'Hello from Electron!',
'This notification uses the Windows SDK.'
);
};
알림 API가 작동하려면 앱이 ID로 실행되도록 해야 합니다. Run:
npx winapp node add-electron-debug-identity
메모
이 명령은 설치 가이드에서 추가한 postinstall 스크립트의 일부이므로 npm install 이후에 자동으로 실행됩니다. 그러나 앱 자산을 수정 Package.appxmanifest하거나, 앱 자산을 업데이트하거나, 종속성을 다시 설치할 때마다 수동으로 실행해야 합니다.
이제 앱을 실행합니다.
npm start
알림이 표시됩니다. 🎉 생성된 추가 기능이 즉시 작동합니다.
⚠️ 알려진 문제: 앱 크래시 또는 빈 창(확장하려면 클릭)
Windows에서 스파스 패키징된 Electron 애플리케이션과 관련된 알려진 버그가 있으며, 이로 인해 애플리케이션이 시작 시 충돌하거나 웹 콘텐츠를 렌더링하지 못할 수 있습니다. 이 문제는 Windows 해결되었지만 아직 모든 디바이스에 전파되지 않았습니다.
해결 방법은 개발 환경 설정을 참조하세요.
3단계: Windows 앱 SDK 알림으로 업그레이드
이제 추가 기능이 작동하는지 확인했으므로 더 나은 개발자 환경과 더 많은 기능을 제공하는 최신 Windows 앱 SDK 알림 API(Microsoft.Windows.AppNotifications)를 사용하도록 업그레이드해 보겠습니다. 설치 단계에서 init 명령을 실행할 때 이미 Windows 앱 SDK 설정했습니다.
전체 내용을 열고 nativeWindowsAddon/nativeWindowsAddon.cc 다음 코드로 바꿉니다.
#include <napi.h>
#include <windows.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Microsoft.Windows.AppNotifications.h>
#include <winrt/Microsoft.Windows.AppNotifications.Builder.h>
using namespace winrt;
using namespace Microsoft::Windows::AppNotifications;
using namespace Microsoft::Windows::AppNotifications::Builder;
// Function to display a Windows App SDK notification
void ShowNotification(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
try {
// Get arguments from JavaScript (title and message)
if (info.Length() < 2 || !info[0].IsString() || !info[1].IsString()) {
Napi::TypeError::New(env, "Expected two string arguments: title and message").ThrowAsJavaScriptException();
return;
}
std::string title = info[0].As<Napi::String>();
std::string message = info[1].As<Napi::String>();
// Convert to wide strings
std::wstring wTitle(title.begin(), title.end());
std::wstring wMessage(message.begin(), message.end());
// Use AppNotificationBuilder for a cleaner API
AppNotificationBuilder builder;
builder.AddText(wTitle);
builder.AddText(wMessage);
AppNotification notification = builder.BuildNotification();
AppNotificationManager::Default().Show(notification);
} catch (const winrt::hresult_error& ex) {
Napi::Error::New(env, winrt::to_string(ex.message())).ThrowAsJavaScriptException();
} catch (const std::exception& ex) {
// Handle exceptions and throw back to JavaScript
Napi::Error::New(env, ex.what()).ThrowAsJavaScriptException();
} catch (...) {
Napi::Error::New(env, "Unknown error occurred").ThrowAsJavaScriptException();
}
}
// Initialize the module
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "showNotification"), Napi::Function::New(env, ShowNotification));
return exports;
}
NODE_API_MODULE(addon, Init)
여기서 주요 변경 내용은 이전 Windows.UI.Notifications 네임스페이스에서 최신 Microsoft.Windows.AppNotifications API로 전환하고 AppNotificationBuilder 사용하여 XML 문자열을 수동으로 빌드하는 대신 알림을 생성하는 것입니다. 이를 통해 Windows 앱 SDK 패턴과 일치하는 더 깨끗하고 유지 관리가 가능한 API를 제공합니다.
4단계: 다시 빌드 및 테스트
이제 업데이트된 코드를 사용하여 추가 기능을 다시 빌드합니다.
npm run build-nativeWindowsAddon
변경 사항을 반영하도록 메시지를 src/index.js 업데이트합니다.
nativeWindowsAddon.showNotification(
'Hello from Electron!',
'This notification is powered by the Windows App SDK!'
);
앱을 다시 실행합니다.
npm start
최신 Windows 앱 SDK API를 사용하여 업데이트된 알림이 표시됩니다.
다음 단계
축하합니다! Windows 앱 SDK API를 호출하는 네이티브 C++ 추가 기능을 성공적으로 만들었습니다. 🎉
이제 다음을 수행할 준비가 되었습니다.
- 배포용 앱 패키지 - 배포할 수 있는 MSIX 패키지 만들기
또는 다른 가이드를 살펴보세요.
- Phi Silica Addon 만들기 - C# 추가 기능에서 Windows AI API를 사용하는 방법 알아보기
- WinML 추가 기능 만들기 - C# 추가 기능에서 Windows Machine Learning 사용하는 방법 알아보기
- 시작 개요 - 기본 가이드로 돌아가기
추가 리소스
- winapp CLI 설명서 - 전체 CLI 참조
- 샘플 Electron 앱 - C++ 추가 기능으로 전체 작업 예제
- node-addon-api - C++ ↔ JavaScript interop 라이브러리
- Windows 앱 SDK 샘플 - Windows 앱 SDK 샘플 컬렉션
Windows developer