DEV Community

Hagicode
Hagicode

Posted on

How to Call Windows Native APIs in Electron

How to Call Windows Native APIs in Electron

Calling Windows native APIs in an Electron app feels like wanting to see the ocean but only having a map. After some trial and error, I've found a few paths—writing this article serves as a record and a guide for others who might follow.

Background

When building Electron desktop applications, you inevitably need to interact with the operating system. On Windows, these requirements are quite common:

  • Calling Windows Store APIs for in-app purchases
  • Handling file system virtualization specific to Windows Store apps
  • Obtaining system-level permissions and resources
  • Interacting with Windows Runtime (WinRT) components

Electron is fundamentally a Node.js environment, and Node.js doesn't natively provide direct access to Windows native APIs. A bridge is needed between the two.

It's like trying to communicate with a friend who doesn't speak Chinese—you need a translator. Electron is written in JavaScript, Windows APIs in C/C++. The language barrier requires building a bridge. That's the harsh reality of the code world.

About HagiCode

The solutions shared in this article come from our practical experience with the HagiCode project. HagiCode Desktop needs to call Microsoft Store APIs to handle subscription purchases and license management, which is why we developed a set of technical solutions. After all, necessity drives innovation—that's a truth.

Technical Solution Comparison

When calling Windows native APIs in Electron, there are several mainstream approaches to choose from. Each has its applicable scenarios—like different tools in a toolbox, they work best when used in the right place, otherwise just add trouble.

Solution Applicable Scenarios Pros Cons
dynwinrt WinRT APIs (e.g., Store API) Type-safe, auto-generated bindings, modern JavaScript support Only supports WinRT APIs, requires Windows SDK
Native Node.js Extensions High performance, any Windows API Complete control, optimal performance Requires C++ development skills, complex cross-platform compatibility
child_process + PowerShell Temporary, one-off calls Simple and fast, no compilation needed Poor performance, complex error handling
edge.js/ffi-napi Calling existing DLLs Can reuse existing libraries Compatibility issues, high maintenance cost

HagiCode Desktop adopts a hybrid approach: using dynwinrt to access Windows Store APIs, native Node.js extensions for high-performance Store purchase operations, and Node.js's native fs and path modules to handle Windows Store app-specific file system virtualization. Keep it simple when possible—that's our principle.

Solution 1: Using dynwinrt to Call WinRT APIs

dynwinrt is a toolchain provided by Microsoft that can automatically generate JavaScript bindings based on Windows SDK metadata files. It's specifically designed for calling WinRT APIs, like Windows Store APIs.

Install dependencies:

{
  "optionalDependencies": {
    "@microsoft/dynwinrt": "0.1.0-preview.6",
    "@microsoft/dynwinrt-codegen": "0.1.0-preview.6"
  }
}
Enter fullscreen mode Exit fullscreen mode

Generate WinRT bindings:

// scripts/generate-store-bindings.js
const { execFileSync } = 'node:child_process';

function generateStoreNamespace(windowsWinmdPath) {
  execFileSync('npx', [
    'dynwinrt-codegen',
    'generate',
    '--winmd', windowsWinmdPath,
    '--namespace', 'Windows.Services.Store',
    '--output', 'src/main/subscription/generated-js',
    '--lang', 'js',
  ]);
}
Enter fullscreen mode Exit fullscreen mode

Use generated bindings:

// Using Store API bindings generated by dynwinrt
import { Windows } from '../subscription/generated-js/index.js';

async function queryStoreProduct(storeId: string) {
  const storeContext = Windows.Services.Store.StoreContext.getDefault();
  const result = await storeContext.getAssociatedStoreProductsAsync(['Subscription', 'Durable']);

  if (result.extendedError !== 0) {
    throw new Error(`Store API error: ${result.extendedError}`);
  }

  return result.products.get(storeId);
}
Enter fullscreen mode Exit fullscreen mode

dynwinrt's advantage is type safety, and the generated code aligns with modern JavaScript conventions. But it can only handle WinRT APIs—if you need to call traditional Win32 APIs, you'll need other solutions. That's how tools work—each has its strengths.

Solution 2: Native Node.js Extensions

When high performance is needed or dynwinrt doesn't support the functionality, native Node.js extensions are the best choice. This approach requires writing C++ code, then compiling it into .node files using node-gyp.

