Electron.NET Documentation

repository·main·Indexed 27 days ago

https://github.com/electronnet/electron.net

Electron.NET allows .NET developers to build cross-platform desktop applications using Electron as the presentation layer. It supports .NET web stacks including ASP.NET Core (MVC, Razor Pages), Minimal APIs, and Blazor. The framework provides the Electron.App API for managing application lifecycle, window management, system integration, and custom protocol handling. Requirements include .NET 6, 8, or later, and Node.js 22.x or later.

Tokens
44K
Snippets
115
Records
221
Agent score
92%

What's inside Electron.NET

  1. Overview of ElectronNET.Core API Classes

    main

    The ElectronNET.Core API provides a .NET interface to access Electron's native desktop functionality. The API is organized into several functional categories:

    Core Application Management

    • Electron.App: Control application lifecycle, metadata, and system-level operations.
    • Electron.WindowManager: Create and manage browser windows and their behavior.
    • Electron.Menu: Create application menus, context menus, and menu items with keyboard shortcuts.

    User Interface & Interaction

    • Electron.Dialog: Display native system dialogs (file open/save, messages, alerts).
    • Electron.Notification: Show native desktop notifications.
    • Electron.Tray: Create system tray icons with context menus and tooltips.
    • Electron.Dock: macOS-specific dock integration (bounce effects, badge counts).

    System Integration

    • Electron.Shell: Open files, URLs, and access system paths.
    • Electron.Clipboard: Read/write to the system clipboard.
    • Electron.Screen: Access display and screen information.
    • Electron.NativeTheme: Detect system theme changes (light/dark mode).

    Communication & Automation

    • Electron.IpcMain: Handle inter-process communication (IPC) between the main and renderer processes.
    • Electron.HostHook: Advanced integration via custom host hooks.
    • Electron.GlobalShortcut: Register global keyboard shortcuts.
    • Electron.AutoUpdater: Manage application updates.

    System Monitoring

    • Electron.PowerMonitor: Monitor power events (sleep, wake, battery status).
  2. Overview of Electron.NET Core

    main

    Electron.NET Core is a modernized framework for building cross-platform desktop applications using ASP.NET Core and Electron. It integrates deeply with the MSBuild system, eliminating the need for external CLI tools or manual JSON configuration files.

    Key features include:

    • Native Visual Studio Integration: Uses MSBuild instead of CLI tools.
    • Console Application Support: Allows building Electron apps from simple console applications (not limited to ASP.NET).
    • Cross-Platform Development: Enables building and debugging Linux applications from Windows via WSL.
    • Enhanced Debugging: Supports ASP.NET-first debugging and Hot Reload.
    • Flexible Architecture: Supports choosing specific Electron versions and targeting multiple platforms.
  3. Monitor system power events with Electron.PowerMonitor

    main
    The Electron.PowerMonitor API allows you to listen for system-level power events, such as changes in power source (AC vs. Battery), system sleep/wake cycles, screen lock/unlock events, and system shutdown signals. This is useful for managing application state, saving data before suspension, or adjusting performance based on power availability.
  4. Manage application lifecycle with Electron.App

    main
    The Electron.App API provides control over your application's lifecycle, including startup, shutdown, window management, and system integration. It handles application-level events and provides methods for managing the overall application state.
  5. Use Electron.Tray to add icons and context menus

    main

    The Electron.Tray API allows you to add icons and context menus to the system's notification area (system tray). This is useful for providing quick access to functions or maintaining application presence when windows are closed.

    // Simple tray icon
    await Electron.Tray.Show("assets/tray-icon.png");
    
    // Tray icon with multiple menu items
    var trayMenuItems = new[] 
    {
        new MenuItem { Label = "Show Window", Click = () => ShowMainWindow() },
        new MenuItem { Label = "Settings", Click = () => OpenSettings() },
        new MenuItem { Type = MenuType.Separator },
        new MenuItem { Label = "Exit", Click = () => Electron.App.Quit() }
    };
    
    await Electron.Tray.Show("assets/tray-icon.png", trayMenuItems);
  6. Intercept and modify web requests with WebRequest

    main

    The WebRequest class allows you to intercept and modify the contents of a request at various stages of its lifetime. Instances are accessed via the webRequest property of a Session (e.g., session.defaultSession.webRequest).

    Key Concepts

    • Filtering: Methods accept an optional filter object with a urls property (an array of URL patterns) to limit interception to specific sites.
    • Listeners: Methods accept a listener function. If you pass null as the listener, you unsubscribe from that event.
    • Unsubscription Warning: Only the last attached listener for a specific event will be used. Subsequent attachments overwrite previous ones.
    • Callbacks: For certain events (like onBeforeSendHeaders or onHeadersReceived), the listener receives a callback function that must be called with a response object to apply modifications or redirects.
  7. Select the appropriate Electron.NET NuGet package

    main

    Electron.NET is distributed via three specialized NuGet packages. Choose the one that matches your project type to ensure correct build integration and runtime behavior.

    ElectronNET.Core (Main Package)

    Use for: Main application projects (startup projects) that require full Electron.NET functionality, including MSBuild targets, process lifecycle management, and automatic generation of electron-builder.json and package.json.

    ElectronNET.Core.Api (API Package)

    Use for: Class library projects that need to interact with Electron APIs but do not require build-time Electron configuration. This is a lightweight package with no build dependencies and provides full TypeScript-style IntelliSense for the Electron API surface.

    ElectronNET.Core.AspNet (ASP.NET Integration)

    Use for: ASP.NET Core projects (MVC, Razor Pages, or Blazor) that require seamless WebHost integration, UseElectron() middleware extension methods, and Hot Reload support.

  8. Configure startup flags for Unpackaged Debugging

    main

    When developing in an unpackaged environment, use specific command-line flags to control which process starts first. This determines whether you are debugging the Electron/Node.js side or the .NET/ASP.NET side.

    • Electron-first debugging (-unpackedelectron): Use this to debug the Electron main process and Node.js code. Electron starts first and then launches the .NET process.
    • .NET-first debugging (-unpackeddotnet): Use this to debug ASP.NET/C# code with Hot Reload. The .NET application starts first and then launches the Electron process.
  9. Implement platform-specific global shortcuts

    main

    Since keyboard conventions vary by OS, use RuntimeInformation.IsOSPlatform to register different accelerators for macOS versus Windows/Linux.

    if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
    {
        // macOS specific
        Electron.GlobalShortcut.Register("Command+Comma", () =>
        {
            OpenPreferences();
        });
    }
    else
    {
        // Windows/Linux
        Electron.GlobalShortcut.Register("Ctrl+Shift+P", () =>
        {
            OpenPreferences();
        });
    }
  10. Configure Electron.NET in Minimal API

    main

    For Minimal API projects, use builder.Services.AddElectron() to set up Dependency Injection and builder.UseElectron() to initialize the Electron host with a callback for window management.

    using ElectronNET;
    using ElectronNET.API;
    using ElectronNET.API.Entities;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddRazorPages();
    builder.Services.AddElectron(); // <- might be useful to set up DI
    
    builder.UseElectron(args, async () =>
    {
        var browserWindow = await Electron.WindowManager.CreateWindowAsync(
            new BrowserWindowOptions { Show = false, AutoHideMenuBar = true });
    
        browserWindow.OnReadyToShow += () => browserWindow.Show();
    });
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
    }
    
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.MapRazorPages();
    app.Run();