Skip to main content

Implementing in C#

Here is where Napacitor diverges most from Capacitor: instead of writing a Swift file for iOS and a Kotlin file for Android, we write one C# class that runs inside the MAUI host on Android, iOS, macOS, and Windows.

The web implementation of ScreenOrientation is finished. Now we implement the native side using the [NapacitorPlugin] model.

Creating the plugin class​

Create the file maui/ScreenOrientationPlugin.cs in the host project generated by nap add maui:

using Microsoft.Maui.Devices;
using Napacitor.Plugins;

namespace DeliveryApp.Maui.Plugins;

/// <summary>屏幕方向插件:读取当前方向并监听变化。</summary>
[NapacitorPlugin("ScreenOrientation")]
public class ScreenOrientationPlugin : NapacitorPluginBase
{
private const string OrientationChangeEvent = "screenOrientationChange";

[NapacitorMethod]
public Task<ScreenOrientationResult> Orientation()
{
var info = DeviceDisplay.Current.MainDisplayInfo;
return Task.FromResult(new ScreenOrientationResult
{
Type = Map(info.Orientation),
});
}

protected override void OnListenerAdded(string eventName)
{
if (eventName == OrientationChangeEvent)
DeviceDisplay.Current.MainDisplayInfoChanged += OnDisplayInfoChanged;
}

protected override void OnListenerRemoved(string eventName)
{
if (eventName == OrientationChangeEvent)
DeviceDisplay.Current.MainDisplayInfoChanged -= OnDisplayInfoChanged;
}

private void OnDisplayInfoChanged(object? sender, DisplayInfoChangedEventArgs e)
{
NotifyListeners(OrientationChangeEvent, new ScreenOrientationResult
{
Type = Map(e.DisplayInfo.Orientation),
});
}

private static string Map(DisplayOrientation orientation) => orientation switch
{
DisplayOrientation.Portrait => "portrait",
_ => "landscape",
};
}

/// <summary>方向结果(序列化为 { type: "portrait" | "landscape" })。</summary>
public class ScreenOrientationResult
{
public string Type { get; set; } = string.Empty;
}

Let's break down what is going on here:

  • [NapacitorPlugin("ScreenOrientation")] registers the class under the name "ScreenOrientation" — the same name passed to registerPlugin on the JS side. The runtime discovers the class by reflection, so there is nothing else to register.
  • [NapacitorMethod] exposes Orientation() to JavaScript. Every public method marked with this attribute becomes callable from JS; unmarked methods stay private to C#.
  • The method returns Task<ScreenOrientationResult>. The bridge awaits the task and serializes the result to JSON with camelCase property names, so Type arrives in JavaScript as type — exactly what ScreenOrientationResult in definitions.ts expects.
  • DeviceDisplay comes from Microsoft.Maui.Essentials and works identically on all four platforms. No #if blocks, no per-platform projects.

Sending events to JavaScript​

ScreenOrientation.orientation() only runs when called; the app also needs to be told when the orientation changes after page load. That's what the event pipeline is for:

  • NotifyListeners("screenOrientationChange", data) pushes the payload to every JS listener registered via addListener.
  • OnListenerAdded / OnListenerRemoved fire when the first JS listener registers and the last one unregisters. Subscribing to the native event source (DeviceDisplay.MainDisplayInfoChanged) only inside these hooks keeps the plugin from doing work when nobody is listening.
  • ListenerCount("screenOrientationChange") reports how many JS listeners are currently attached.

The JS side receives the payload exactly as with the web implementation:

ScreenOrientation.addListener('screenOrientationChange', res => {
// res.type === 'portrait' | 'landscape'
});

Testing the C# implementation​

Build the web assets, sync, and run the app in the MAUI host:

npm run build
npx nap sync
npx nap open windows # or: npx nap open android
npx nap run windows

nap sync copies the built web app into the host project and regenerates maui/napacitor.build.props. When you rotate the device (or resize the window on desktop), the UI should switch designs just like it did in the browser.

If you see ScreenOrientation does not have web implementation or an unimplemented error inside the host, the plugin class was not discovered. Check that the class is public with a public parameterless constructor, that the assembly name starts with Napacitor, and that you ran nap sync after adding the file. See Host discovery requirements.

The plugin is functionally complete as a local plugin. Next up: packaging it as a global npm package so other apps can install it.