Create binding.gyp:

{
  "targets": [{
    "target_name": "windows-store-addon",
    "sources": ["src/windows-store-addon.cpp"],
    "include_dirs": [
      "<!(node -e \"require('nan')\")"
    ],
    "defines": [
      "WIN32_LEAN_AND_MEAN"
    ]
  }]
}
Enter fullscreen mode Exit fullscreen mode

C++ native module example:

// src/windows-store-addon.cpp
#include <nan.h>
#include <windows.h>
#include <wrl.h>
#include <windows.services.store.h>

using namespace v8;
using namespace Windows::Services::Store;

NAN_METHOD(QueryStoreStatus) {
  auto async = new Nan::AsyncWorker(
    []() {
      // Call Windows Store API
      auto context = StoreContext::GetDefault();
      auto products = context->GetAssociatedStoreProductsAsync(...)->GetResults();
      // Process results
    }
  );
  Nan::AsyncQueueWorker(async);
}

NAN_MODULE_INIT(InitModule) {
  Nan::Set(target, Nan::New("queryStoreStatus").ToLocalChecked(),
           Nan::GetFunction(Nan::New<FunctionTemplate>(QueryStoreStatus)).ToLocalChecked());
}

NODE_MODULE(windows_store_addon, InitModule)
Enter fullscreen mode Exit fullscreen mode

Compile and use:

node-gyp rebuild
Enter fullscreen mode Exit fullscreen mode
import addon from './build/Release/windows-store-addon.node';

const result = addon.queryStoreStatus({
  storeId: 'your-store-id',
  productKinds: ['Subscription', 'Durable']
});
Enter fullscreen mode Exit fullscreen mode

Native extensions offer the best performance, but development costs are high. You need C++ skills and must handle cross-platform compatibility issues. If your team has C++ experience or performance requirements are particularly demanding, this solution is worth the investment. But this path is ultimately more challenging.

Solution 3: Handling Windows Store App Virtualization

Windows Store apps run in a virtualized environment, requiring special path mapping. HagiCode Desktop uses the following function to handle this:

// src/main/windows-store-path-display.ts
export function resolveWindowsStorePackageFamilyName(executablePath: string): string | null {
  const WINDOWS_APPS_SEGMENT = '\\windowsapps\\';
  const windowsPath = executablePath.replace(/\//g, '\\');
  const markerIndex = windowsPath.toLowerCase().indexOf(WINDOWS_APPS_SEGMENT);

  if (markerIndex < 0) return null;

  const relativePath = windowsPath.slice(markerIndex + WINDOWS_APPS_SEGMENT.length);
  const packageFullName = relativePath.split('\\', 1)[0]?.trim();
  return packageFullName || null;
}

export function resolveWindowsStoreVirtualizedPhysicalPath(
  logicalPath: string,
  options: ResolveWindowsStorePathDisplayOptions = {}
): string | null {
  const packageFamilyName = options.packageFamilyName
    ?? resolveWindowsStorePackageFamilyName(options.execPath ?? process.execPath);
  if (!packageFamilyName) return null;

  const packageStorageRoot = path.win32.join(
    options.env.LOCALAPPDATA,
    'Packages',
    packageFamilyName
  );

  // Map virtualized path to physical path
  if (isPathWithinWindowsRoot(logicalPath, options.env.APPDATA)) {
    return path.win32.join(
      packageStorageRoot,
      'LocalCache',
      'Roaming',
      path.win32.relative(options.env.APPDATA, logicalPath)
    );
  }

  return null;
}
Enter fullscreen mode Exit fullscreen mode

Virtualization is quite complex. Simply put, the file paths that Windows Store apps see differ from actual storage locations, requiring translation. The code above performs this translation. Like memory and reality, sometimes they don't align and require patience to distinguish.

Practical Experience

Platform Detection

Always check process.platform === 'win32' to avoid executing Windows-specific code on non-Windows platforms. This is a good habit—like checking the weather before leaving home to avoid getting caught in the rain.

if (process.platform !== 'win32') {
  return { availability: 'not-supported' };
}
Enter fullscreen mode Exit fullscreen mode

Error Handling

Windows API calls may fail and need proper error handling. We've learned this the hard way—without comprehensive error handling, users have no idea what went wrong when problems occur. Actually, writing more code teaches you that error handling isn't for anyone else—it's just to save yourself trouble.

function normalizeThrownError(error: unknown): { errorCode: string | null; errorMessage: string | null } {
  if (error instanceof Error) {
    const errorWithCode = error as Error & { code?: unknown };
    return {
      errorCode: normalizeErrorCode(errorWithCode.code) ?? error.name,
      errorMessage: error.message,
    };
  }
  return { errorCode: null, errorMessage: error == null ? null : String(error) };
}
Enter fullscreen mode Exit fullscreen mode

Async Handling

Most Windows Store APIs are asynchronous—use Promise or async/await. When writing async code, remember to handle edge cases like timeouts and cancellation. The taste of waiting—no one wants more of that.

async function queryStatus(): Promise<RawStoreLicenseState> {
  try {
    const result = await storeContext.getAssociatedStoreProductsAsync(productKinds);
    return buildSupportedStateFromProductQueries(result);
  } catch (error) {
    return buildUnavailableState(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

Resource Cleanup

Ensure native resources are released when no longer needed. C++ resources aren't automatically collected—manual release is a good habit. Like some things, you can only travel light after letting them go.

class MicrosoftStoreSubscriptionBroker {
  private broker: StoreLicensePlatformBroker | null = null;

  dispose(): void {
    this.broker?.dispose();
    this.broker = null;
  }
}
Enter fullscreen mode Exit fullscreen mode

Timestamp Conversion

Windows uses 1601-01-01 as its epoch, which needs conversion to Unix timestamps. This detail is easily overlooked, but if handled incorrectly, dates will be completely wrong. Time—a small difference makes a big difference.

const WINDOWS_EPOCH_OFFSET_MILLISECONDS = 11644473600000n;
const HUNDRED_NANOSECONDS_PER_MILLISECOND = 10000n;

function toIsoDate(value: unknown): string | null {
  const universalTime = (value as { universalTime?: unknown } | null)?.universalTime;
  const ticks = typeof universalTime === 'bigint' ? universalTime : null;

  if (ticks == null) return null;

  const unixMilliseconds = ticks / HUNDRED_NANOSECONDS_PER_MILLISECOND - WINDOWS_EPOCH_OFFSET_MILLISECONDS;
  return new Date(Number(unixMilliseconds)).toISOString();
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

Based on our experience with the HagiCode project, here are a few recommendations:

  • Prioritize dynwinrt: For WinRT APIs, dynwinrt provides type-safe and modern JavaScript bindings
  • Minimize native extensions: Only use native extensions when truly necessary for high performance or unsupported features
  • Cross-platform compatibility: Use conditional compilation or runtime detection for different platforms
  • Test coverage: Thoroughly test native API calls on Windows, including error scenarios
  • Documentation: Clearly document the purpose and potential side effects of each native API call

When writing code, keep it simple if possible. If dynwinrt can solve the problem, don't write C++ extensions. Maintenance costs will be much lower. This is a small insight—not some profound truth.

Summary

Calling Windows native APIs is an important means for Electron apps to implement advanced features on Windows. This article shares several technical solutions used in the HagiCode Desktop project: dynwinrt for WinRT APIs, native Node.js extensions for high-performance scenarios, and virtualized path handling for Store app file access.

Which solution to choose depends on your specific needs. If you're only calling WinRT APIs, dynwinrt is the simplest choice. If you need high performance or traditional Win32 APIs, native extensions are essential. For temporary operations, using child_process to call PowerShell works too. All roads lead to Rome—some are easier to travel, others a bit more winding.

Regardless of which solution you use, remember these principles: proper platform detection, comprehensive error handling, careful async handling, timely resource cleanup. These details determine the robustness of your code. Writing code for long enough teaches you that details matter more than grand frameworks.

If you're working on similar development, I hope these experiences help you. Technology—you gain experience after stumbling enough. Like life—you learn to walk after falling enough...

References

Summary

A more steady approach to "How to Call Windows Native APIs in Electron" is to first validate key configurations, dependency boundaries, and implementation paths, then fill in optimization details.

Once objectives, steps, and acceptance criteria are clear, such solutions typically enter actual delivery more smoothly.

Top comments (0)