Compare commits

...

374 Commits

Author SHA1 Message Date
Florian Rappl
8009348941 Update transformed files 2026-02-04 11:26:06 +01:00
Florian Rappl
b3b124bde1 Updated TS formatting to match prettier 2026-02-04 11:25:30 +01:00
Florian Rappl
21226e1ef0 Updated deps 2026-02-04 11:18:55 +01:00
Florian Rappl
7174118a3e Merge pull request #1019 from DYH1319/feat/submit_new_event_for_ipc
feat: submit new events for ipcMain
2026-02-03 00:32:04 +01:00
DYH1319
092789a5ec feat: Add overloaded methods in IpcMain that supports listeners with a return type of Task<object>. 2026-01-25 00:47:35 +08:00
DYH1319
bff3fffcbd feat: Add the Handle, HandleOnce, and RemoveHandler events to IpcMain 2026-01-24 23:18:16 +08:00
Florian Rappl
456135a562 Merge pull request #1015 from hillin/main
Update Migration Guide
2026-01-21 12:18:25 +01:00
lucas
300f52510c Update Migration Guide with details on electron-builder.json location and launch settings 2026-01-21 15:30:44 +08:00
Florian Rappl
d85a64f515 Merge pull request #1014 from softworkz/submit_new_event
BrowserWindow: Add OnBoundsChanged event
2026-01-21 08:19:16 +01:00
Florian Rappl
53698d1d44 Merge pull request #1013 from softworkz/submit_timeout
Double-up timeout for electron-builder and other fixes
2026-01-21 08:07:50 +01:00
Florian Rappl
04a224aa4f Merge pull request #1012 from softworkz/submit_migcheck_updates
Relax Migration check for package.json in root
2026-01-21 08:06:55 +01:00
softworkz
891da140b7 Relax Migration check for package.json in root 2026-01-21 06:50:07 +01:00
softworkz
17f761d184 Fix FormatException 2026-01-21 06:48:28 +01:00
softworkz
9f6489891e ElectronNET.Host: Revert JS SDK to default value from VS 2026 2026-01-21 06:48:28 +01:00
softworkz
c8f1cdf59f Add tests for BrowserWindow.OnBoundsChanged event 2026-01-21 06:47:28 +01:00
softworkz
6c95dfd476 BrowserWindow: Add OnBoundsChanged event
While not being an original Electron event, this one includes the bounds values,
saving the additional roundtrip for calling GetBoundsAsync
2026-01-21 06:47:28 +01:00
softworkz
b180fc2ea8 Double-up timeout for electron-builder 2026-01-21 05:10:24 +01:00
Florian Rappl
682a1c38ed Optional 2025-12-23 21:10:57 +01:00
Florian Rappl
809b0a6be7 Added missing methods 2025-12-23 00:38:37 +01:00
Florian Rappl
ae3f755648 Fixed center handling 2025-12-22 12:32:52 +01:00
Florian Rappl
7e6760a428 Merge pull request #998 from ElectronNET/develop
Release 0.4.0
2025-12-19 00:09:34 +01:00
Florian Rappl
29fdbb5315 Updated changelog 2025-12-18 23:58:04 +01:00
Florian Rappl
36bba6a49f Merge pull request #995 from softworkz/submit_packageid
Set PackageId from ElectronPackageId
2025-12-18 21:57:28 +01:00
Florian Rappl
44a010e0ed Merge pull request #996 from softworkz/submit_singleinstance
Fix ElectronSingleInstance handling
2025-12-18 21:56:59 +01:00
softworkz
25770db138 Update src/ElectronNET/build/ElectronNET.Core.targets
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-18 17:25:52 +01:00
Florian Rappl
1c99ab02cc Merge pull request #997 from softworkz/submit_rerun
Try fix retry-test-jobs
2025-12-18 16:56:29 +01:00
softworkz
73c56e2450 Try fix retry-test-jobs 2025-12-18 16:13:04 +01:00
softworkz
30037fce69 Fix ElectronSingleInstance handling 2025-12-18 15:52:56 +01:00
softworkz
69048d5565 Set PackageId from ElectronPackageId 2025-12-18 15:12:21 +01:00
Florian Rappl
d9c8e04b5c Meta for 0.4.0 2025-12-17 16:40:46 +01:00
Florian Rappl
368ef412bb Merge pull request #988 from softworkz/submit_crossdebug
Core: Introduce cross-platform npm restore and check mismatch on publish
2025-12-17 15:29:48 +01:00
Florian Rappl
cb20fbad25 Merge pull request #991 from ElectronNET/develop
Release 0.3.1
2025-12-16 19:00:07 +01:00
Florian Rappl
89cdf2f55b Merge pull request #992 from softworkz/submit_rerun
Try fix job re-run
2025-12-16 18:53:23 +01:00
softworkz
1c62c1f132 Try fix job re-run 2025-12-16 16:02:43 +01:00
Florian Rappl
d3e3188681 Prepare for 0.3.1 2025-12-16 15:51:39 +01:00
Florian Rappl
4f95043309 Merge pull request #990 from softworkz/submit_packageid
Use ElectronPackageId instead of PackageId
2025-12-16 15:48:43 +01:00
softworkz
13f1203ccc Use ElectronPackageId instead of PackageId 2025-12-16 14:54:20 +01:00
softworkz
9d0378798b ElectronProcessActive: Add check for platform mismatch 2025-12-15 13:22:53 +01:00
softworkz
1d6ef7a250 ElectronProcessActive: Mark binaries as executable when debugging 2025-12-15 12:18:42 +01:00
softworkz
2d6d4e2320 Fix up incorrect symlinks created by npm on Windows 2025-12-15 12:18:42 +01:00
softworkz
df8e269d5c Core: Introduce cross-platform npm restore and check mismatch on publish 2025-12-15 12:18:42 +01:00
Florian Rappl
bdfbcd5b77 Merge pull request #986 from ElectronNET/develop
Release 0.3.0
2025-12-14 22:13:10 +01:00
Florian Rappl
19e785f53f Fixed whitespace 2025-12-14 15:30:21 +01:00
Florian Rappl
0b453177b5 Added contributing guide 2025-12-14 15:20:15 +01:00
Florian Rappl
8ed7f27722 Make sure the electron-host-hook strays unobtrusive 2025-12-14 00:49:34 +01:00
Florian Rappl
321b8cd9e5 Merge branch 'develop' of https://github.com/ElectronNET/Electron.NET into develop 2025-12-14 00:36:59 +01:00
Florian Rappl
b326f863d8 Updated changelog 2025-12-14 00:36:53 +01:00
Florian Rappl
f148fe6a14 Merge pull request #983 from markatosi/develop
Wiki Package building macOS sections added
2025-12-14 00:32:37 +01:00
Florian Rappl
515d325731 Fixed startup in VS Code 2025-12-13 23:43:12 +01:00
markatosi
f32a40fe17 Add macOS profiles for ASP.NET and Console apps
Added profiles for ASP.NET and Console applications on macOS.
2025-12-13 12:18:38 -10:00
Florian Rappl
c53a5a9163 Merge pull request #982 from markatosi/develop
Change Example code for AutoMenuHide
2025-12-13 12:28:41 +01:00
markatosi
8d4cdddc46 Conditionally set AutoHideMenuBar for Windows/Linux 2025-12-12 13:45:56 -10:00
Florian Rappl
70e8f85123 Merge pull request #977 from softworkz/submit_revertnet6
Combine and separate workflows
2025-12-12 07:23:26 +01:00
softworkz
5a7cbd972f Combine and separate workflows
- Separate between PR and Push execution (with and without secrets)
- Turn tests into re-usable workflows and call them from the main ones
2025-12-12 02:15:44 +01:00
softworkz
33da428c45 Fix build after PR merge
Re-adding .net6 caused the collection expression to fail
2025-12-12 01:39:02 +01:00
softworkz
f1b4766360 Add automatic retry for failed test jobs 2025-12-12 00:51:13 +01:00
softworkz
e070759645 integration-tests: Add random delay 2025-12-12 00:49:16 +01:00
Florian Rappl
49eaa5e129 Merge pull request #973 from davidroth/set-menu-items
Add dynamic tray menu update functionality
2025-12-11 22:58:06 +01:00
Florian Rappl
b3f5a3c52b Merge pull request #976 from softworkz/submit_revertnet6
Partially revert "Drop .NET 6.0, default to .NET 10.0 and update dependencies"
2025-12-11 22:57:40 +01:00
softworkz
0d732ce99e Partially revert "Drop .NET 6.0, default to .NET 10.0 and update dependencies" 2025-12-11 22:35:45 +01:00
David Roth
218b99808b Add dynamic tray menu update functionality
Introduced a `SetMenuItems` method in `Tray.cs` to enable updating the tray's context menu dynamically. This method clears existing menu items, adds new ones, and registers click handlers. Added XML documentation for the method.
2025-12-11 18:04:31 +01:00
Florian Rappl
7f507a6d86 Merge pull request #975 from davidroth/missing-usings
Fix build by adding necessary using directives for async and DI setup.
2025-12-11 10:55:17 +01:00
Florian Rappl
81b3793966 Merge pull request #974 from davidroth/dotnet-targets
Drop .NET 6.0, default to .NET 10.0 and update dependencies
2025-12-11 10:54:44 +01:00
David Roth
1baa5c6200 Drop .NET 6.0, default to .NET 10.0 and update dependencies
Updated all projects to target .NET 10.0, removing support for .NET 6.0. Upgraded key dependencies, including:
- `Microsoft.Build` and `Microsoft.Build.Tasks.Core` to 18.0.2.
- `Nuke.Common` to 10.1.0.
- `System.Drawing.Common` to 10.0.1.
- `System.Text.Json` to 10.0.1.

Removed `NoWarn` configurations for .NET 6.0 in `ElectronNET.AspNet.csproj`. Reformatted the `Copy` task in `ElectronNET.Build.csproj` for readability. Updated `.pubxml` files and other project files to reflect the framework upgrade.
2025-12-11 07:25:07 +01:00
David Roth
5f76804065 Fix buidl by adding necessary using directives for async and DI setup. 2025-12-11 07:23:30 +01:00
Florian Rappl
70ffebf39d Updated changelog 2025-12-10 23:03:57 +01:00
Florian Rappl
0a54735f35 Merge branch 'main' of https://github.com/ElectronNET/Electron.NET into develop 2025-12-10 22:54:56 +01:00
Florian Rappl
1ac371b3da Merge pull request #962 from softworkz/submit_testupd
Collection of test fixes
2025-12-09 15:23:33 +01:00
Florian Rappl
e854451043 Merge pull request #968 from adityashirsatrao007/feat/host-hook-sample
feat: Add ElectronHostHook sample application (#967)
2025-12-09 10:21:36 +01:00
Aditya
331c2f548c fix: address review comments (protocol, config, startup) 2025-12-07 23:08:09 +05:30
Aditya
b00adcbd38 feat: Add ElectronHostHook sample application (#967) 2025-12-07 22:57:35 +05:30
Florian Rappl
ed6d24dbb1 Merge pull request #964 from niteshsinghal85/custom_main_example
Add custom_main.js guide to documentation
2025-12-07 18:08:26 +01:00
Florian Rappl
2c82206c62 Merge pull request #966 from softworkz/submit_migrationchecks
Add migration checks
2025-12-07 18:00:18 +01:00
softworkz
d0eb0880b1 Fix publishing documentation 2025-12-07 16:12:49 +01:00
softworkz
0321804128 Add documentation for migration checks 2025-12-07 16:12:49 +01:00
softworkz
f548ff08d4 Add migration checks 2025-12-07 16:12:23 +01:00
Nitesh Singhal
bbc7c79d5a Merge branch 'custom_main_example' of https://github.com/niteshsinghal85/Electron.NET into custom_main_example 2025-12-07 18:17:26 +05:30
Nitesh Singhal
2389ae32bd Update Custom_main.md to clarify usage of custom_main.js 2025-12-07 18:16:48 +05:30
Nitesh Singhal
42fecbdc98 Update docs/_Sidebar.md
Co-authored-by: softworkz <4985349+softworkz@users.noreply.github.com>
2025-12-07 18:10:16 +05:30
softworkz
95e02e2655 Introduce common base class for tests 2025-12-07 11:56:32 +01:00
softworkz
153625ba51 Introduce IntegrationFactAttribute 2025-12-07 11:56:26 +01:00
softworkz
c97f914e7a Introduce TimeSpan extensions 2025-12-07 11:20:43 +01:00
Nitesh Singhal
d95b41fbae Add custom_main.js guide to documentation 2025-12-07 15:00:28 +05:30
softworkz
2b2b26e13b GetSetUserAgent 2025-12-06 21:08:47 +01:00
softworkz
9bb2adca78 Use 3s timeout for GetUserAgentAsync and updat test 2025-12-06 20:53:15 +01:00
softworkz
88d2daacb1 WebContentsTests: Experiment!
Re-enable some tests for CI as experiment
2025-12-06 20:35:51 +01:00
softworkz
c90f003519 GetSetZoomLevel: Don't use shared window
Because we need a visible window and the main window
visibility must not be mutated by tests
2025-12-06 20:11:27 +01:00
softworkz
daa9f399e9 ScreenTests: Remove invalid constraints
Negative values for cursor position are not invalid
2025-12-06 20:09:05 +01:00
softworkz
6246b44d68 ReadyToShow_event_fires: Destroy window 2025-12-06 20:08:01 +01:00
softworkz
347c1ef0e4 Show_hide_visibility_roundtrip: Don't use shared window 2025-12-06 20:06:34 +01:00
softworkz
7c8eeef225 GetPrintersAsync: Increase timeout 2025-12-06 20:04:23 +01:00
Florian Rappl
44a820e285 Merge pull request #960 from agracio/apis
Removing all properties merged in #958
2025-12-06 14:12:59 +01:00
agracio
8ccc7bfdd0 updating Microsoft.VisualStudio.JavaScript.Sdk to correct version 2025-12-06 12:30:05 +00:00
agracio
cf185fd2fb removing properties from webContents.ts 2025-12-06 12:11:58 +00:00
agracio
4ee11aaeae removing properties 2025-12-06 11:58:30 +00:00
Florian Rappl
f1063bbe98 Merge pull request #958 from agracio/apis
Additional APIs for WebContents
2025-12-05 09:10:11 +01:00
agracio
7c39d28f81 adding missing semicolon 2025-12-05 00:09:22 +00:00
agracio
e52bf69dee excluding some tests based on GitHub runner OS 2025-12-04 20:36:41 +00:00
agracio
46d395ad12 excluding some tests based on GitHub runner OS 2025-12-04 20:31:14 +00:00
agracio
c0e3a595c3 adding a couple await Task.Delay(500); to test in order to resolve flaky tests 2025-12-04 19:26:24 +00:00
agracio
65db66b4e9 trying a different env variable for skipping tests 2025-12-04 19:16:41 +00:00
agracio
ce8a86baf5 trying to fix some tests on CI 2025-12-04 19:13:20 +00:00
agracio
7eaf84a021 attempting to fix some tests on CI 2025-12-04 19:07:26 +00:00
agracio
90f5f5dbe2 attempting to fix some tests on CI 2025-12-04 18:38:12 +00:00
agracio
e09ef35be4 removing incorrect import 2025-12-04 18:08:42 +00:00
agracio
dae521180f adding WebContents APIs for Zoom, Audio and DevTools 2025-12-04 17:52:01 +00:00
Florian Rappl
c81ed54fff Merge pull request #953 from kevinfoley/readme-fix
README.md: fix grammar and typos
2025-11-29 21:12:35 +01:00
Kevin Foley
276ce8f4dc README.md: fix grammar and typos 2025-11-25 17:13:20 -08:00
Florian Rappl
20212cdca7 Merge pull request #951 from agracio/macos-intel-runners
adding macOS Intel runner
2025-11-24 09:01:23 +01:00
agracio
0acdc65271 adding macOS Intel runner 2025-11-24 00:45:31 +00:00
Florian Rappl
c92a54fbda Merge pull request #949 from softworkz/submit_model_update
Update all model classes to Electron API 39.2
2025-11-22 14:17:25 +01:00
Florian Rappl
4de7760556 Merge pull request #948 from softworkz/submit_extend_test_matrix
CI Tests: Extend matrix - 6 runners and 2 Electron versions
2025-11-22 14:11:50 +01:00
softworkz
3821ca60ea getPrinters: Increase timeout 2025-11-22 02:27:44 +01:00
softworkz
59887cce5f Guard deserialization error 2025-11-22 02:24:32 +01:00
softworkz
77834d0f2e Drop workaround via DescriptinoAttribute: No longer needed 2025-11-22 02:24:32 +01:00
softworkz
6761119241 Update all model classes to Electron API 39.2 2025-11-22 02:24:32 +01:00
softworkz
41d9f0afc7 Integration CI Tests: Extend matrix for more runners and two Electron versions 2025-11-22 00:57:15 +01:00
Florian Rappl
1d554fda60 Merge pull request #945 from softworkz/submit_outpath
BrowserWindowOptions; Fix default  and add more Tests
2025-11-21 00:34:09 +01:00
softworkz
2f4d37d823 Try macOS 26 2025-11-20 20:32:08 +01:00
softworkz
1815951092 BrowserWindowOptions; Fix default for FullScreenable
Electron's default is true
2025-11-20 02:56:00 +01:00
Florian Rappl
aa483ebaa4 Updated version 2025-11-19 09:14:54 +01:00
Florian Rappl
9b4e0e4504 Merge pull request #942 from softworkz/submit_outpath
electron-builder: Provide correct output path
2025-11-19 02:14:45 +01:00
softworkz
d05191d1e2 electron-builder: Provide correct output path and fix publish url 2025-11-19 02:05:48 +01:00
Florian Rappl
ef41329a91 Merge pull request #938 from softworkz/submit_ipc_types
Fix API break: public API must not expose JsonElement objects
2025-11-17 16:27:56 +01:00
Florian Rappl
edafa8ccdb Merge pull request #939 from softworkz/submit_cleanup
Cleanup & Consistency
2025-11-17 15:15:42 +01:00
softworkz
55c035323b Use non-generic TaskCompletionSource where applicable 2025-11-17 13:58:47 +01:00
softworkz
2e5c6200a6 ShowItemInFolderAsync: Fix endless hang 2025-11-17 13:58:47 +01:00
softworkz
be518a7a10 IpcMain: Properly handle Ipc message params (always 2-elem array) 2025-11-17 13:57:04 +01:00
softworkz
9e9558b837 SocketIoFacade: Remove unused method
It's not needed for compatibility since SocketIoFacade is internal
2025-11-17 13:18:41 +01:00
softworkz
5f6e4a9e9d Disable Nullable for all projects (was already for API/AspNet) 2025-11-17 13:18:41 +01:00
softworkz
b89c08ee96 IpcMainTests: Properly test for the types of values (must not be JsonElement) 2025-11-17 13:17:01 +01:00
softworkz
8ff875435b Fix API break: public API must not expose JsonElement objects
This changes deserialization to the way how it was with
Json.Net: Only .net primitive types are exposed publicly
2025-11-17 13:17:01 +01:00
Florian Rappl
bfad0cd45a Merge pull request #937 from softworkz/submit_move_workflow
Move PR comment creation to separate workflow on:pull_request_target
2025-11-17 09:03:53 +01:00
softworkz
91ed116cb1 Harden reading of PR number against injection attacks 2025-11-17 03:33:51 +01:00
softworkz
54eac4b521 Add workflow files to solution 2025-11-17 02:49:57 +01:00
softworkz
ac05ded844 Move PR comment creation to separate workflow on:pull_request_target 2025-11-17 02:49:57 +01:00
Florian Rappl
5434b0ec8e Merge pull request #936 from ElectronNET/develop
Release 0.2.0
2025-11-16 23:19:06 +01:00
Florian Rappl
20acd31f1a Updated changelog 2025-11-16 09:59:46 +01:00
Florian Rappl
f53d071bd9 Merge pull request #929 from softworkz/submit_platform_annotations
ElectronNET.API: Add platform support attributes
2025-11-16 09:38:31 +01:00
softworkz
2cf3095450 BrowserWindowTests: Add delays everywhere 2025-11-16 03:05:33 +01:00
softworkz
0ec791da9d Improve test Progress_bar_and_always_on_top_toggle 2025-11-16 02:59:50 +01:00
softworkz
0580942a59 ElectronNET API: Add platform support attributes 2025-11-16 02:53:28 +01:00
Florian Rappl
8e8d88c48f Merge pull request #931 from softworkz/submit_update_tests
Integration Tests Everywhere!
2025-11-16 02:42:22 +01:00
softworkz
61476e3ca4 Try fix remaining tests 2025-11-16 01:04:58 +01:00
softworkz
9488576d8f Add integration-tests workflow 2025-11-16 00:30:07 +01:00
softworkz
ff1b802838 Update ElectronFixture 2025-11-16 00:30:07 +01:00
softworkz
c98ad58290 Add xunit.runner.json 2025-11-16 00:30:07 +01:00
softworkz
a30239e3a6 Update electron start 2025-11-16 00:30:07 +01:00
softworkz
17f24749cd Project defaults: Make RuntimeIdentifier overrideable 2025-11-16 00:30:07 +01:00
softworkz
7558037b91 ElectronNET.IntegrationTests: Add platform support attributes 2025-11-16 00:30:07 +01:00
softworkz
e4485fd483 Remove Can_set_app_logs_path test
It's pointless because it doesn't ever throw
2025-11-16 00:24:17 +01:00
softworkz
1a964b405e BrowserWindow tests: use about:blank as url 2025-11-16 00:24:17 +01:00
softworkz
dfcb2345f3 Test project: Update to .net10 2025-11-16 00:24:17 +01:00
softworkz
3f10d6b5dd Remove tests for app badgecount
These require a full-blown desktop environment which is hardly ever available where these tests are run
2025-11-16 00:24:17 +01:00
Florian Rappl
90c3eb2c88 Merge pull request #935 from softworkz/submit_ts_project
ElectronNET.Host: Replace website by a real ts project
2025-11-15 16:02:02 +01:00
Florian Rappl
dbf76a1d6d Merge pull request #927 from softworkz/submit_whitespace2
Fix formatting and add GitHub Action to check trailing whitespace
2025-11-15 16:00:36 +01:00
softworkz
8e7892ebd4 Fix whitespace formatting 2025-11-15 13:52:19 +01:00
softworkz
30b547b8d3 Add R# settings 2025-11-15 13:41:25 +01:00
softworkz
30b4d92291 Add GitHub Action to check trailing whitespace on PRs 2025-11-15 13:41:25 +01:00
softworkz
6c9027faf3 WebApp: Do not compiled TS on build
(it's sufficient on save)
2025-11-15 13:14:27 +01:00
softworkz
c712027ea3 ElectronNET.Host: Replace website by a real ts project 2025-11-15 13:13:35 +01:00
Florian Rappl
7889057022 Merge pull request #933 from softworkz/submit_invocation_rename
Rename PropertyGet to more generic Invocator
2025-11-15 12:38:48 +01:00
Florian Rappl
68c50f1c1e Merge pull request #928 from softworkz/submit_remove_priv
Remove softworkz' special sauce
2025-11-15 12:37:24 +01:00
Florian Rappl
1006355bb7 Merge pull request #930 from softworkz/submit_pkg_update
build project: Update packages (due to vulnerabilities)
2025-11-15 12:35:34 +01:00
Florian Rappl
12c5391164 Merge pull request #932 from softworkz/submit_platform_specific
Webb app: add platform guards and promote analyzer severity
2025-11-15 12:34:57 +01:00
Florian Rappl
8ba24c0f2f Merge pull request #934 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/js-yaml-4.1.1
Bump js-yaml from 4.1.0 to 4.1.1 in /src/ElectronNET.WebApp/ElectronHostHook
2025-11-15 12:25:28 +01:00
dependabot[bot]
bb7ae8d711 Bump js-yaml in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.0 to 4.1.1.
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.0...4.1.1)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.1.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-15 10:40:05 +00:00
softworkz
385dcfbf52 ApiBase: Code style and whitespace 2025-11-15 10:21:18 +01:00
softworkz
515430ff96 ApiBase: Rename PropertyGet to more generic Invocator 2025-11-15 10:21:18 +01:00
softworkz
a6d67a4dfe Make CA1416 and error (platform-depended reachabílitiy of code 2025-11-15 09:50:00 +01:00
softworkz
946b2af81a Webb app: add platform conditions 2025-11-15 09:50:00 +01:00
softworkz
1e483e9cc4 build project: Update packages (due to vulnerabilities) 2025-11-15 09:35:42 +01:00
softworkz
5305e17ba9 MSBuild props/targets: Adapt demo/test projects for change 2025-11-15 08:44:50 +01:00
softworkz
442084a3e5 MSBuild props/targets: Remove wrapped files 2025-11-15 08:44:50 +01:00
softworkz
cd205edabb common.props: Remove personal extras 2025-11-15 08:27:34 +01:00
Florian Rappl
10bf461b51 Prepare for Blazor support 2025-11-14 17:38:55 +01:00
Florian Rappl
5b0ab76d38 Disable Linux for now 2025-11-14 09:55:30 +01:00
Florian Rappl
349762bd5e Updated changelog 2025-11-14 09:46:01 +01:00
Florian Rappl
0b49467186 Merge pull request #924 from agracio/event-task-rework
ApiEventManager Rework and refactoring of task calls
2025-11-13 14:30:31 +01:00
agracio
6fa65aa149 adding block statements to if 2025-11-12 20:20:13 +00:00
agracio
816e9c0fe9 increasing test timeout times 2025-11-12 15:56:36 +00:00
agracio
c81b0e537f increasing test timeout times 2025-11-12 15:40:04 +00:00
agracio
b89e3caa17 Merge branch 'event-task-rework' of https://github.com/agracio/Electron.NET into event-task-rework 2025-11-12 15:32:33 +00:00
agracio
e8c5de63c9 reverting Linux CI changes, skipping printer test in CI 2025-11-12 15:32:17 +00:00
agracio
d7b9174853 Merge branch 'develop' into event-task-rework 2025-11-12 15:09:44 +00:00
agracio
5ba4ab24d5 adding virtual env instructions for Linux CI 2025-11-12 15:06:14 +00:00
agracio
c6ff957d9a rebase from develop, add timeouts to tests and attempt to skip NativeImageTests on Linux 2025-11-12 14:42:43 +00:00
Florian Rappl
c37f98dcd6 Added the test logger 2025-11-12 14:27:30 +01:00
Florian Rappl
0188051d6c Updated NUKE and integrated tests in CI/CD 2025-11-12 14:21:11 +01:00
Florian Rappl
3eb8507985 Updated to target .NET 10 as well 2025-11-12 13:48:03 +01:00
agracio
546668a2c0 refactoring events API, replacing task code with calls to ApiBase. 2025-11-12 10:43:32 +00:00
Florian Rappl
68feffba02 Merge pull request #922 from softworkz/submit_fix_ipc_params
Fix sendToIpcRenderer parameter handling
2025-11-12 01:30:35 +01:00
softworkz
12d2fcb484 Fix sendToIpcRenderer parameter handling 2025-11-11 23:46:56 +01:00
Florian Rappl
979cf72d4c Merge pull request #920 from Denny09310/feature/using-once
feat: Add "Once" socket listener registration for one-time handlers
2025-11-10 22:29:01 +01:00
Florian Rappl
14bf7fdcd8 Merge pull request #921 from softworkz/submit_missing_locks
SocketIOFacade: Add missing locking on .Off calls
2025-11-10 22:27:02 +01:00
softworkz
f89f2e7591 SocketIOFacade: Add missing locking on .Off calls 2025-11-10 21:29:16 +01:00
Denny09310
9a0a494bc5 fix: missing "Once" changes, rollback to "On" on Notification 2025-11-10 11:27:32 +01:00
Florian Rappl
41a2b075c9 Merge pull request #917 from Denny09310/feature/system-text-json
refactor: Migrating from Newtonsoft.Json to System.Text.Json
2025-11-10 11:03:19 +01:00
Denny09310
adc1e81743 fix: simplified add/remove of socket listener through usage of "Once" 2025-11-10 10:40:51 +01:00
Denny09310
d8062aae00 fix: scale factor can be a double 2025-11-10 10:40:19 +01:00
Denny09310
0522bc425b fix: using correct deserialization type instead JsonElement for everyting except mixed arrays 2025-11-09 15:46:33 +01:00
Denny09310
168eceac8c fix: removed unused JsonPropertyName as ElectronJson.Options as by default camel case 2025-11-09 15:17:42 +01:00
Denny09310
4736bc640c fix: added usings, simplified imports, using JsonElement.Deserialize directly instead of JsonSerializer.Deserialize(JsonElement), removed some unused attributes 2025-11-09 15:15:52 +01:00
Denny09310
18b1317fc5 fix: ignore writing when value is null 2025-11-09 14:53:44 +01:00
Denny09310
dfe04f14d0 fix: menuItems splattering due to "params" keyword 2025-11-09 14:40:55 +01:00
Denny09310
9d6861ffcd fix: including internal properties in json 2025-11-09 14:40:55 +01:00
Denny09310
d8b0d0443d fix: removed useless attribute 2025-11-09 14:40:55 +01:00
Denny09310
71ced8db56 refactor: Migrated from Newtonsoft.Json to System.Text.Json, missing one test passing 2025-11-09 14:40:51 +01:00
Florian Rappl
fc69598b09 Merge pull request #913 from softworkz/submit_tests_fixes
Add 77 IntegrationTests and lots of fixes
2025-11-09 14:05:41 +01:00
softworkz
60a278c41f Cookie: Fix formatting 2025-11-09 12:47:56 +01:00
softworkz
9d25795b7a SocketBridgeService: Fix state transition error 2025-11-09 12:45:01 +01:00
softworkz
5b597cc12c StartupManager: Add support for running under testhost 2025-11-09 12:45:01 +01:00
softworkz
707c0f5a7b BrowserView.cs: Fix cast exception in Bounds property getter 2025-11-09 12:45:01 +01:00
softworkz
bb59bc8365 App.cs: Fix UserAgentFallbackAsync 2025-11-09 12:45:01 +01:00
softworkz
423ea57af7 ipc.ts: Add helper method for tests 2025-11-09 12:45:01 +01:00
softworkz
8dcc3721eb browserWindows.ts: Fix SetThumbarButtons 2025-11-09 12:45:01 +01:00
softworkz
dc27511aa5 browserWindows.ts: Add catch for Set/GetRepresentedFilename
It's not supported on all platforms
2025-11-09 12:45:01 +01:00
softworkz
dd465baebf notification.ts: Fix notificationIsSupported
It's a method, was used like a property
2025-11-09 12:45:01 +01:00
softworkz
04210955a3 webContents.ts: Fix clearAuthCache invocation
The options were no propagated for the overload
with RemovePassword options
2025-11-09 12:45:01 +01:00
softworkz
4129cc17a6 main.js: Load api/process import (was missing) 2025-11-09 12:45:01 +01:00
softworkz
bc0f601dd8 ProcessMetric: Fix deserialization error for CreationTime 2025-11-09 12:45:01 +01:00
softworkz
95fd7aa665 ApiBase: fix event names for App 2025-11-09 12:45:01 +01:00
softworkz
402147b8ef BrowserWindow: Disable SetPosition 'workaround'
It doesn't make sense to do this adjustment for
set only but not for get.
Neither is this done for SetBounds, so it should
be either fully consistent or left up to the
application to deal with it.
2025-11-09 12:45:01 +01:00
softworkz
ed7cc434ea browserWindowSetParentWindow: Support null parameter 2025-11-09 12:44:20 +01:00
softworkz
c5fb5f62d9 Add IntegrationTests project 2025-11-09 12:44:20 +01:00
Florian Rappl
84989cda25 Merge pull request #914 from softworkz/submit_whitespace
Fix and normalize whitespace
2025-11-09 12:25:49 +01:00
softworkz
84b3c59353 Fix and normalize whitespace 2025-11-09 03:50:24 +01:00
Florian Rappl
c1e7b84ec6 Merge pull request #911 from Denny09310/develop
feat: updated 'TitleBarOverlay' property to be passed as object
2025-11-08 16:54:35 +01:00
Denny09310
9bb7dcfa62 fix: added WriteUndefined as there is Newtonsoft.Json 2025-11-08 16:49:33 +01:00
Denny09310
c0e711940d fix: don't write anything if value is null 2025-11-08 16:45:25 +01:00
Florian Rappl
d03458094b Added converter to improve object serialization 2025-11-08 16:38:36 +01:00
Denny09310
14962e1983 chore: updated documentation 2025-11-08 11:24:36 +01:00
Denny09310
d79b73e960 fix: using newtonsoft.json instead of system.text.json for the converter 2025-11-08 11:21:39 +01:00
Denny09310
21ae89bc70 fix: missing public constructor 2025-11-08 11:15:34 +01:00
Denny09310
7927a95cb8 feat: enhance titleBarOverlay to accept both a boolean and an object 2025-11-08 11:14:33 +01:00
Florian Rappl
758e6a41e3 Added properties 2025-11-07 22:12:54 +01:00
Florian Rappl
61421ddd66 Updated changelog 2025-11-07 09:58:38 +01:00
Florian Rappl
98d085f112 Merge pull request #907 from NimbusFox/main
Removed ownjsonSerializer from WindowManager
2025-11-07 08:47:12 +01:00
Florian Rappl
cf0b12ed0a Merge pull request #908 from softworkz/submit_api_consolidation
Mitigate race conditions and simplify API invocations
2025-11-07 08:46:36 +01:00
softworkz
4c3065c64b SocketIOFacade: Synchronize un/registration of events 2025-11-07 03:49:42 +01:00
softworkz
2a6d2117e9 Mitigate race condition, introduce timeout and simplify code for property gets 2025-11-07 03:49:08 +01:00
softworkz
93f457dd0f Introduce ApiBase and simplify method invocation 2025-11-07 00:11:52 +01:00
NimbusFox
6001a3c481 Removed ownjsonSerializer from WindowManager
Removed the unneeded serializer and applied the settings to the global
this._jsonSerializer as when the X and Y values are -1 in the options
it would lead to some settings not being applied. E.g. ContextIsolation
with it now applying the default values when serializing, settings
mentioned before are correctly assigned on Electron's end
2025-11-06 18:04:06 +00:00
Florian Rappl
4671b9b32a Merge pull request #905 from agracio/develop
Initial refactoring of dotnet  API
2025-11-06 10:22:04 +01:00
agracio
de7f98136e removing '-event' suffix from event names to normalise naming convention 2025-11-05 19:05:12 +00:00
agracio
87668f5606 removing '-event' suffix from event names to normalise naming convention 2025-11-05 18:59:21 +00:00
agracio
ea688026d0 refactoring dotnet events 2025-11-05 15:08:43 +00:00
agracio
b6b9292478 refactoring dotnet events 2025-11-05 15:06:41 +00:00
agracio
408f83e401 refactoring dotnet events 2025-11-05 14:14:37 +00:00
agracio
689a002dc2 refactoring dotnet events 2025-11-05 13:25:15 +00:00
Florian Rappl
f919289628 Switched default to true 2025-11-05 01:00:44 +01:00
Florian Rappl
2c544a83e9 Updated process class 2025-11-04 17:22:15 +01:00
Florian Rappl
2b393079ae Merge branch 'develop' 2025-11-04 16:18:53 +01:00
Florian Rappl
79d3d3f0b1 Fixed dup 2025-11-04 16:16:15 +01:00
Florian Rappl
688d6d83cc Fixed single instance behavior 2025-11-02 23:36:26 +01:00
Florian Rappl
7bcc5c9878 Corrected output path 2025-11-02 22:43:35 +01:00
Florian Rappl
0cfadb36f5 Updated process metric 2025-11-02 02:43:16 +01:00
Florian Rappl
568c785412 Redefine URL 2025-11-02 02:39:06 +01:00
Florian Rappl
2944e69b21 Added couple of enhancements 2025-11-02 02:24:32 +01:00
Florian Rappl
8df9eff3bc Updated repo 2025-11-01 10:44:49 +01:00
Florian Rappl
14f43f4574 Improved build process 2025-10-31 21:25:18 +01:00
Florian Rappl
d96eebd5ee Added float in SetAspectRatio 2025-10-31 18:25:50 +01:00
Florian Rappl
23fac3263f Updated readme 2025-10-31 18:24:27 +01:00
Florian Rappl
935de8a1a5 Updated packages 2025-10-31 17:56:05 +01:00
Florian Rappl
c2ba55e333 Merge branch 'develop' 2025-10-31 17:52:49 +01:00
Florian Rappl
be1887c930 Merge pull request #895 from softworkz/electronnet_core
Add documentation
2025-10-16 08:44:08 +02:00
softworkz
1852802667 Some more polishing 2025-10-15 23:04:37 +02:00
softworkz
5bdabd94ba Fix typos 2025-10-15 22:29:22 +02:00
softworkz
2bc2b4bb70 Move some parts from ReadMe to Wiki 2025-10-15 22:12:46 +02:00
softworkz
771b1109f7 Add About page 2025-10-15 22:12:46 +02:00
softworkz
56258d1be8 Add API documentation (AI generated) 2025-10-15 22:12:46 +02:00
softworkz
88766adaf6 Update docs after manual review 2025-10-15 16:06:53 +02:00
softworkz
341ebe2bb1 Add .gitkeep file 2025-10-15 16:06:53 +02:00
softworkz
0c5cc3ba9d AI-written docs 2025-10-15 16:06:53 +02:00
softworkz
bb5779a941 Add docs project to solution 2025-10-15 16:06:53 +02:00
softworkz
0dd263e2b8 Docs: add automatic Wiki publishing 2025-10-15 12:54:08 +02:00
softworkz
0a0e26a9dd Add docs 2025-10-15 12:54:08 +02:00
softworkz
7b812bfae7 Remove whatsnew from root 2025-10-15 12:40:02 +02:00
Florian Rappl
82814d91d9 Merge pull request #893 from softworkz/electronnet_core
ElectronNET.Core:: Taking it to the Next Leve
2025-10-14 23:59:42 +02:00
softworkz
fcb589d58e What's new doc page (AI writen) 2025-10-14 06:24:10 +02:00
softworkz
c914bb8f14 Draft for a ReadMe update 2025-10-14 06:24:10 +02:00
softworkz
bf3e149d43 Add changelog entries (AI authored) 2025-10-14 06:24:10 +02:00
softworkz
6060e355bd Fix warnings 2025-10-14 03:48:53 +02:00
softworkz
868451408c Move global.json to repo root 2025-10-14 03:48:03 +02:00
softworkz
bef7a42fbb Update nuke build with the following changes:
- Remove obsolete sample targets
- Restore and build solution (.Lean) instead of projects
- Read version from common.props, compare with latest changelog version
  and fail if not equal
- Keep PostFix separate from version (AssemblyVersion may not have
  a postfix), so the postfix will go into the package version and
  file name as well as the informational version (visible in file
  properties dialog on Windows)
- Add "ElectronNET.Core " as prefix to GitHub release names (to
  disambiguate with earlier versions)
2025-10-14 00:19:50 +02:00
softworkz
50b49068d8 Add VersionPostFix to common.props 2025-10-14 00:19:50 +02:00
softworkz
cf87904210 Mark ElectronNET.Build as non-packable 2025-10-14 00:19:50 +02:00
softworkz
0b05b2f5a4 Add solution ElectronNET.Lean for building core projects/packages only 2025-10-14 00:19:50 +02:00
softworkz
1ea4c1343d Add nuke project to solution 2025-10-14 00:19:50 +02:00
softworkz
5d5e0b848c Reset changelog 2025-10-14 00:19:40 +02:00
softworkz
2d626ab319 Reduce pinned dotnet version to 8.0.305 and rollForward to 'feature' 2025-10-14 00:19:11 +02:00
softworkz
2e051762dd Fix typos 2025-10-13 15:23:59 +02:00
softworkz
96063bbe7d ElectronNET.Core: Update solution file 2025-10-13 14:39:22 +02:00
softworkz
471289813a Check in version 0.0.18 packages for convenient testing 2025-10-13 14:38:58 +02:00
softworkz
d0d214cd24 Introduce a common.props file, which provides version and other package metadata
...in a single place.

There's some special sauce for myself, but we'll find a better way
eventually, so that it can be removed.
2025-10-13 14:36:31 +02:00
softworkz
43ce20d60f Add ElectronNET.ConsoleApp test project 2025-10-13 14:36:31 +02:00
softworkz
40d6558613 ElectronNET.WebApp: Update project file with these changes:
- Add a ElectronNetDevMode property at the top
  This allows switching the project between using the nuget packages
  and consuming the core code directly via project references and
  direct imports or .props and .targets files
- Add the project data which was previously in the manifest file
- Add the Microsoft.TypeScript.MSBuild package
  This overrides the ASP.Net built-in TS support which is currently
  at version 5.6 only. With this package, we get 5.9.3 everywhere, so
  everything is consistent now.
  The only caveat is that it requires exclusion of folders (especially
  node_modules), so that they don't get attempted to be compiled
2025-10-13 14:36:31 +02:00
softworkz
ae12eb49ee ElectronNET.WebApp: Adjust startup to use new onAppReady callback 2025-10-13 14:36:31 +02:00
softworkz
2a26b46f91 ElectronNET.WebApp: Add builder.json, launchsettings and publish profiles 2025-10-13 14:36:31 +02:00
softworkz
78b59f62c9 ElectronNET.WebApp: Adjust controllers for API changes 2025-10-13 14:36:31 +02:00
softworkz
667a1b290e ElectronNET.WebApp: Remove manifest file (not needed anymore) 2025-10-13 14:36:31 +02:00
softworkz
c5d9ba0e43 ElectronNET.WebApp: Remove invalid property in appSettings 2025-10-13 14:36:31 +02:00
softworkz
f81424978e ElectronNET.WebApp: HostHook: Make it compile properly 2025-10-13 14:36:31 +02:00
softworkz
7fcb2f05bd ElectronNET.WebApp: HostHook: Add missing deps, update same like Host code 2025-10-13 14:36:31 +02:00
softworkz
69129a6f02 ElectronNET.WebApp: nav.js and demo-btns.js: Increase timeouts
These were too short when debugging on WSL
2025-10-13 14:36:31 +02:00
softworkz
bcde1032af ElectronNET.AspNet: Add WebApplicationBuilderExtensions (new ASP.Net builders) 2025-10-13 14:36:31 +02:00
softworkz
3a42c479dd Add ElectronNET.AspNet project (ASP.Net specific runtime code) 2025-10-13 14:36:31 +02:00
softworkz
c6c73a7c8a ElectronNET.API: Update project file 2025-10-13 14:36:31 +02:00
softworkz
d1db928222 ElectronNET.API: Add new runtime code (for launch, lifecycle and service orchestration) 2025-10-13 14:36:31 +02:00
softworkz
b06d20450b ElectronNET.API: Add ProcessRunner (for running electron from dotnet) 2025-10-13 14:36:31 +02:00
softworkz
3811b7ea20 ElectronNET.API: Re-add moved types 2025-10-13 14:36:31 +02:00
softworkz
9275f2a765 ElectronNET.API: Add WebRequest API 2025-10-13 14:36:31 +02:00
softworkz
feddf5f8f4 ElectronNET.API: Move API code to subfolder 2025-10-13 14:36:18 +02:00
softworkz
e4ce61c965 ElectronNET.Host: Update compiled files 2025-10-13 14:36:18 +02:00
softworkz
1e93d91e66 ElectronNET.Host: Fix TS compilation error webcontents.ts
The crashed event has been removed in Electron 29 - just let TS ignore
that error
2025-10-13 14:36:18 +02:00
softworkz
77efea50ed ElectronNET.Host: Fix TS compilation error in tray.js
This probably stems from newer ts definition or the newer ts version.
It errored because it cannot determine the event name and so it
considers argv[] as empty.
2025-10-13 14:36:18 +02:00
softworkz
5ea368bb16 ElectronNET.Host: Update main.js with these changes:
- Consume host-hook as a module
- Use package.json instead of electron-manifest.json
- Support new commandline flags:
  - unpackedelectron
    running in debug mode, electron first, so must launch dotnet
  - unpackeddotnet
    running in debug mode, dotnet first, do not launch dotnet
  - dotnetpacked
    running from electron-builder output, dotnet first, do not launch
  - {none of the above flags}
    running from electron-builder output, electron first, launch dotnet
  - electronforcedport
    specified by dotnet when dotnet-first, port is validated to be free
- Removed 'watch' functionality (regular debugging is working now)
- New feature to load a custom_main.js file, if present
- Removed the 'electronWebPort' handling
  When ASP.Net is launched first, then the information which port it
  should use would be coming too late; anyway, there's no need for
  letting the port number round-trip all the way through the manifest
  file, loaded by main.js and then sent to dotnet.
- Reworked handling of 'quit' message
2025-10-13 14:36:18 +02:00
softworkz
0dca0e90f9 ElectronNET.Host: Update build configuration - changes:
- Update all packages to their latest version
- Drop tslint (replaced by eslint)
- Update node types to 22 => nodejs => 22 is minimum now
- Also use latest TypeScript version
- Finally, reference ElectronHostHook has a package dependency
  this avoids conflicts of dependency versions between main code
  and host-hook code, by letting npm resolve them
2025-10-13 13:16:10 +02:00
softworkz
c0c3aaebdc ElectronNET.Host: Remove build-helper and manifest (no longer needed) 2025-10-13 13:08:32 +02:00
softworkz
14722e1f63 Remove ElectronNET.CLI project 2025-10-13 13:06:50 +02:00
softworkz
d6e39fef24 Add ElectronNET.Build project (dll with custom MSBuild tasks) 2025-10-13 13:06:20 +02:00
softworkz
74b80b3177 Add ElectronNET project (all build functionality) 2025-10-13 13:05:34 +02:00
softworkz
0f3f29eae3 global.json: Pin .net SDK 2025-10-13 13:04:24 +02:00
softworkz
f634dc45ed Update NuGet.config 2025-10-13 13:03:53 +02:00
softworkz
c6b9de2afa Update .gitignore 2025-10-13 13:03:36 +02:00
Florian Rappl
9a615ca7e0 Merge pull request #881 from hillin/reintroduce-#648
Reintroduce #648
2025-06-22 07:53:30 +02:00
Todd Schavey
f9601a6e3e fix #647 make ProcessVersions Entity a record to ensure readonly access to props
This is to address a PR #648 review comment to ensure that only the external
users are not able to modify the instance values.
2025-06-18 11:57:04 +08:00
Todd Schavey
8daf4d1498 #647 update XML documentation to ElectronNET.API Process members 2025-06-18 11:52:02 +08:00
Todd Schavey
c01ef407af fix #647 add to ElectronNET.API Process member interfaces for various fields 2025-06-18 11:51:58 +08:00
Todd Schavey
dc019adb10 #647 add to ElectronNET.API Process member interfaces for argv and type 2025-06-18 11:47:01 +08:00
Todd Schavey
f7de17f1ee fix #647 add initial Process class to ElectronNET.API 2025-06-18 11:46:42 +08:00
Todd Schavey
ca748384cf fix #647 process argv for open-file for win and linux 2025-06-18 11:40:23 +08:00
Florian Rappl
4c880cb627 Merge pull request #852 from rs22/update-electron-30
Update Electron version to 30.0.3
2024-06-04 20:51:37 +02:00
Robert Schmid
e46ba98c8d Update version in ElectronNET.WebApp electron manifest 2024-06-04 15:57:22 +02:00
Robert Schmid
4b9fe4656e Add changelog entry 2024-06-04 15:56:47 +02:00
Robert Schmid
fdb8be46b7 Update electron version 2024-05-10 17:34:27 +02:00
Florian Rappl
e361367a95 Merge pull request #849 from gorsheninmv/get-back-net6-support
Get back net6 support
2024-05-01 17:08:29 +02:00
Florian Rappl
7ca40bcaec Merge pull request #848 from gorsheninmv/update-npm-packages
Update node modules packages
2024-05-01 14:37:39 +02:00
Misha Gorshenin
1864c21c10 fix: specify target framework 2024-05-01 13:20:14 +05:00
Misha Gorshenin
0775b91dd4 fix: get back net6 support 2024-05-01 09:49:47 +05:00
Misha Gorshenin
f55dbc14c0 chore: update node modules packages 2024-05-01 09:16:25 +05:00
Florian Rappl
6472f34a75 Merge pull request #847 from gorsheninmv/feat-introduce-new-cli-args
Add /no-restore and SelfContained property support in CLI
2024-04-29 15:40:27 +02:00
Misha Gorshenin
91714f5807 feat: CLI: add /no-restore arg and SelfContained propeprty support 2024-04-29 14:56:57 +05:00
Florian Rappl
6182320003 Merge branch 'main' into develop 2024-04-29 11:45:11 +02:00
Florian Rappl
5125ee0109 Merge pull request #801 from ds5678/primitive-implicit-conversions
Implicit Conversions to System.Drawing structs
2024-04-29 11:42:45 +02:00
Florian Rappl
21c17dc82b Merge pull request #846 from Lemon73-Computing/net8.0
Upgrade to .NET 8.0
2024-04-27 20:11:37 +02:00
Lemon73-Computing
dbcd4ac940 add: setting
self-contained
2024-04-26 19:42:32 +09:00
Lemon73-Computing
286978c523 update: readme.md
.net 6 -> .net 8
2024-04-25 17:27:45 +09:00
Lemon73-Computing
96ae77ceb4 update: workflow 2024-04-25 01:01:22 +09:00
Lemon73-Computing
a893ccd646 fix: debug workflows 2024-04-25 00:58:50 +09:00
Lemon73-Computing
2edad2d329 upgrade: dependencies version 2024-04-25 00:58:27 +09:00
Lemon73-Computing
7be796f77b upgrade: dependency
* nuke 6.2.1 -> 8.0.0
2024-04-25 00:34:38 +09:00
Lemon73-Computing
19da7f47b1 change: target dotnet version 2024-04-24 23:44:10 +09:00
Florian Rappl
d22532488e Updated to 23.6.2 2024-02-15 01:12:33 +01:00
Florian Rappl
30558dea5f Updated changelog 2024-02-15 01:10:48 +01:00
Florian Rappl
464eaca593 Merge branch 'main' of https://github.com/ElectronNET/Electron.NET into develop 2024-02-15 01:04:11 +01:00
Florian Rappl
df3bd122df Merge pull request #813 from softworkz/submit_execjs_domready
WebContents: add executeJavaScript and dom-ready event
2024-02-15 01:01:59 +01:00
Florian Rappl
eabcc3a6b6 Merge pull request #798 from dlanorok/fixes/appSetAccessibilitySupportEnabled
Fixes/app set accessibility support enabled
2024-02-15 01:01:38 +01:00
Florian Rappl
2b5435381f Merge pull request #800 from franpersanchez/main
fix: typo in README.md
2024-02-15 00:59:08 +01:00
Florian Rappl
0d63383899 Merge pull request #833 from Yuvix25/ipc-once-memory
Fix huge memory waste in IpcMain.Once [IMPORTANT]
2024-02-15 00:55:40 +01:00
Florian Rappl
f31fe19652 Merge pull request #828 from Yuvix25/yuvix25/update-display-object
Update Display.cs to current spec
2024-02-15 00:55:33 +01:00
Florian Rappl
0a80367e3e Merge pull request #822 from NickRimmer/features/splash-size
Configurable splash screen size
2024-02-15 00:55:13 +01:00
Florian Rappl
34761456ad Merge pull request #821 from sajmonr/feature/osx-architecture-detection
Added OSX architecture detection
2024-02-15 00:55:05 +01:00
Florian Rappl
e4e96bbcc4 Merge pull request #819 from NickRimmer/features/webContent-additional-events
WebContent additional events
2024-02-15 00:54:42 +01:00
Yuval Rosen
1253df3d9a Fix huge memory waste in IpcMain.Once 2024-02-15 01:06:08 +02:00
Yuval Rosen
b8b634beb3 update display.cs to current spec 2024-01-10 11:10:49 +02:00
Nick Rimmer
94dc82ec62 configurable splash screen size 2023-11-13 01:29:17 +01:00
Adam Simonicek
53ccf4d302 Added OSX architecture detection 2023-11-04 14:09:07 -04:00
Nick Rimmer
bf0bdc8386 did-start-navigation, did-navigate, will-redirect, did-fail-load, did-redirect-navigation events added for WebContents 2023-11-03 00:23:37 +01:00
softworkz
73a3e331dc Add executeJavaScript method to WebContents 2023-09-24 16:37:36 +02:00
softworkz
a15db713ad Add dom-ready event for WebContents 2023-09-24 16:37:36 +02:00
Jeremy Pritts
4be5cef3ef Add implicit conversions to System.Drawing structs. 2023-08-24 21:09:19 -04:00
Fran Pérez
e2d03d6818 fix: typo in README.md 2023-08-24 18:24:15 +02:00
Ronald Ramirez Moran
0dc8369fb3 Method SetAccessibilitySupportEnabled is incorrect. 2023-08-23 18:39:37 -05:00
507 changed files with 37811 additions and 15768 deletions

137
.github/CONTRIBUTING.md vendored Normal file
View File

@@ -0,0 +1,137 @@
# Contributing
## Project Scope
The Electron.NET project ultimately tries to provide a framework for developing cross-platform client applications on the basis of .NET and Electron. Anything that is related to this goal will be considered. The project aims to be as close to Electron with .NET as a basis as possible. If your contribution does not reflect that goal, the chances of accepting it are limited.
## Code License
This is an open source project falling under the [MIT License](../LICENSE). By using, distributing, or contributing to this project, you accept and agree that all code within the Electron.NET project and its libraries are licensed under MIT license.
## Becoming a Contributor
Usually appointing someone as a contributor follows this process:
1. An individual contributes actively via discussions (reporting bugs, giving feedback to existing or opening new issues) and / or pull requests
2. The individual is either directly asked, invited or asks for contributor rights on the project
3. The individual uses the contribution rights to sustain or increase the active contributions
Every contributor might have to sign the contributor's license agreement (CLA) to establish a legal trust between the project and its contributors.
## Working on Electron.NET
### Issue Discussion
Discussion of issues should be placed transparently in the issue tracker here on GitHub.
* [General issues, bugs, new features](https://github.com/ElectronNET/Electron.NET/issues)
* [General discussions, help, exchange of ideas](https://github.com/ElectronNET/Electron.NET/discussions)
### Modifying the code
Electron.NET and its libraries uses features from the latest versions of C# (e.g., C# 10). You will therefore need a C# compiler that is up for the job.
1. Fork and clone the repo.
2. First try to build the ElectronNET.Core library and see if you get the tests running.
3. You will be required to resolve some dependencies via NuGet.
The build system of Electron.NET uses NUKE.
### Code Conventions
Most parts in the Electron.NET project are fairly straight forward. Among these are:
* Always use statement blocks for control statements, e.g., in a for-loop, if-condition, ...
* You may use a simple (throw) statement in case of enforcing contracts on argument
* Be explicit about modifiers (some files follow an older convention of the code base, but we settled on the explicit style)
### Development Workflow
1. If no issue already exists for the work you'll be doing, create one to document the problem(s) being solved and self-assign.
2. Otherwise please let us know that you are working on the problem. Regular status updates (e.g. "still in progress", "no time anymore", "practically done", "pull request issued") are highly welcome.
3. Create a new branch—please don't work in the `main` branch directly. It is reserved for releases. We recommend naming the branch to match the issue being addressed (`feature/#777` or `issue-777`).
4. Add failing tests for the change you want to make. Tests are crucial and should be taken from W3C (or other specification).
5. Fix stuff. Always go from edge case to edge case.
6. All tests should pass now. Also your new implementation should not break existing tests.
7. Update the documentation to reflect any changes. (or document such changes in the original issue)
8. Push to your fork or push your issue-specific branch to the main repository, then submit a pull request against `develop`.
Just to illustrate the git workflow for Electron.NET a little bit more we've added the following graphs.
Initially, Electron.NET starts at the `main` branch. This branch should contain the latest stable (or released) version.
Here we now created a new branch called `develop`. This is the development branch.
Now active work is supposed to be done. Therefore a new branch should be created. Let's create one:
```sh
git checkout -b feature/#777
```
There may be many of these feature branches. Most of them are also pushed to the server for discussion or synchronization.
```sh
git push -u origin feature/#777
```
Now feature branches may be closed when they are done. Here we simply merge with the feature branch(es). For instance the following command takes the `feature/#777` branch from the server and merges it with the `develop` branch.
```sh
git checkout develop
git pull
git pull origin feature/#777
git push
```
Finally, we may have all the features that are needed to release a new version of Electron.NET. Here we tag the release. For instance for the 1.0 release we use `v1.0`.
```sh
git checkout main
git merge develop
git tag v1.0
```
(The last part is automatically performed by our CI system. Don't tag manually.)
### Versioning
The rules of [semver](http://semver.org/) don't necessarily apply here, but we will try to stay quite close to them.
Prior to version 1.0.0 we use the following scheme:
1. MINOR versions for reaching a feature milestone potentially combined with dramatic API changes
2. PATCH versions for refinements (e.g. performance improvements, bug fixes)
After releasing version 1.0.0 the scheme changes to become:
1. MAJOR versions at maintainers' discretion following significant changes to the codebase (e.g., API changes)
2. MINOR versions for backwards-compatible enhancements (e.g., performance improvements)
3. PATCH versions for backwards-compatible bug fixes (e.g., spec compliance bugs, support issues)
#### Code style
Regarding code style like indentation and whitespace, **follow the conventions you see used in the source already.** In general most of the [C# coding guidelines from Microsoft](https://msdn.microsoft.com/en-us/library/ff926074.aspx) are followed. This project prefers type inference with `var` to explicitly stating (redundant) information.
It is also important to keep a certain `async`-flow and to always use `ConfigureAwait(false)` in conjunction with an `await` expression.
## Backwards Compatibility
We always try to remain backwards compatible beyond the currently supported versions of .NET.
For instance, in December 2025 there have been activity to remove .NET 6 support from the codebase. We rejected this. Key points:
1. We have absolutely no need to drop `.net6` support. It doesn't hurt us in any way.
2. Many are still using `.net6`, including Electron.NET (non-Core) users. It doesn't make sense to force them to update two things at the same time (.NET + Electron.NET).
3. We MUST NOT and NEVER update `Microsoft.Build.Utilities.Core`. This will make Electron.NET stop working on older Visual Studio and MSBuild versions. There's are also no reasons to update it in the first place.
It's important to note that the Microsoft label of "Out of support" on .NET has almost no practical meaning. We've rarely (if ever) seen any bugs fixed in the same .NET version which mattered. The bugs that all new .NET versions have are much worse than mature .NET versions which are declared as "out of support". Keep in mind that the LTS matters most for active development / ongoing supported projects. If, e.g., a TV has been released a decade ago it most likely won't be patched. Still, you might want to deploy applications to it, which then naturally would involve being based on "out of support" versions of the framework.
TL;DR: Unless there is a technical reason (e.g., a crucial new API not being available) we should not drop "out of support" .NET versions. At the time of writing (December 2025) the minimum supported .NET version remains at `.net6`.
## Timeline
**All of this information is related to ElectronNET.Core pre-v1!**
We pretty much release whenever we have something new (i.e., do fixes such as a 0.1.1, or add new features, such as a 0.2.0) quite quickly.
We will go for a 1.0.0 release of this as early as ~mid of January 2026 (unless we find some critical things or want to extend the beta phase for ElectronNET.Core). This should be sufficient time to get some user input and have enough experience to call it stable.

BIN
.github/WikiLinks.exe vendored Normal file

Binary file not shown.

View File

@@ -1,40 +1,36 @@
name: CI
name: Build and Publish
on: [push, pull_request]
on: [push]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
concurrency:
group: build-publish-${{ github.ref }}
cancel-in-progress: true
jobs:
linux:
runs-on: ubuntu-latest
Integration-Tests:
uses: ./.github/workflows/integration-tests.yml
name: '1'
steps:
- uses: actions/checkout@v2
- name: Setup dotnet
uses: actions/setup-dotnet@v1
with:
dotnet-version: |
6.0.x
7.0.x
- name: Build
run: ./build.sh
windows:
Publish:
needs: [Integration-Tests]
runs-on: windows-latest
timeout-minutes: 10
name: '2 / Publish'
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Setup dotnet
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v4
with:
dotnet-version: |
6.0.x
7.0.x
8.0.x
10.0.x
- name: Build
run: |

39
.github/workflows/PR Validation.yml vendored Normal file
View File

@@ -0,0 +1,39 @@
name: PR Validation
on: [pull_request]
concurrency:
group: pr-validation-${{ github.ref }}
cancel-in-progress: true
jobs:
Whitespace-Check:
uses: ./.github/workflows/trailing-whitespace-check.yml
secrets: inherit
name: '1'
Tests:
needs: Whitespace-Check
uses: ./.github/workflows/integration-tests.yml
secrets: inherit
name: '2'
build:
needs: [Whitespace-Check, Tests]
runs-on: windows-latest
timeout-minutes: 10
name: '3 / Build'
steps:
- uses: actions/checkout@v4
- name: Setup dotnet
uses: actions/setup-dotnet@v4
with:
dotnet-version: |
6.0.x
8.0.x
10.0.x
- name: Build
run: .\build.ps1

220
.github/workflows/integration-tests.yml vendored Normal file
View File

@@ -0,0 +1,220 @@
name: Tests
on:
workflow_call:
concurrency:
group: integration-tests-${{ github.ref }}
cancel-in-progress: true
jobs:
tests:
name: ${{ matrix.os }} API-${{ matrix.electronVersion }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-22.04, ubuntu-24.04, windows-2022, windows-2025, macos-14, macos-15-intel, macos-26]
electronVersion: ['30.4.0', '38.2.2']
include:
- os: ubuntu-22.04
rid: linux-x64
- os: ubuntu-24.04
rid: linux-x64
- os: windows-2022
rid: win-x64
- os: windows-2025
rid: win-x64
- os: macos-14
rid: osx-arm64
- os: macos-15-intel
rid: osx-x64
- os: macos-26
rid: osx-arm64
env:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1
DOTNET_NOLOGO: 1
CI: true
ELECTRON_ENABLE_LOGGING: 1
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Random delay (0-20 seconds)
shell: bash
run: |
DELAY=$((RANDOM % 21))
echo "Waiting for $DELAY seconds..."
sleep $DELAY
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Restore
run: dotnet restore -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj
- name: Build
run: dotnet build --no-restore -c Release -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj
- name: Install Linux GUI dependencies
if: runner.os == 'Linux'
run: |
set -e
sudo apt-get update
. /etc/os-release
if [ "$VERSION_ID" = "24.04" ]; then ALSA_PKG=libasound2t64; else ALSA_PKG=libasound2; fi
echo "Using ALSA package: $ALSA_PKG"
sudo apt-get install -y xvfb \
libgtk-3-0 libnss3 libgdk-pixbuf-2.0-0 libdrm2 libgbm1 libxss1 libxtst6 libatk-bridge2.0-0 libatk1.0-0 libatspi2.0-0 libx11-xcb1 "$ALSA_PKG"
- name: Run tests (Linux)
if: runner.os == 'Linux'
continue-on-error: true
run: |
mkdir -p test-results
xvfb-run -a dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj \
-c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} \
--logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" \
--logger "console;verbosity=detailed" \
--results-directory test-results
- name: Run tests (Windows)
if: runner.os == 'Windows'
continue-on-error: true
run: |
New-Item -ItemType Directory -Force -Path test-results | Out-Null
dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj -c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} --logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" --logger "console;verbosity=detailed" --results-directory test-results
- name: Run tests (macOS)
if: runner.os == 'macOS'
continue-on-error: true
run: |
mkdir -p test-results
dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj -c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} --logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" --logger "console;verbosity=detailed" --results-directory test-results
- name: Upload raw test results
if: always()
uses: actions/upload-artifact@v4
with:
name: test-results-${{ matrix.os }}-electron-${{ matrix.electronVersion }}
path: test-results/*.trx
retention-days: 7
summary:
name: Test Results
runs-on: ubuntu-24.04
if: always()
needs: [tests]
permissions:
actions: read
contents: read
checks: write
pull-requests: write
steps:
- name: Download all test results
uses: actions/download-artifact@v4
with:
path: test-results
- name: Setup .NET (for CTRF conversion)
uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- name: Install CTRF TRX→CTRF converter (dotnet tool)
run: |
dotnet new tool-manifest
dotnet tool install DotnetCtrfJsonReporter --local
- name: Convert TRX → CTRF and clean names (filePath=OS|Electron X.Y.Z)
shell: bash
run: |
set -euo pipefail
mkdir -p ctrf
shopt -s globstar nullglob
conv=0
for trx in test-results/**/*.trx; do
base="$(basename "$trx" .trx)" # e.g. ubuntu-22.04-electron-30.4.0
os="${base%%-electron-*}"
electron="${base#*-electron-}"
label="$os|Electron $electron"
outdir="ctrf/${label}"
mkdir -p "$outdir"
out="${outdir}/ctrf-report.json"
dotnet tool run DotnetCtrfJsonReporter -p "$trx" -d "$outdir" -f "ctrf-report.json"
jq --arg fp "$label" '.results.tests |= map(.filePath = $fp)' "$out" > "${out}.tmp" && mv "${out}.tmp" "$out"
echo "Converted & normalized $trx -> $out"
conv=$((conv+1))
done
echo "Processed $conv TRX file(s)"
- name: Publish Test Report
if: always()
uses: ctrf-io/github-test-reporter@v1
with:
report-path: 'ctrf/**/*.json'
summary: true
pull-request: false
status-check: false
status-check-name: 'Integration Tests'
use-suite-name: true
update-comment: true
always-group-by: true
overwrite-comment: true
exit-on-fail: true
group-by: 'suite'
upload-artifact: true
fetch-previous-results: true
summary-report: false
summary-delta-report: true
github-report: true
test-report: false
test-list-report: false
failed-report: true
failed-folded-report: false
skipped-report: true
suite-folded-report: true
suite-list-report: false
file-report: true
previous-results-report: true
insights-report: true
flaky-report: true
flaky-rate-report: true
fail-rate-report: false
slowest-report: false
report-order: 'summary-delta-report,failed-report,skipped-report,suite-folded-report,file-report,previous-results-report,github-report'
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Save PR Number
if: github.event_name == 'pull_request'
run: echo "PR_NUMBER=${{ github.event.pull_request.number }}" >> $GITHUB_ENV
- name: Write PR Number to File
if: github.event_name == 'pull_request'
run: echo "$PR_NUMBER" > pr_number.txt
shell: bash
- name: Upload PR Number Artifact
if: github.event_name == 'pull_request'
uses: actions/upload-artifact@v4
with:
name: pr_number
path: pr_number.txt
- name: Summary
run: echo "All matrix test jobs completed."

81
.github/workflows/pr-comment.yml vendored Normal file
View File

@@ -0,0 +1,81 @@
name: Create PR Comments
on:
workflow_run:
workflows: [ "PR Validation" ]
types: [completed]
permissions:
contents: read
actions: read
pull-requests: write
jobs:
pr-comment:
name: Post Test Result as PR comment
runs-on: ubuntu-24.04
if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'cancelled'
steps:
- name: Download CTRF artifact
uses: dawidd6/action-download-artifact@v8
with:
github_token: ${{ github.token }}
run_id: ${{ github.event.workflow_run.id }}
name: ctrf-report
path: ctrf
- name: Download PR Number Artifact
uses: dawidd6/action-download-artifact@v8
with:
github_token: ${{ github.token }}
run_id: ${{ github.event.workflow_run.id }}
name: pr_number
path: pr_number
- name: Read PR Number
run: |
set -Eeuo pipefail
FILE='pr_number/pr_number.txt'
# Ensure file exists
if [ ! -f "$FILE" ] || [ -L "$FILE" ]; then
echo "Error: $FILE is missing or is not a regular file." >&2
exit 1
fi
# Chec file size
if [ "$(wc -c < "$FILE" | tr -d ' ')" -gt 200 ]; then
echo "Error: $FILE is too large." >&2
exit 1
fi
# Read first line
PR_NUMBER=""
IFS= read -r PR_NUMBER < "$FILE" || true
# Validate whether it's a number
if ! [[ "$PR_NUMBER" =~ ^[0-9]{1,10}$ ]]; then
echo "Error: PR_NUMBER is not a valid integer on the first line." >&2
exit 1
fi
printf 'PR_NUMBER=%s\n' "$PR_NUMBER" >> "$GITHUB_ENV"
- name: Post PR Comment
uses: ctrf-io/github-test-reporter@v1
with:
report-path: 'ctrf/**/*.json'
issue: ${{ env.PR_NUMBER }}
summary: true
pull-request: true
use-suite-name: true
update-comment: true
always-group-by: true
overwrite-comment: true
upload-artifact: false
pull-request-report: true
env:
GITHUB_TOKEN: ${{ github.token }}

59
.github/workflows/publish-wiki.yml vendored Normal file
View File

@@ -0,0 +1,59 @@
name: Publish wiki
on:
push:
branches: [electronnet_core, main]
workflow_dispatch:
concurrency:
group: publish-wiki
cancel-in-progress: true
permissions:
contents: write
jobs:
publish-wiki:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- name: Remove level 1 headings from Markdown files
shell: bash
run: |
find docs/ -name '*.md' -exec sed -i '1d' {} \;
- name: Move all files to root folder
shell: bash
run: |
mv docs/*/* docs/
- name: Delete unwanted files
shell: bash
run: |
# rm docs/*.xlsm
# rm docs/*.pptx
rm docs/*.shproj
- name: Stripping file extensions....
uses: softworkz/strip-markdown-extensions-from-links-action@main
with:
path: ./docs/
- name: Copy Changelog
shell: bash
run: |
cp Changelog.md docs/RelInfo/ 2>/dev/null || true
- name: Copy images to wiki/wiki folder
shell: bash
run: |
mkdir docs/wiki
cp docs/*.svg docs/wiki/ 2>/dev/null || true
cp docs/*.png docs/wiki/ 2>/dev/null || true
cp docs/*.jpg docs/wiki/ 2>/dev/null || true
cp docs/*.gif docs/wiki/ 2>/dev/null || true
cp docs/*.mp4 docs/wiki/ 2>/dev/null || true
- name: Commit and push changes
run: |
git config --global user.name "GitHub Action"
git config --global user.email "action@github.com"
git add -A
git commit -m "Automatically update Markdown files" || echo "No changes to commit"
- uses: Andrew-Chen-Wang/github-wiki-action@v4.4.0
with:
path: docs/
ignore: |
'**/*.xlsm'
'**/*.pptx'
'**/*.shproj'

49
.github/workflows/retry-test-jobs.yml vendored Normal file
View File

@@ -0,0 +1,49 @@
name: Tests auto-rerun
on:
workflow_run:
workflows: [ "PR Validation", "Build and Publish" ]
types: [ completed ]
jobs:
rerun-failed-matrix-jobs-once:
if: >
${{
github.event.workflow_run.conclusion == 'failure' &&
github.event.workflow_run.run_attempt == 1
}}
runs-on: ubuntu-24.04
permissions:
actions: write
contents: read
steps:
- name: Decide whether to rerun (only if matrix jobs failed)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
RUN_ID: ${{ github.event.workflow_run.id }}
run: |
echo "Inspecting jobs of workflow run $RUN_ID in $REPO"
jobs_json="$(gh api -R $REPO repos/$REPO/actions/runs/$RUN_ID/jobs)"
echo "Jobs and conclusions:"
echo "$jobs_json" | jq '.jobs[] | {name: .name, conclusion: .conclusion}'
failed_matrix_jobs=$(echo "$jobs_json" | jq -r '
[ .jobs[]
| select(.conclusion == "failure"
and (.name | contains(" API-")))
]
| length // 0
')
failed_matrix_jobs=${failed_matrix_jobs:-0}
if [ "${failed_matrix_jobs}" -gt 0 ]; then
echo "Detected failing Integration Tests jobs re-running failed jobs for this run."
gh run rerun -R "$REPO" "$RUN_ID" --failed
else
echo "Only non-matrix jobs (like Test Results) failed not auto-rerunning."
fi

View File

@@ -0,0 +1,84 @@
name: Whitespace Check
on:
workflow_call:
jobs:
check-whitespace:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check for trailing whitespace
run: |
echo "Checking for trailing whitespace in changed files..."
# Get the base branch
BASE_SHA="${{ github.event.pull_request.base.sha }}"
HEAD_SHA="${{ github.event.pull_request.head.sha }}"
# Get list of changed files (excluding deleted files)
CHANGED_FILES=$(git diff --name-only --diff-filter=d "$BASE_SHA" "$HEAD_SHA")
if [ -z "$CHANGED_FILES" ]; then
echo "No files to check."
exit 0
fi
# File patterns to check (text files)
PATTERNS="\.cs$|\.csproj$|\.sln$|\.ts$|\.html$|\.css$|\.scss$"
# Directories and file patterns to exclude
EXCLUDE_PATTERNS="(^|\/)(\.|node_modules|bin|obj|artifacts|packages|\.vs|\.nuke\/temp)($|\/)"
ERRORS_FOUND=0
TEMP_FILE=$(mktemp)
while IFS= read -r file; do
# Skip if file doesn't exist (shouldn't happen with --diff-filter=d, but just in case)
if [ ! -f "$file" ]; then
continue
fi
# Check if file matches patterns to check
if ! echo "$file" | grep -qE "$PATTERNS"; then
continue
fi
# Check if file should be excluded
if echo "$file" | grep -qE "$EXCLUDE_PATTERNS"; then
continue
fi
# Find trailing whitespace lines, excluding XML doc placeholder lines that are exactly "/// " (one space)
MATCHES=$(grep -n '[[:space:]]$' "$file" | grep -vE '^[0-9]+:[[:space:]]*/// $' || true)
if [ -n "$MATCHES" ]; then
echo "❌ Trailing whitespace found in: $file"
echo "$MATCHES" | head -10
TOTAL=$(echo "$MATCHES" | wc -l)
if [ "$TOTAL" -gt 10 ]; then
echo " ... and $(($TOTAL - 10)) more lines"
fi
echo "1" >> "$TEMP_FILE"
fi
done <<< "$CHANGED_FILES"
ERRORS_FOUND=$(wc -l < "$TEMP_FILE" 2>/dev/null || echo "0")
rm -f "$TEMP_FILE"
if [ "$ERRORS_FOUND" -gt 0 ]; then
echo ""
echo "❌ Found trailing whitespace in $ERRORS_FOUND file(s)."
echo "Please remove trailing whitespace from the files listed above."
exit 1
else
echo "✅ No trailing whitespace found in changed files."
exit 0
fi

1
.gitignore vendored
View File

@@ -266,3 +266,4 @@ __pycache__/
# Nuke build tool
.nuke/temp
/publish.cmd

View File

@@ -1,19 +1,54 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Build Schema",
"$ref": "#/definitions/build",
"definitions": {
"build": {
"type": "object",
"Host": {
"type": "string",
"enum": [
"AppVeyor",
"AzurePipelines",
"Bamboo",
"Bitbucket",
"Bitrise",
"GitHubActions",
"GitLab",
"Jenkins",
"Rider",
"SpaceAutomation",
"TeamCity",
"Terminal",
"TravisCI",
"VisualStudio",
"VSCode"
]
},
"ExecutableTarget": {
"type": "string",
"enum": [
"Clean",
"Compile",
"Default",
"Package",
"PrePublish",
"Publish",
"PublishPackages",
"PublishPreRelease",
"PublishRelease",
"Restore",
"RunUnitTests"
]
},
"Verbosity": {
"type": "string",
"description": "",
"enum": [
"Verbose",
"Normal",
"Minimal",
"Quiet"
]
},
"NukeBuild": {
"properties": {
"Configuration": {
"type": "string",
"description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)",
"enum": [
"Debug",
"Release"
]
},
"Continue": {
"type": "boolean",
"description": "Indicates to continue a previously failed build attempt"
@@ -23,25 +58,8 @@
"description": "Shows the help text for this build assembly"
},
"Host": {
"type": "string",
"description": "Host for execution. Default is 'automatic'",
"enum": [
"AppVeyor",
"AzurePipelines",
"Bamboo",
"Bitbucket",
"Bitrise",
"GitHubActions",
"GitLab",
"Jenkins",
"Rider",
"SpaceAutomation",
"TeamCity",
"Terminal",
"TravisCI",
"VisualStudio",
"VSCode"
]
"$ref": "#/definitions/Host"
},
"NoLogo": {
"type": "boolean",
@@ -62,10 +80,6 @@
"type": "string"
}
},
"ReleaseNotesFilePath": {
"type": "string",
"description": "ReleaseNotesFilePath - To determine the SemanticVersion"
},
"Root": {
"type": "string",
"description": "Root directory during build execution"
@@ -74,71 +88,50 @@
"type": "array",
"description": "List of targets to be skipped. Empty list skips all dependencies",
"items": {
"type": "string",
"enum": [
"Clean",
"Compile",
"CompileSample",
"CreatePackages",
"Default",
"ElectronizeCustomWin7TargetSample",
"ElectronizeGenericTargetSample",
"ElectronizeLinuxTargetSample",
"ElectronizeMacOsTargetSample",
"ElectronizeWindowsTargetSample",
"Package",
"PrePublish",
"Publish",
"PublishPackages",
"PublishPreRelease",
"PublishRelease",
"Restore",
"RunUnitTests"
]
"$ref": "#/definitions/ExecutableTarget"
}
},
"Solution": {
"type": "string",
"description": "Path to a solution file that is automatically loaded"
},
"Target": {
"type": "array",
"description": "List of targets to be invoked. Default is '{default_target}'",
"items": {
"type": "string",
"enum": [
"Clean",
"Compile",
"CompileSample",
"CreatePackages",
"Default",
"ElectronizeCustomWin7TargetSample",
"ElectronizeGenericTargetSample",
"ElectronizeLinuxTargetSample",
"ElectronizeMacOsTargetSample",
"ElectronizeWindowsTargetSample",
"Package",
"PrePublish",
"Publish",
"PublishPackages",
"PublishPreRelease",
"PublishRelease",
"Restore",
"RunUnitTests"
]
"$ref": "#/definitions/ExecutableTarget"
}
},
"Verbosity": {
"type": "string",
"description": "Logging verbosity during build execution. Default is 'Normal'",
"enum": [
"Minimal",
"Normal",
"Quiet",
"Verbose"
]
"$ref": "#/definitions/Verbosity"
}
}
}
}
}
},
"allOf": [
{
"properties": {
"CommonPropsFilePath": {
"type": "string",
"description": "common.props file path - to determine the configured version"
},
"Configuration": {
"type": "string",
"description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)",
"enum": [
"Debug",
"Release"
]
},
"ReleaseNotesFilePath": {
"type": "string",
"description": "ReleaseNotesFilePath - To determine the lates changelog version"
},
"Solution": {
"type": "string",
"description": "Path to a solution file that is automatically loaded"
}
}
},
{
"$ref": "#/definitions/NukeBuild"
}
]
}

View File

@@ -1,4 +1,4 @@
{
"$schema": "./build.schema.json",
"Solution": "src/ElectronNET.sln"
"Solution": "src/ElectronNET.Lean.sln"
}

4
.vscode/launch.json vendored
View File

@@ -10,9 +10,9 @@
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceRoot}/ElectronNET.CLI/bin/Debug/netcoreapp2.0/dotnet-electronize.dll",
"program": "${workspaceRoot}/src/ElectronNET.CLI/bin/Debug/net8.0/dotnet-electronize.dll",
"args": [],
"cwd": "${workspaceRoot}/ElectronNET.CLI",
"cwd": "${workspaceRoot}/src/ElectronNET.CLI",
// For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
"console": "internalConsole",
"stopAtEntry": false,

2
.vscode/tasks.json vendored
View File

@@ -7,7 +7,7 @@
"label": "build",
"type": "shell",
"command": "dotnet",
"args": ["build", "${workspaceRoot}/ElectronNET.CLI/ElectronNET.CLI.csproj"],
"args": ["build", "${workspaceRoot}/src/ElectronNET.CLI/ElectronNET.CLI.csproj"],
"problemMatcher": "$msCompile",
"group": {
"_id": "build",

View File

@@ -1,377 +1,139 @@
# 23.6.2
# 0.4.1
## ElectronNET.API
## ElectronNET.Core
- Fixed handling of `Center` property for windows (#1001)
- Added missing methods on `Cookies` (#1000)
* Fixed escaping of URL (#735) @cosmo0
* Changed `ZoomFactor` type from `int` to `double` (#754) @Yuvix25
# 0.4.0
## ElectronNET.CLI
## ElectronNET.Core
* (none)
- Fixed ElectronSingleInstance handling (#996) @softworkz
- Fixed `PackageId` handling (#993) @softworkz
- Added cross-platform npm restore and check mismatch on publish (#988) @softworkz
## Infrastructure
# 0.3.1
* Changed build system to NUKE #757 @FlorianRappl
* Updated target framework for host project #753 @r-pankevicius
## ElectronNET.Core
# 23.6.1
- Fixed issue transforming the project ID (#989, #990) @softworkz
# 0.3.0
## ElectronNET.CLI
## ElectronNET.Core
* New Feature: Upgrade to .NET 6 support
- Updated infrastructure (#937, #939) @softworkz
- Updated all model classes to Electron API 39.2 (#949) @softworkz
- Fixed output path for `electron-builder` (#942) @softworkz
- Fixed floating point display resolution (#944) @softworkz
- Fixed error in case of missing electron-host-hook (#978)
- Fixed previous API break using exposed `JsonElement` objects (#938) @softworkz
- Fixed and improved several test cases (#962) @softworkz
- Fixed startup of Electron.NET from VS Code Debug Adapter (#952)
- Fixed the `BrowserWindowOptions` (#945) @softworkz
- Fixed example for `AutoMenuHide` to reflect platform capabilities (#982) @markatosi
- Added several migration checks for publishing (#966) @softworkz
- Added more test runners for E2E tests (#950, #951) @agracio
- Added dynamic updates for tray menu (#973) @davidroth
- Added matrix tests with 6 runners and 2 electron version (#948) @softworkz
- Added additional APIs for WebContents (#958) @agracio
- Added documentation for MacOS package publish (#983) @markatosi
- Added sample application for `ElectronHostHook` (#967) @adityashirsatrao007
## ElectronNET.API
# 0.2.0
* New Feature: Native Electron 23.2.0 support, but not all new API features included (we search contributors)
* New Feature: Upgrade to .NET 6 support
* New Feature: Changed Web-Socket .NET Library to [SocketIOClient](https://github.com/doghappy/socket.io-client-csharp)
* Breaking Changes: We removed deprecated API events/methods from ElectronNET.API [(More Details)](https://www.electronjs.org/docs/latest/breaking-changes)
# 13.5.1
## ElectronNET.Core
ElectronNET.CLI:
* New Feature: Using exit code instead of seek for the term 'error' (thanks [TSrgy](https://github.com/TSrgy)) [\#562](https://github.com/ElectronNET/Electron.NET/pull/562)
* Fixed bug: Allow for property overrides to be passed in (thanks [danatcofo](https://github.com/danatcofo)) [\#531](https://github.com/ElectronNET/Electron.NET/pull/531)
Use `/p:propertyName=value` or `/property:propertyName=value` to pass in property overrides. This is equivalent to the `-p:` option documented here: [https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-publish](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-publish)
* Fixed bug: Add ability to pass an argument for "Version" for both the "dotnet publish" and "electron-builder" commands (thanks [tub5](https://github.com/tub5)) [\#546](https://github.com/ElectronNET/Electron.NET/pull/546)
* Fixed bug: Version flag not persisting with the referenced executable (thanks [tub5](https://github.com/tub5)) [\#585](https://github.com/ElectronNET/Electron.NET/pull/585)
* Fixed bug: Changes PublishSingleFile default to false for NET5 compatibility (thanks [cristiangiagante](https://github.com/cristiangiagante)) [\#570](https://github.com/ElectronNET/Electron.NET/pull/570)
ElectronNET.API:
* New Feature: Native Electron 13.1.5 support, but not all new features (we search contributors)
* Breaking API Changes (from native Electron 13.1.5):
- `Shell.MoveItemToTrashAsync` renamed with `Shell.TrashItemAsync`
- The deprecated extension APIs have been removed: `BrowserWindow.GetAllExtensionsAsync()`, `BrowserWindow.RemoveExtension()`, `BrowserWindow.AddExtensionAsync()`. Use the session APIs instead: `Session.GetAllExtensionsAsync()`, `Session.RemoveExtension()`, `Session.LoadExtensionAsync()`.
* New Feature: singleInstance handle command line arguments [\#520](https://github.com/ElectronNET/Electron.NET/issues/520)
* New Feature: Add WebContents [insertCSS](https://www.electronjs.org/docs/api/web-contents#contentsinsertcsscss-options) functionality (thanks [nfichter](https://github.com/nfichter)) [\#559](https://github.com/ElectronNET/Electron.NET/pull/559)
* New Feature: Allow IpcMain to send IPC messages to BrowserViews (thanks [nfichter](https://github.com/nfichter)) [\#560](https://github.com/ElectronNET/Electron.NET/pull/560)
* New Feature: Add support for proxies that require basic username/password authentication (thanks [nfichter](https://github.com/nfichter)) [\#561](https://github.com/ElectronNET/Electron.NET/pull/561)
* New Feature: Add PostData to LoadURLOptions to allow http-posts in LoadURL calls (thanks [Funkrusha](https://github.com/Funkrusha)) [\#547](https://github.com/ElectronNET/Electron.NET/pull/547)
* Fixed bug: Fix splash screen interaction causing crashes, ghost dragging, and resizable behavior #540 (thanks [MiniguyBrendan](https://github.com/MiniguyBrendan)) [\#540](https://github.com/ElectronNET/Electron.NET/pull/540)
* Fixed bug: Vibrancy serialization fix (thanks [tantumalice](https://github.com/tantumalice)) [\#573](https://github.com/ElectronNET/Electron.NET/pull/573)
- Updated dependencies (#930) @softworkz
- Updated integration tests (#931) @softworkz
- Updated `ElectronNET.Host` (#935) @softworkz
- Removed transition period specific build configuration (#928) @softworkz
- Added `IsRunningBlazor` option to `BrowserWindowOptions` (#926)
- Added platform support attributes (#929) @softworkz
# 11.5.1
# 0.1.0
ElectronNET.CLI:
## ElectronNET.Core
* New Feature: Added new build and start commandline options for single exe (thanks [nathanwienand](https://github.com/nathanwienand)) [\#506](https://github.com/ElectronNET/Electron.NET/pull/506)
* New Feature: Set a description of the app in `electron.manifest.json` (thanks [BurtsevC](https://github.com/BurtsevC)) [\#433](https://github.com/ElectronNET/Electron.NET/pull/433)
* New Feature: Set a target for the start command (thanks [gabecook](https://github.com/gabecook)) [\#463](https://github.com/ElectronNET/Electron.NET/pull/463)
* New Feature: `electronize init` support for F# projects (thanks [kojo12228](https://github.com/kojo12228)) [\#457](https://github.com/ElectronNET/Electron.NET/pull/457)
* New Feature: Linux support for the buildAll.sh (thanks [duncanawoods](https://github.com/duncanawoods)) [\#465](https://github.com/ElectronNET/Electron.NET/pull/465)
* Fixed bug: ERR_UNKNOWN_URL_SCHEME by intercepting file:// protocol (thanks [duncanawoods](https://github.com/duncanawoods)) [\#467](https://github.com/ElectronNET/Electron.NET/pull/467)
- Updated `PrintToPDFOptions` to also allow specifying the `PageSize` with an object (#769)
- Updated splashscreen image to have 0 margin (#622)
- Updated the IPC API w.r.t. naming and consistency (#905) @agracio
- Updated the IPC bridge w.r.t. synchronization and thread-safety (#918) @agracio
- Updated serialization to use `System.Text.Json` replacing `Newtonsoft.Json` (#917) @Denny09310
- Fixed parameter handling for the `sendToIpcRenderer` function (#922) @softworkz
- Fixed synchronization on removing event handlers (#921) @softworkz
- Fixed creation of windows with `contextIsolation` enabled (#906) @NimbusFox
- Fixed single instance behavior using the `ElectronSingleInstance` property (#901)
- Fixed potential race conditions (#908) @softworkz
- Added option to use `ElectronSplashScreen` with an HTML file (#799)
- Added option to provide floating point value as aspect ratios with `SetAspectRatio` (#793)
- Added option to provide `TitleBarOverlay` as an object (#911) @Denny09310
- Added `TitleBarOverlay` property to `BrowserWindowOptions` (#909)
- Added `RoundedCorners` property to `BrowserWindowOptions`
- Added integration tests and robustness checks (#913) @softworkz
- Added .NET 10 as an explicit target
ElectronNET.API:
# 0.0.18
* New Feature: Native Electron 11.1.1 support, but not all new features (we search contributors)
* Breaking API Changes (from native Electron 11.0): - Removed: BrowserView.{destroy, fromId, fromWebContents, getAllViews} and id property of BrowserView
* New Feature: Upgrade to .NET 5 (thanks [scottkuhl](https://github.com/scottkuhl)) [\#509](https://github.com/ElectronNET/Electron.NET/pull/509)
* New Feature: Extension Method for adding the Electron static class members to the standard MS DI Containers, this is a QOL issue only. `services.AddElectron()` (thanks [danatcofo](https://github.com/danatcofo )) [\#528](https://github.com/ElectronNET/Electron.NET/pull/528)
* New Feature: SetMenu completed for the Dock (MacOS) (thanks [danatcofo](https://github.com/danatcofo )) [\#528](https://github.com/ElectronNET/Electron.NET/pull/528)
Example for the Dock Menu
`Electron.Dock.SetMenu(new [] {
new MenuItem {
Label = "Dock Menu Item",
Click = () => {
// do something
}
},
});`
Example for consuming the activate event (MacOs only)
## ElectronNET.Core
`Electron.App.On("activate", obj => {
var hasWindows = (bool)obj;
// do something
});`
* New Feature: On and Once implementations for the App and Tray to cover the plethora of events that are not mapped explicitly in those two modules. (thanks [danatcofo](https://github.com/danatcofo )) [\#528](https://github.com/ElectronNET/Electron.NET/pull/528)
* New Feature: Adding the `EnableRemoteModule` property to the WebPreferences object. As of Electron 10, this property defaulted to false and without it exposed you can't use the remote module within a window. (thanks [danatcofo](https://github.com/danatcofo )) [\#528](https://github.com/ElectronNET/Electron.NET/pull/528)
* New Feature: Adding a configurable default electron port. (thanks [aarong-av](https://github.com/aarong-av)) [\#505](https://github.com/ElectronNET/Electron.NET/pull/505)
* New Feature: Added support for launching the application with a file on MacOS (thanks [dlitty](https://github.com/dlitty)) [\#478](https://github.com/ElectronNET/Electron.NET/pull/478)
* Improved: Avoid Blocking Calls in App and AutoUpdater (thanks [freosc](https://github.com/freosc)) [\#474](https://github.com/ElectronNET/Electron.NET/pull/474)
* Fixed bug: Maintain references between socket.io connection events (thanks [danatcofo](https://github.com/danatcofo )) [\#468](https://github.com/ElectronNET/Electron.NET/pull/486)
* Fixed bug: Set default WebPreferences.DefaultFontSize (thanks [duncanawoods](https://github.com/duncanawoods)) [\#468](https://github.com/ElectronNET/Electron.NET/pull/468)
### Highlights
# 9.31.2
- **Complete MSBuild Integration**: Eliminated CLI tool dependency, moved all build processes to MSBuild with deep Visual Studio integration
- **Modernized Architecture**: Restructured process lifecycle with .NET launching first and running Electron as child process for better control and reliability
- **Cross-Platform Development**: Build and debug Linux applications directly from Windows Visual Studio via WSL integration
- **Flexible Electron Versioning**: Removed version lock-in, users can now select any Electron version with build-time validation
- **Enhanced Debugging Experience**: ASP.NET-first debugging with Hot Reload support and improved process termination handling
- **Console App Support**: No longer requires ASP.NET - now works with simple console applications for file system or remote server HTML/JS
* Electron-Builder fixed for Windows builds.
### Build System & Project Structure
# 9.31.1
- Eliminated electron.manifest.json configuration file, replaced with MSBuild project properties
- Introduced new package structure: ElectronNET.Core (main package), ElectronNET.Core.Api (API definitions), ElectronNET.Core.AspNet (ASP.NET integration)
- Added Runtime Identifier (RID) selection as part of project configuration
- Restructured build folder layout to use standard .NET format (bin\net8.0\win-x64) instead of bin\Desktop
- Implemented incremental build support for Electron assets to improve build performance
- Added custom MSBuild tasks for Electron-specific build operations
ElectronNET.CLI:
### Development Experience
* New Feature: Added config parameter (thanks [konstantingross](https://github.com/konstantingross)) [\#409](https://github.com/ElectronNET/Electron.NET/pull/409)
* New Feature: Set the configuration environment with the electron.manifest.json file.
* Fixed bug: Custom user path removed and replaced by the correct directory with VS macro (When ElectronNET.CLI is the Startup Project, press F5 (Debug) and the ElectronNET.WebApp starts correctly without error!) (thanks [konstantingross](https://github.com/konstantingross)) [\#409](https://github.com/ElectronNET/Electron.NET/pull/409)
ElectronNET.API:
* New Feature: Native Electron 9.0.3 support, but not all new features (we search contributors)
* New Feature: PowerMonitor API Support (thanks [gustavo-lara-molina](https://github.com/gustavo-lara-molina)) [\#399](https://github.com/ElectronNET/Electron.NET/pull/399) [\#423](https://github.com/ElectronNET/Electron.NET/pull/423)
* New Feature: NativeTheme API Support (thanks [konstantingross](https://github.com/konstantingross)) [\#402](https://github.com/ElectronNET/Electron.NET/pull/402)
* New Feature: Cookie API Support (thanks [freosc](https://github.com/freosc)) [\#413](https://github.com/ElectronNET/Electron.NET/pull/413)
* Changed Feature: Removed dock methods from App API and moved to Dock API (thanks [konstantingross](https://github.com/konstantingross)) [\#422](https://github.com/ElectronNET/Electron.NET/pull/422)
* App-Api Enhancement: MenuItems with Submenus need an submenu type workaround [\#412](https://github.com/ElectronNET/Electron.NET/issues/412)
* App-Api Enhancement: Added UserAgentFallback (thanks [Mandrakia](https://github.com/Mandrakia)) [\#406](https://github.com/ElectronNET/Electron.NET/pull/406)
* App-Api Enhancement: Summaries rewritten, new App.IsReady / App.HasSingleInstanceLock property, App.Ready event, App.Focus with force parameter method, many parameters changes (thanks [konstantingross](https://github.com/konstantingross)) [\#415](https://github.com/ElectronNET/Electron.NET/pull/415) [\#422](https://github.com/ElectronNET/Electron.NET/pull/422)
* App-Api Enhancement: New App.IsReady property and App.Ready event (thanks [konstantingross](https://github.com/konstantingross)) [\#415](https://github.com/ElectronNET/Electron.NET/pull/415)
* Shell-Api Enhancement: API fixes for Electron 9.0.0 / Added missing parameters / Summaries rewritten (thanks [konstantingross](https://github.com/konstantingross)) [\#417](https://github.com/ElectronNET/Electron.NET/pull/417) [\#418](https://github.com/ElectronNET/Electron.NET/pull/418)
* Notification-Api Enhancement: Added missing properties in Notifications (thanks [konstantingross](https://github.com/konstantingross)) [\#410](https://github.com/ElectronNET/Electron.NET/pull/410)
* BrowserWindows-Api Enhancement: Add missing API call for SetProgressBar options (thanks [konstantingross](https://github.com/konstantingross)) [\#416](https://github.com/ElectronNET/Electron.NET/pull/416)
* BrowserWindow Enhancement: Add BrowserWindow.GetNativeWindowHandle() (thanks [kdlslyv](https://github.com/kdlslyv)) [\#429](https://github.com/ElectronNET/Electron.NET/pull/429)
* HostHook-Api Enhancement: HostHook.CallAsync should use TaskCompletionSource.SetException instead of throwing exception (thanks [Fre V](https://github.com/freosc)) [\#430](https://github.com/ElectronNET/Electron.NET/pull/430)
* MacOS Enhancement: Application exit logic (thanks [dafergu2](https://github.com/dafergu2)) [\#405](https://github.com/ElectronNET/Electron.NET/pull/405)
* Fixed bug: ElectronNET.API.Entities.WebPreferences.ContextIsolation [DefaultValue(true)] [\#411](https://github.com/ElectronNET/Electron.NET/issues/411)
ElectronNET.WebApp (internal use):
* Improvement debugging and testing new API calls (without install ElectronNET.CLI) (thanks [konstantingross](https://github.com/konstantingross)) [\#425](https://github.com/ElectronNET/Electron.NET/pull/425)
* Fixed bug: Cannot find modules in ElectronHostHook (thanks [konstantingross](https://github.com/konstantingross)) [\#425](https://github.com/ElectronNET/Electron.NET/pull/425)
Thank you for donation [Phil Seeman](https://github.com/mpnow) ❤
# 8.31.2
ElectronNET.CLI:
* New Feature: Deactivate PublishReadyToRun for build or start [\#395](https://github.com/ElectronNET/Electron.NET/issues/395)
`electronize build /target win /PublishReadyToRun false`
`electronize start /PublishReadyToRun false`
* Fixed bug: Application window doesn't open after packaging [\#387](https://github.com/ElectronNET/Electron.NET/issues/387)
ElectronNET.API:
* New Feature: NativeImage Support (thanks [ThrDev](https://github.com/ThrDev)) [\#394](https://github.com/ElectronNET/Electron.NET/pull/394)
* New Feature: Update menu items for context menu and system tray on-the-fly. [\#270](https://github.com/ElectronNET/Electron.NET/pull/270)
# 8.31.1
ElectronNET.CLI:
* New Feature: Set a name and author of the app in `electron.manifest.json` [\#348](https://github.com/ElectronNET/Electron.NET/issues/348#issuecomment-615977950) [\#310](https://github.com/ElectronNET/Electron.NET/issues/310#issuecomment-617361086)
* New Feature: Live reload (thanks [syedadeel2](https://github.com/syedadeel2)) [\#390](https://github.com/ElectronNET/Electron.NET/pull/390)
`electronize start /watch`
* New Feature: Every new window will created with an clear cache [\#273](https://github.com/ElectronNET/Electron.NET/issues/273)
`electronize start /clear-cache`
ElectronNET.API:
* New Feature: Native Electron 8.2.3 support, but not all new features (we search contributors)
* New Feature: We incease the startup time for ~25-36% [\#356](https://github.com/ElectronNET/Electron.NET/issues/356)
* New Feature: Added print capability (thanks [x-xx-o](https://github.com/x-xx-o)) [\#355](https://github.com/ElectronNET/Electron.NET/pull/355)
* New Feature: BrowserView API [\#371](https://github.com/ElectronNET/Electron.NET/issues/371)
* Changed App.GetNameAsync and App.SetNameAsync to the App.Name Property [\#350](https://github.com/ElectronNET/Electron.NET/issues/350)
* Fixed bug: Splash Screen disappearing on click [\#357](https://github.com/ElectronNET/Electron.NET/issues/357)
* Fixed bug: Start MenuRole enum at 1 (thanks [jjuback](https://github.com/jjuback)) [\#369](https://github.com/ElectronNET/Electron.NET/pull/369)
* Fixed bug: BridgeConnector not connected (spam console) [\#347](https://github.com/ElectronNET/Electron.NET/issues/347)
* Fixed bug: BrowserWindowOptions is not setting Width and Height properly [\#373](https://github.com/ElectronNET/Electron.NET/issues/373)
* Fixed bug: IpcMain.Once(string) is not one time use, is not removing listener [\#366](https://github.com/ElectronNET/Electron.NET/issues/366)
* Fixed bug: IpcMain.RemoveAllListeners(string) is not removing the listeners [\#365](https://github.com/ElectronNET/Electron.NET/issues/365)
* Fixed bug: GetLoginItemSettingsAsync does not work [\#352](https://github.com/ElectronNET/Electron.NET/issues/352)
* Fixed bug: Using OnReadyToShow to display the main window in Blazor does not seem to work with Show set to false [\#361](https://github.com/ElectronNET/Electron.NET/issues/361)
* Fixed bug: Unable to disable WebSecurity along with NodeIntegration enabled [\#389](https://github.com/ElectronNET/Electron.NET/issues/389)
# 7.30.2
ElectronNET.CLI:
* New Feature: Different manifest file support [\#340](https://github.com/ElectronNET/Electron.NET/issues/340)
* Create a additional manifest file: `electronize init /manifest test`
* Start the app with your additional manifest file: `electronize start /manifest electron.manifest.test.json`
* Build the app with your additional manifest file: `electronize build /target win /manifest electron.manifest.test.json`.
* New Feature: Command Line support [\#337](https://github.com/ElectronNET/Electron.NET/issues/337)
* You can start the app with: `electronize start /args --dog=woof --test=true`
* Or as binary: `myapp.exe /args --dog=woof --test=true`
* Fixed bug: Start process with listen port 8000 error. [\#308](https://github.com/ElectronNET/Electron.NET/issues/308) (thanks [thecodejedi](https://github.com/thecodejedi))
* Fixed bug: `electronize build` with no arguments would throw a `KeyNotFoundException`. (thanks [jamiebrynes7](https://github.com/jamiebrynes7))
ElectronNET.API:
* New Feature: Electron 7.1.2 support, but not all new features (we search contributors) [\#341](https://github.com/ElectronNET/Electron.NET/issues/341)
* New Feature: Electron.App.CommandLine API [\#337](https://github.com/ElectronNET/Electron.NET/issues/337)
* New Feature: Support of BrowserWindow.AddExtension, BrowserWindow.RemoveExtension, BrowserWindow.GetExtensions (thanks [Daddoon](https://github.com/Daddoon))
Thank you for donation [robertmclaws](https://github.com/robertmclaws) ❤
# 5.30.1
ElectronNET.CLI:
* Move to .NET Core 3.0
* Use npm npx instead of global installations (thanks [jimbuck](https://github.com/jimbuck))
ElectronNET.API:
* Move to .NET Core 3.0
* New Feature: Add BrowserWindow.RemoveMenu() (thanks [hack2root](https://github.com/hack2root))
Thanks to [MaherJendoubi](https://github.com/MaherJendoubi), [kant2002](https://github.com/kant2002), [raz-canva](https://github.com/raz-canva) and [Daddoon](https://github.com/Daddoon) to give .NET Core 3.0 feedback!
# 5.22.14
ElectronNET.CLI:
* Fixed bug: Build fails with latest electron-builder version [\#288](https://github.com/ElectronNET/Electron.NET/issues/288)
ElectronNET.API:
* New Feature: Full support for Auto Updater [(Based on electron-updater - Version 4.0.6)](https://www.electron.build/auto-update)
* New Feature: Support for set a custom static Port to ASP.NET Backend [\#155](https://github.com/ElectronNET/Electron.NET/issues/155)
* Fixed bug: Electron tray icon TypeError ([Electron original issue](https://github.com/electron/electron/issues/7657)) (thanks [Tum4ik](https://github.com/Tum4ik))
* Fixed bug: Wrong tray icon path in the application built via `electronize build` command (thanks [Tum4ik](https://github.com/Tum4ik))
* Fixed bug: fix async issue where same port is considered open [\#261](https://github.com/ElectronNET/Electron.NET/issues/261) (thanks [netpoetica](https://github.com/netpoetica))
ElectronNET.WebApp:
* Fixed usage of the `Electron.Tray.Show` according fixed bugs in the ElectronNET.CLI (thanks [Tum4ik](https://github.com/Tum4ik))
# 5.22.13
ElectronNET.API:
* Fixed bug: Menu Item visibility [\#257](https://github.com/ElectronNET/Electron.NET/issues/257)
* Fixed bug: electron.manifest.json - singleInstance not working [\#258](https://github.com/ElectronNET/Electron.NET/issues/258)
* Fixed security issue: ASP.NET Core process is now bound to 127.0.0.1 instead of the broader localhost [\#258](https://github.com/ElectronNET/Electron.NET/pull/266)
# 5.22.12
ElectronNET.CLI:
* New Feature: Changed from **electron packager** to [**electron builder**](https://www.electron.build/)
* New Feature: 'add hosthook' command for add a ElectronHostHook-Directory
* Fixed bug: 'Unexpected firewall warnings' [\#181](https://github.com/ElectronNET/Electron.NET/issues/181)
* Fixed bug: 'found 8 vulnerabilities (1 low, 5 moderate, 2 high)' [\#199](https://github.com/ElectronNET/Electron.NET/pull/199)
* Merged pull request: Call electronize from the Path instead of via dotnet in launchSettings.json [\#243](https://github.com/ElectronNET/Electron.NET/pull/243) (thanks [grbd](https://github.com/grbd))
ElectronNET.API:
* New Feature: Electron 5.0.1 support, but not all new features
* New Feature: Auto Updater [(Based on electron-updater)](https://www.electron.build/auto-update)
* New Feature: Splashscreen-Support
* New Feature: HostHook-API for execute own TypeScript/JavaScript code on native Electron Main-Process
* New Feature: Session-API functions
* Fixed bug: Node process running after stopping app [\#96](https://github.com/ElectronNET/Electron.NET/issues/96)
* Fixed bug: 'X and Y options to not work on Windows 10' [\#193](https://github.com/ElectronNET/Electron.NET/issues/193)
* Fixed bug: Unable to clear cache [\#66](https://github.com/ElectronNET/Electron.NET/issues/66)
* Merged pull request: Fix BrowserWindow::SetMenu [\#231](https://github.com/ElectronNET/Electron.NET/pull/231) thanks (thanks [CodeKenpachi](https://github.com/CodeKenpachi))
* Merged pull request: FIX application hangs after socket reconnect [\#233](https://github.com/ElectronNET/Electron.NET/pull/233) (thanks [pedromrpinto](https://github.com/pedromrpinto))
* Merged pull request: Reduce chance of detecting false positives when scanning subprocesses for errors. [\#236](https://github.com/ElectronNET/Electron.NET/pull/236) (thanks [BorisTheBrave](https://github.com/BorisTheBrave))
* Merged pull request: Updates the C# API to accept floating point as in JS. [\#240](https://github.com/ElectronNET/Electron.NET/pull/240) (thanks [BorisTheBrave](https://github.com/BorisTheBrave))
* Merged pull request: buildReleaseNuGetPackages should leave you in the same directory you … [\#241](https://github.com/ElectronNET/Electron.NET/pull/241) (thanks [BorisTheBrave](https://github.com/BorisTheBrave))
ElectronNET.WebApp:
* Implemented a sample for the new HostHook-API
* Fixed bug: 'Electron.NET API Demo: unable to copy code?' [\#247](https://github.com/ElectronNET/Electron.NET/issues/247)
# 0.0.11
ElectronNET.CLI:
* Invoke 'npm install' without --prod flag to install needed devDependencies as well.
* Enable SourceLink
* NuGet Package License Information updated (deprecation of licenseUrl)
ElectronNET.API:
* Documentation added for WebContents.GetUrl()
* Enable SourceLink
* NuGet Package License Information updated (deprecation of licenseUrl)
# 0.0.10
ElectronNET.API:
* manifestJsonFilePath fixed (thanks @smack0007)
* Use Electron release 3.0.0 and updated packages (thanks @deinok)
* fixes for Socket interaction (thanks @mojinxun)
* Fixing SingleInstances (thanks @yaofeng)
* Enhance WebContent.GetUrl (thanks @ru-sh)
ElectronNET.CLI:
* Show Resultcode for better debugging when using Build/Start Command
* ElectronNET.CLI is now a global dotnet tool
# 0.0.9
ElectronNET.API:
* Better Async handling - thanks @danielmarbach
ElectronNET.CLI:
* More options on the 'build' command, e.g. for a 32bit debug build with electron prune: build /target custom win7-x86;win32 /dotnet-configuration Debug /electron-arch ia32 /electron-params "--prune=true "
* .NET Core project is now built with Release configuration but can be adjusted with the new params.
* Be aware: "Breaking" (but because of the alpha status of this project, we won't use SemVer)
# 0.0.8
This version was skipped because we unfortunately released a pre-version of this on NuGet.
# 0.0.7
ElectronNET.CLI:
* Fixed electronize start for macos/linux - thanks @yamachu
* Skip NPM install on start when node_modules directory already exists
# 0.0.6
ElectronNET.CLI:
* nuget packages are now release bits and have the correct assembly version
* Version command
* better devCleanup.cmd
* Better Platform Support Issue - thanks to @Petermarcu
* Start Command should now work on OSX/Linux - thanks to @r105m
ElectronNET.API:
* Thread-Safe methods - thanks to @yeskunall
# 0.0.5
ElectronNET.API:
* The last nuget package didn't contain the actual webpreferences settings with defaults - hopefully now.
# 0.0.4
ElectronNET.CLI:
* dotnet electronize start fixed
ElectronNET.API:
* WebPreferences settings with default values
# 0.0.3
ElectronNET.CLI:
* Init with Debug profile
* Build for all platforms (well... for newest OSX/Linux/Windows)
ElectronNET.API:
* Moar XML documentation
* Hybrid support (e.g. running as normal website and electron app)
* Event bugfixing
# 0.0.2
ElectronNET.CLI:
* Added Init to Help page
* Added XML documentation to NuGet output
* Maybe fixed for https://github.com/GregorBiswanger/Electron.NET/issues/2
ElectronNET.API:
* Add XML documentation to NuGet output
* Implemented Notification-, Dialog- & Tray-API
# 0.0.1
* init everything and basic functionality
- Implemented unpackaged run-mode for development using regular .NET builds with unpackaged Electron configuration
- Added support for building Linux packages on Windows via WSL integration
- Enabled running and debugging Linux application outputs on Windows through WSL
- Integrated TypeScript compilation with ASP.NET tooling for consistent builds
- Added process orchestration supporting 8 different launch scenarios (packaged/unpackaged × console/ASP.NET × dotnet-first/electron-first)
### Debugging & Runtime
- Dramatically improved debugging experience with ASP.NET-first launch mode
- Added Hot Reload support for ASP.NET code during development
- Implemented proper process termination handling for all exit scenarios
- Minimized startup times through optimized build and launch procedures
### Technical Improvements
- Enhanced splash screen handling with automatic path resolution
- Improved ElectronHostHook integration as proper npm package dependency
- Updated to latest TypeScript version with ESLint configuration
- Added support for custom main.js files in projects
- Implemented version management through common.props file
- Added build-time Electron version compatibility validation
### Package & Distribution
- Integrated MSBuild publishing mechanisms for creating Electron packages
- Added folder publishing support with improved parameter handling
- Implemented automated package.json generation from MSBuild properties
- Added GitHub release automation with proper versioning
- Reduced package sizes by eliminating unnecessary TypeScript dependencies
### Migration & Compatibility
- Maintained backward compatibility for existing ElectronHostHook implementations
- Removed ASP.NET requirement: Now works with simple console applications for file system or remote server HTML/JS scenarios
- Added support for both console and ASP.NET Core application types
- Preserved all existing Electron API functionality while modernizing architecture
- Added migration path for existing projects through updated package structure
This represents a comprehensive modernization of Electron.NET, addressing the major pain points around debugging, build complexity, and platform limitations while maintaining full API compatibility.

View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2017-2023 Gregor Biswanger, Robert Mühsig
Copyright (c) 2017-2025 Gregor Biswanger, Robert Mühsig, Florian Rappl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<config>
<add key="repositoryPath" value="artifacts" />
</config>
<packageSources>
<clear />
<add key="LocalDev" value="artifacts" />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</packageSources>
</packageSources>
</configuration>

378
README.md
View File

@@ -2,191 +2,186 @@
[![donate](https://img.shields.io/badge/Donate-Donorbox-green.svg)](https://donorbox.org/electron-net) [![Gitter](https://badges.gitter.im/ElectronNET/community.svg)](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Build status](https://github.com/ElectronNET/Electron.NET/actions/workflows/ci.yml/badge.svg)](https://github.com/ElectronNET/Electron.NET/actions/workflows/ci.yml)
Build cross platform desktop apps with .NET 6 and Blazor, ASP.NET Core (Razor Pages, MVC).
# Electron.NET Core is here!
Electron.NET is a __wrapper__ around a native Electron application with an embedded ASP.NET Core application. Via our Electron.NET IPC bridge we can invoke Electron APIs from .NET.
## A Complete Transformation
The CLI extensions hosts our toolset to build and start Electron.NET applications.
`ElectronNET.Core` represents a fundamental modernization of Electron.NET, addressing years of accumulated pain points while preserving full API compatibility. This isn't just an update — it's a complete rethinking of how .NET developers build and debug cross-platform desktop applications with Electron.
## Wait - you host a .NET Core app inside Electron? Why?
Read more: [**What's New in `ElectronNET.Core`**](https://github.com/ElectronNET/Electron.NET/wiki/What's-New)
Well... there are lots of different approaches how to get a X-plat desktop app running. We thought it would be nice for .NET devs to use the ASP.NET Core environment and just embed it inside a pretty robust X-plat enviroment called Electron. Porting Electron to .NET is not a goal of this project, at least we don't have any clue how to do it. We just combine ASP.NET Core & Electron.
Build cross platform desktop applications with .NET 6/8/10 - from console apps to ASP.NET Core (Razor Pages, MVC) to Blazor.
## Wait - how does that work exactly?
Well... there are lots of different approaches how to get a X-plat desktop app running. Electron.NET provides a range of ways to build .NET-based solutions using Electron at the side of presentation.
While the classic Electron.NET setup (using an ASP.NET host run by the Electron side) is still the primary way, there's more flexibility now. Both .NET and Electron are now able to launch the other for better lifetime management, and when you don't need a local web server (like when running content from files or remote servers), you can drop the ASP.NET stack altogether and go with a lightweight console app instead.
## 📦 NuGet
[![NuGet](https://img.shields.io/nuget/v/ElectronNET.API.svg?style=flat-square) ElectronNET.API ](https://www.nuget.org/packages/ElectronNET.API/) | [![NuGet](https://img.shields.io/nuget/v/ElectronNET.CLI.svg?style=flat-square) ElectronNET.CLI](https://www.nuget.org/packages/ElectronNET.CLI/)
* ElectronNET.Core: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.API/)
* ElectronNET.Core.API: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.API.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.API/)
* ElectronNET.Core.AspNet: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.AspNet.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.AspNet/)
## 🛠 Requirements to Run
The current Electron.NET CLI builds Windows/macOS/Linux binaries. Our API uses .NET 6, so our minimum base OS is the same as [.NET 6](https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md).
You should have installed:
Also you should have installed:
* .NET 6/8 or later.
* The minimum base OS is the same as [.NET 6](https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md) / [.NET 8](https://github.com/dotnet/core/blob/main/release-notes/8.0/supported-os.md).
* Node.JS using at least [Version 22.x](https://nodejs.org).
* npm [contained in nodejs (at least Version 16.17.1)](https://nodejs.org)
## 👩‍🏫 Usage with ASP.NET
## 💬 Community
[![Gitter](https://badges.gitter.im/ElectronNET/community.svg)](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
Besides the chat on Gitter and the issues [discussed here](https://github.com/ElectronNET/Electron.NET/issues) you can also use [StackOverflow](https://stackoverflow.com/questions/tagged/electron.net) with the tag `electron.net`.
If you want to sponsor the further maintenance and development of this project [see the donate section](#🙏-donate).
## 👩‍🏫 Usage
To activate and communicate with the "native" (sort of native...) Electron API include the [ElectronNET.API NuGet package](https://www.nuget.org/packages/ElectronNET.API/) in your ASP.NET Core app.
- Create a new ASP.NET Core project
- Install the following two NuGet packages:
```ps1
PM> Install-Package ElectronNET.API
dotnet add package ElectronNET.Core
dotnet add package ElectronNET.Core.AspNet
```
## Setup Using Minimal-API
### Classic ASP.NET Core
You start Electron.NET up with an `UseElectron` WebHostBuilder-Extension and open the Electron Window:
#### Enable Electron.NET on Startup
### Program.cs
To do so, use the `UseElectron` extension method on a `WebApplicationBuilder`, an `IWebHostBuilder` or any descendants.
> [!NOTE]
> New in Electron.NET Core is that you provide a callback method as an argument to `UseElectron()`, which ensures that you get to know the right moment to set up your application UI.
#### Program.cs
```csharp
using ElectronNET.API;
using ElectronNET.API.Entities;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseElectron(args);
// Is optional, but you can use the Electron.NET API-Classes directly with DI (relevant if you wont more encoupled code)
builder.Services.AddElectron();
var app = builder.Build();
...
await app.StartAsync();
// Open the Electron-Window here
await Electron.WindowManager.CreateWindowAsync();
app.WaitForShutdown();
```
## Setup using Normal-API
### Program.cs
You start Electron.NET up with an `UseElectron` WebHostBuilder-Extension.
```csharp
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseElectron(args);
webBuilder.UseStartup<Startup>();
});
```
### Startup.cs
Open the Electron Window in the *Startup.cs* file:
```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
public static void Main(string[] args)
{
//...
WebHost.CreateDefaultBuilder(args)
.UseElectron(args, ElectronAppReady)
.UseStartup<Startup>()
.Build()
.Run();
}
Electron.WindowManager.CreateWindowAsync();
public static async Task ElectronAppReady()
{
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions { Show = false });
browserWindow.OnReadyToShow += () => browserWindow.Show();
}
```
## 🚀 Starting the Application
### Minimal API Example
To start the application make sure you have installed the "[ElectronNET.CLI](https://www.nuget.org/packages/ElectronNET.CLI/)" packages as global tool:
For a minimal API you can use:
```sh
dotnet tool install ElectronNET.CLI -g
```csharp
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();
```
At the first time, you need an Electron.NET project initialization. Type the following command in your ASP.NET Core folder:
### Blazor
```sh
electronize init
For a project with Blazor you can use:
```cs
using ElectronNET.API;
using ElectronNET.API.Entities;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddRazorComponents()
.AddInteractiveWebAssemblyComponents();
builder.Services.AddElectron(); // <-- might be useful to set up DI
builder.UseElectron(args, async () =>
{
var options = new BrowserWindowOptions {
Show = false,
IsRunningBlazor = true, // <-- crucial
};
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux())
options.AutoHideMenuBar = true;
var browserWindow = await Electron.WindowManager.CreateWindowAsync(options);
browserWindow.OnReadyToShow += () => browserWindow.Show();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents<BlazorApp.Components.App>()
.AddInteractiveWebAssemblyRenderMode();
app.Run();
```
* Now a electronnet.manifest.json should appear in your ASP.NET Core project
* Now run the following:
The `IsRunningBlazor` option makes sure to set up the renderer in a way that Blazor can just run without any interference. This includes things such as HMR for development.
```sh
electronize start
```
## 🚀 Starting and Debugging the Application
### Note
> Only the first `electronize start` is slow. The next will go on faster.
## 🔭 Develop Electron.NET apps using a file watcher
The file watcher is included with version 8.31.1 of Electron.NET. For example, a file change can trigger compilation, test execution, or deployment. The Electron.NET window will automatically refresh and new code changes will be visible more quickly. The following Electron.NET CLI command is required:
```sh
electronize start /watch
```
### Note
> Only the first `electronize start` is slow. The next will go on faster.
## 🐞 Debugging the Application
Start your Electron.NET application with the Electron.NET CLI command. In Visual Studio attach to your running application instance. Go in the __Debug__ Menu and click on __Attach to Process...__. Sort by your projectname on the right and select it on the list.
Just press `F5` in Visual Studio or use dotnet for debugging.
## 📔 Usage of the Electron API
A complete documentation will follow. Until then take a look in the source code of the sample application:
[Electron.NET API Demos](https://github.com/ElectronNET/electron.net-api-demos)
Complete documentation is available on the Wiki.
In this YouTube video, we show you how you can create a new project, use the Electron.NET API, debug a application and build an executable desktop app for Windows: [Electron.NET - Getting Started](https://www.youtube.com/watch?v=nuM6AojRFHk)
## ⛏ Building Release Artifacts
Here you need the Electron.NET CLI as well. Type the following command in your ASP.NET Core folder:
```sh
electronize build /target win
```
There are additional platforms available:
```sh
electronize build /target win
electronize build /target osx
electronize build /target linux
```
Those three "default" targets will produce x64 packages for those platforms.
For certain NuGet packages or certain scenarios you may want to build a pure x86 application. To support those things you can define the desired [.NET Core runtime](https://docs.microsoft.com/en-us/dotnet/core/rid-catalog), the [electron platform](https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#platform) and [electron architecture](https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#arch) like this:
```sh
electronize build /target custom "win7-x86;win32" /electron-arch ia32
```
The end result should be an electron app under your __/bin/desktop__ folder.
### Note
> macOS builds can't be created on Windows machines because they require symlinks that aren't supported on Windows (per [this Electron issue](https://github.com/electron-userland/electron-packager/issues/71)). macOS builds can be produced on either Linux or macOS machines.
## 🔄 Update
After an update to the latest Electron.API package, an update to the latest Electron.CLI is always required. In addition, always update the CLI via NuGet:
```sh
dotnet tool update ElectronNET.CLI -g
```
> [!NOTE]
> The video hasn't been updated for the changes in ElectronNET.Core, so it is partially outdated.
## 👨‍💻 Authors
* **[Gregor Biswanger](https://github.com/GregorBiswanger)** - (Microsoft MVP, Intel Black Belt and Intel Software Innovator) is a freelance lecturer, consultant, trainer, author and speaker. He is a consultant for large and medium-sized companies, organizations and agencies for software architecture, web- and cross-platform development. You can find Gregor often on the road attending or speaking at international conferences. - [Cross-Platform-Blog](http://www.cross-platform-blog.com) - Twitter [@BFreakout](https://www.twitter.com/BFreakout)
* **[Dr. Florian Rappl](https://github.com/FlorianRappl)** - Software Developer - from Munich, Germany. Microsoft MVP & Web Geek. - [The Art of Micro Frontends](https://microfrontends.art) - [Homepage](https://florian-rappl.de) - Twitter [@florianrappl](https://twitter.com/florianrappl)
* **[softworkz](https://github.com/softworkz)** - Full Range Developer - likes to start where others gave up. MS MVP alumni and Munich citizen as well.
* **[Robert Muehsig](https://github.com/robertmuehsig)** - Software Developer - from Dresden, Germany, now living & working in Switzerland. Microsoft MVP & Web Geek. - [codeinside Blog](https://blog.codeinside.eu) - Twitter [@robert0muehsig](https://twitter.com/robert0muehsig)
See also the list of [contributors](https://github.com/ElectronNET/Electron.NET/graphs/contributors) who participated in this project.
@@ -196,16 +191,6 @@ See also the list of [contributors](https://github.com/ElectronNET/Electron.NET/
Feel free to submit a pull request if you find any bugs (to see a list of active issues, visit the [Issues section](https://github.com/ElectronNET/Electron.NET/issues).
Please make sure all commits are properly documented.
## 🧪 Working with this Repo
This video provides an introduction to development for Electron.NET: [Electron.NET - Contributing Getting Started](https://youtu.be/Po-saU_Z6Ws)
This repository consists of the main parts (API & CLI) and it's own "playground" ASP.NET Core application. Both main parts produce local NuGet packages, that are versioned with 99.0.0. The first thing you will need is to run one of the build scripts (.cmd or .ps1 for Windows, the .sh for macOS/Linux).
If you look for pure __[demo projects](https://github.com/ElectronNET)__ checkout the other repositories.
The problem working with this repository is, that NuGet has a pretty aggressive cache, see [here for further information](https://github.com/ElectronNET/Electron.NET/wiki).
## 🙏 Donate
We do this open source work in our free time. If you'd like us to invest more time on it, please [donate](https://donorbox.org/electron-net). Donation can be used to increase some issue priority. Thank you!
@@ -221,106 +206,7 @@ Any support appreciated! 🍻
## 🎉 License
MIT-licensed. See [LICENSE](./LICENSE) for details.
MIT-licensed. See [LICENSE](https://github.com/ElectronNET/Electron.NET/blob/main/LICENSE) for details.
**Enjoy!**
## 📝 Important notes
### ElectronNET.API & ElectronNET.CLI Version 9.31.2
Make sure you also have the new Electron.NET API & CLI 9.31.2 version.
```sh
dotnet tool update ElectronNET.CLI -g
```
This now uses [electron-builder](https://www.electron.build/configuration/configuration) and the necessary configuration to build is made in the **electron.manifest.json** file (on the build part). In addition, own Electron.NET configurations are stored (on the root).
Please make sure that your **electron.manifest.json** file has the following new structure:
```json
{
"executable": "{{executable}}",
"splashscreen": {
"imageFile": ""
},
"name": "{{executable}}",
"author": "",
"singleInstance": false,
"build": {
"appId": "com.{{executable}}.app",
"productName": "{{executable}}",
"copyright": "Copyright © 2020",
"buildVersion": "1.0.0",
"compression": "maximum",
"directories": {
"output": "../../../bin/Desktop"
},
"extraResources": [
{
"from": "./bin",
"to": "bin",
"filter": ["**/*"]
}
],
"files": [
{
"from": "./ElectronHostHook/node_modules",
"to": "ElectronHostHook/node_modules",
"filter": ["**/*"]
},
"**/*"
]
}
}
```
### ElectronNET.CLI Version 0.0.9
In the Version 0.0.9 the CLI was not a global tool and needed to be registered like this in the *.csproj*:
```xml
<ItemGroup>
<DotNetCliToolReference Include="ElectronNET.CLI" Version="0.0.9" />
</ItemGroup>
```
After you edited the *.csproj* file, you need to restore your NuGet packages within your Project. Run the following command in your ASP.NET Core folder:
```sh
dotnet restore
```
If you still use this version you will need to invoke it like this:
```sh
electronize ...
```
### Node.js Integration
Electron.NET requires Node.js integration to be enabled for IPC to function. If you are not using the IPC functionality you can disable Node.js integration like so:
```csharp
WebPreferences wp = new WebPreferences();
wp.NodeIntegration = false;
BrowserWindowOptions browserWindowOptions = new BrowserWindowOptions
{
WebPreferences = wp
};
```
### Dependency Injection
ElectronNET.API can be added to your DI container within the `Startup` class. All of the modules available in Electron will be added as Singletons.
```csharp
using ElectronNET.API;
public void ConfigureServices(IServiceCollection services)
{
services.AddElectron();
}
```

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<TargetPlatformVersion>8.1</TargetPlatformVersion>
<IsCodeSharingProject>true</IsCodeSharingProject>
<DefineCommonItemSchemas>true</DefineCommonItemSchemas>
</PropertyGroup>
<PropertyGroup>
<MdIncludes>**/*.md;**/*.markdown</MdIncludes>
<ImageIncludes>**/*.png;**/*.bmp;**/*.jpg;**/*.gif;**/*.mp4</ImageIncludes>
<WebIncludes>**/*.css;**/*.js;**/*.json</WebIncludes>
</PropertyGroup>
<ItemGroup>
<Compile Remove="**/*" />
<Content Remove="**/*" />
</ItemGroup>
<ItemGroup>
<None Include="$(ImageIncludes)" />
<None Include="$(WebIncludes)" />
<None Include="$(MdIncludes)" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ProjectCapability Include="SourceItemsFromImports;SharedImports;SharedAssetsProject"/>
<ProjectCapability Include="HandlesOwnReload"/>
<ProjectCapability Include="UserSourceItems"/>
<ProjectCapability Include="OpenProjectFile"/>
<ProjectCapability Include="UseFileGlobs"/>
<ProjectCapability Include="SingleFileGenerators"/>
</ItemGroup>
<Target Name="Compile">
</Target>
<Target Name="Build">
</Target>
<Target Name="Clean">
</Target>
<Target Name="_CheckForInvalidConfigurationAndPlatform">
</Target>
</Project>

489
docs/API/App.md Normal file
View File

@@ -0,0 +1,489 @@
# Electron.App
Control your application's event lifecycle.
## Overview
The `Electron.App` API provides comprehensive 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.
## Properties
#### 📋 `CommandLine`
A `CommandLine` object that allows you to read and manipulate the command line arguments that Chromium uses.
#### 📋 `IsReady`
Application host fully started.
#### 📋 `Name`
A string property that indicates the current application's name, which is the name in the application's package.json file.
Usually the name field of package.json is a short lowercase name, according to the npm modules spec. You should usually also specify a productName field, which is your application's full capitalized name, and which will be preferred over name by Electron.
#### 📋 `NameAsync`
A `Task<string>` property that indicates the current application's name, which is the name in the application's package.json file.
Usually the name field of package.json is a short lowercase name, according to the npm modules spec. You should usually also specify a productName field, which is your application's full capitalized name, and which will be preferred over name by Electron.
#### 📋 `UserAgentFallback`
A string which is the user agent string Electron will use as a global fallback.
This is the user agent that will be used when no user agent is set at the webContents or session level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used.
#### 📋 `UserAgentFallbackAsync`
A `Task<string>` which is the user agent string Electron will use as a global fallback.
This is the user agent that will be used when no user agent is set at the webContents or session level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used.
## Methods
#### 🧊 `void AddRecentDocument(string path)`
Adds path to the recent documents list. This list is managed by the OS. On Windows you can visit the list from the task bar, and on macOS you can visit it from dock menu.
#### 🧊 `void ClearRecentDocuments()`
Clears the recent documents list.
#### 🧊 `void Exit(int exitCode = 0)`
All windows will be closed immediately without asking user and the BeforeQuit and WillQuit events will not be emitted.
**Parameters:**
- `exitCode` - Exits immediately with exitCode. exitCode defaults to 0.
#### 🧊 `void Focus()`
On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window.
#### 🧊 `void Focus(FocusOptions focusOptions)`
On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window.
You should seek to use the `FocusOptions.Steal` option as sparingly as possible.
**Parameters:**
- `focusOptions` - Focus options
#### 🧊 `Task<ProcessMetric[]> GetAppMetricsAsync(CancellationToken cancellationToken = default)`
Memory and cpu usage statistics of all the processes associated with the app.
**Returns:**
Array of ProcessMetric objects that correspond to memory and cpu usage statistics of all the processes associated with the app.
#### 🧊 `Task<string> GetAppPathAsync(CancellationToken cancellationToken = default)`
The current application directory.
**Returns:**
The current application directory.
#### 🧊 `Task<int> GetBadgeCountAsync(CancellationToken cancellationToken = default)`
The current value displayed in the counter badge.
**Returns:**
The current value displayed in the counter badge.
#### 🧊 `Task<string> GetCurrentActivityTypeAsync(CancellationToken cancellationToken = default)`
The type of the currently running activity.
**Returns:**
The type of the currently running activity.
#### 🧊 `Task<GPUFeatureStatus> GetGpuFeatureStatusAsync(CancellationToken cancellationToken = default)`
The Graphics Feature Status from chrome://gpu/.
Note: This information is only usable after the gpu-info-update event is emitted.
**Returns:**
The Graphics Feature Status from chrome://gpu/.
#### 🧊 `Task<JumpListSettings> GetJumpListSettingsAsync(CancellationToken cancellationToken = default)`
Jump List settings for the application.
**Returns:**
Jump List settings.
#### 🧊 `Task<string> GetLocaleAsync(CancellationToken cancellationToken = default)`
The current application locale. Possible return values are documented [here](https://www.electronjs.org/docs/api/locales).
Note: When distributing your packaged app, you have to also ship the locales folder.
Note: On Windows, you have to call it after the Ready events gets emitted.
**Returns:**
The current application locale.
#### 🧊 `Task<LoginItemSettings> GetLoginItemSettingsAsync(CancellationToken cancellationToken = default)`
If you provided path and args options to SetLoginItemSettings then you need to pass the same arguments here for LoginItemSettings.OpenAtLogin to be set correctly.
**Returns:**
Login item settings.
#### 🧊 `Task<string> GetPathAsync(PathName pathName, CancellationToken cancellationToken = default)`
The path to a special directory. If GetPathAsync is called without called SetAppLogsPath being called first, a default directory will be created equivalent to calling SetAppLogsPath without a path parameter.
**Parameters:**
- `pathName` - Special directory.
**Returns:**
A path to a special directory or file associated with name.
#### 🧊 `Task<string> GetVersionAsync(CancellationToken cancellationToken = default)`
The version of the loaded application. If no version is found in the application's package.json file, the version of the current bundle or executable is returned.
**Returns:**
The version of the loaded application.
#### 🧊 `Task<bool> HasSingleInstanceLockAsync(CancellationToken cancellationToken = default)`
This method returns whether or not this instance of your app is currently holding the single instance lock. You can request the lock with RequestSingleInstanceLockAsync and release with ReleaseSingleInstanceLock.
**Returns:**
Whether this instance of your app is currently holding the single instance lock.
#### 🧊 `void Hide()`
Hides all application windows without minimizing them.
#### 🧊 `Task<int> ImportCertificateAsync(ImportCertificateOptions options, CancellationToken cancellationToken = default)`
Imports the certificate in pkcs12 format into the platform certificate store. callback is called with the result of import operation, a value of 0 indicates success while any other value indicates failure according to chromium net_error_list.
**Parameters:**
- `options` - Import certificate options
- `cancellationToken` - The cancellation token
**Returns:**
Result of import. Value of 0 indicates success.
#### 🧊 `void InvalidateCurrentActivity()`
Invalidates the current Handoff user activity.
#### 🧊 `Task<bool> IsAccessibilitySupportEnabledAsync(CancellationToken cancellationToken = default)`
true if Chrome's accessibility support is enabled, false otherwise. This API will return true if the use of assistive technologies, such as screen readers, has been detected. See Chromium's accessibility docs for more details.
**Returns:**
true if Chrome's accessibility support is enabled, false otherwise.
#### 🧊 `Task<bool> IsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)`
This method checks if the current executable is the default handler for a protocol (aka URI scheme).
Note: On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking ~/Library/Preferences/com.apple.LaunchServices.plist on the macOS machine. Please refer to Apple's documentation for details.
The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.
**Parameters:**
- `protocol` - The name of your protocol, without ://
- `cancellationToken` - The cancellation token
**Returns:**
Whether the current executable is the default handler for a protocol (aka URI scheme).
#### 🧊 `Task<bool> IsUnityRunningAsync(CancellationToken cancellationToken = default)`
Whether the current desktop environment is Unity launcher.
**Returns:**
Whether the current desktop environment is Unity launcher.
#### 🧊 `void Quit()`
Try to close all windows. The BeforeQuit event will be emitted first. If all windows are successfully closed, the WillQuit event will be emitted and by default the application will terminate. This method guarantees that all beforeunload and unload event handlers are correctly executed. It is possible that a window cancels the quitting by returning false in the beforeunload event handler.
#### 🧊 `void ReleaseSingleInstanceLock()`
Releases all locks that were created by makeSingleInstance. This will allow multiple instances of the application to once again run side by side.
#### 🧊 `void Relaunch()`
Relaunches the app when current instance exits. By default the new instance will use the same working directory and command line arguments with current instance.
Note that this method does not quit the app when executed, you have to call Quit or Exit after calling Relaunch() to make the app restart.
When Relaunch() is called for multiple times, multiple instances will be started after current instance exited.
#### 🧊 `void Relaunch(RelaunchOptions relaunchOptions)`
Relaunches the app when current instance exits. By default the new instance will use the same working directory and command line arguments with current instance. When RelaunchOptions.Args is specified, the RelaunchOptions.Args will be passed as command line arguments instead. When RelaunchOptions.ExecPath is specified, the RelaunchOptions.ExecPath will be executed for relaunch instead of current app.
Note that this method does not quit the app when executed, you have to call Quit or Exit after calling Relaunch() to make the app restart.
When Relaunch() is called for multiple times, multiple instances will be started after current instance exited.
**Parameters:**
- `relaunchOptions` - Options for the relaunch
#### 🧊 `Task<bool> RemoveAsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)`
This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler.
**Parameters:**
- `protocol` - The name of your protocol, without ://
- `cancellationToken` - The cancellation token
**Returns:**
Whether the call succeeded.
#### 🧊 `Task<bool> RequestSingleInstanceLockAsync(Action<string[], string> newInstanceOpened, CancellationToken cancellationToken = default)`
The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately.
I.e.This method returns true if your process is the primary instance of your application and your app should continue loading. It returns false if your process should immediately quit as it has sent its parameters to another instance that has already acquired the lock.
On macOS, the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the open-file and open-url events will be emitted for that.However when users start your app in command line, the system's single instance mechanism will be bypassed, and you have to use this method to ensure single instance.
**Parameters:**
- `newInstanceOpened` - Lambda with an array of the second instance's command line arguments. The second parameter is the working directory path.
- `cancellationToken` - The cancellation token
**Returns:**
This method returns false if your process is the primary instance of the application and your app should continue loading. And returns true if your process has sent its parameters to another instance, and you should immediately quit.
#### 🧊 `void ResignCurrentActivity()`
Marks the current Handoff user activity as inactive without invalidating it.
#### 🧊 `void SetAccessibilitySupportEnabled(bool enabled)`
Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See Chromium's accessibility docs for more details. Disabled (false) by default.
This API must be called after the Ready event is emitted.
Note: Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
**Parameters:**
- `enabled` - Enable or disable accessibility tree rendering
#### 🧊 `void SetAppLogsPath(string path)`
Sets or creates a directory your app's logs which can then be manipulated with GetPathAsync or SetPath.
Calling SetAppLogsPath without a path parameter will result in this directory being set to ~/Library/Logs/YourAppName on macOS, and inside the userData directory on Linux and Windows.
**Parameters:**
- `path` - A custom path for your logs. Must be absolute
#### 🧊 `void SetAppUserModelId(string id)`
Changes the Application User Model ID to id.
**Parameters:**
- `id` - Model Id
#### 🧊 `Task<bool> SetAsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)`
Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with your-protocol:// will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter.
Note: On macOS, you can only register protocols that have been added to your app's info.plist, which cannot be modified at runtime. However, you can change the file during build time via Electron Forge, Electron Packager, or by editing info.plist with a text editor. Please refer to Apple's documentation for details.
Note: In a Windows Store environment (when packaged as an appx) this API will return true for all calls but the registry key it sets won't be accessible by other applications. In order to register your Windows Store application as a default protocol handler you must declare the protocol in your manifest.
The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.
**Parameters:**
- `protocol` - The name of your protocol, without ://. For example, if you want your app to handle electron:// links, call this method with electron as the parameter.
- `cancellationToken` - The cancellation token
**Returns:**
Whether the call succeeded.
#### 🧊 `Task<bool> SetBadgeCountAsync(int count, CancellationToken cancellationToken = default)`
Sets the counter badge for current app. Setting the count to 0 will hide the badge. On macOS it shows on the dock icon. On Linux it only works for Unity launcher.
Note: Unity launcher requires the existence of a .desktop file to work, for more information please read Desktop Environment Integration.
**Parameters:**
- `count` - Counter badge
- `cancellationToken` - The cancellation token
**Returns:**
Whether the call succeeded.
#### 🧊 `void SetJumpList(JumpListCategory[] categories)`
Sets or removes a custom Jump List for the application. If categories is null the previously set custom Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows).
Note: If a JumpListCategory object has neither the Type nor the Name property set then its Type is assumed to be tasks. If the Name property is set but the Type property is omitted then the Type is assumed to be custom.
Note: Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until after the next successful call to SetJumpList. Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. The list of removed items can be obtained using GetJumpListSettingsAsync.
**Parameters:**
- `categories` - Array of JumpListCategory objects
#### 🧊 `void SetLoginItemSettings(LoginSettings loginSettings)`
Set the app's login item settings.
To work with Electron's autoUpdater on Windows, which uses Squirrel, you'll want to set the launch path to Update.exe, and pass arguments that specify your application name.
**Parameters:**
- `loginSettings` - Login settings
#### 🧊 `void SetPath(PathName name, string path)`
Overrides the path to a special directory or file associated with name. If the path specifies a directory that does not exist, an Error is thrown. In that case, the directory should be created with fs.mkdirSync or similar.
You can only override paths of a name defined in GetPathAsync.
By default, web pages' cookies and caches will be stored under the PathName.UserData directory. If you want to change this location, you have to override the PathName.UserData path before the Ready event of the App module is emitted.
**Parameters:**
- `name` - Special directory name
- `path` - New path to a special directory
#### 🧊 `void SetUserActivity(string type, object userInfo)`
Creates an NSUserActivity and sets it as the current activity. The activity is eligible for Handoff to another device afterward.
**Parameters:**
- `type` - Uniquely identifies the activity. Maps to NSUserActivity.activityType.
- `userInfo` - App-specific state to store for use by another device
#### 🧊 `Task<bool> SetUserTasksAsync(UserTask[] userTasks, CancellationToken cancellationToken = default)`
Adds tasks to the UserTask category of the JumpList on Windows.
Note: If you'd like to customize the Jump List even more use SetJumpList instead.
**Parameters:**
- `userTasks` - Array of UserTask objects
- `cancellationToken` - The cancellation token
**Returns:**
Whether the call succeeded.
#### 🧊 `void Show()`
Shows application windows after they were hidden. Does not automatically focus them.
#### 🧊 `void ShowAboutPanel()`
Show the app's about panel options. These options can be overridden with SetAboutPanelOptions.
## Events
#### ⚡ `AccessibilitySupportChanged`
Emitted when Chrome's accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details.
#### ⚡ `BrowserWindowBlur`
Emitted when a BrowserWindow blurred.
#### ⚡ `BrowserWindowCreated`
Emitted when a new BrowserWindow is created.
#### ⚡ `BrowserWindowFocus`
Emitted when a BrowserWindow gets focused.
#### ⚡ `OpenFile`
Emitted when a macOS user wants to open a file with the application. The open-file event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. open-file is also emitted when a file is dropped onto the dock and the application is not yet running.
On Windows, you have to parse the arguments using App.CommandLine to get the filepath.
#### ⚡ `OpenUrl`
Emitted when a macOS user wants to open a URL with the application. Your application's Info.plist file must define the URL scheme within the CFBundleURLTypes key, and set NSPrincipalClass to AtomApplication.
#### ⚡ `Quitting`
Emitted when the application is quitting.
Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
#### ⚡ `Ready`
Emitted when the application has finished basic startup.
#### ⚡ `WebContentsCreated`
Emitted when a new WebContents is created.
#### ⚡ `WillQuit`
Emitted when all windows have been closed and the application will quit.
See the description of the WindowAllClosed event for the differences between the WillQuit and WindowAllClosed events.
Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
#### ⚡ `WindowAllClosed`
Emitted when all windows have been closed.
If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not.If the user pressed Cmd + Q, or the developer called Quit, Electron will first try to close all the windows and then emit the WillQuit event, and in this case the WindowAllClosed event would not be emitted.
## Usage Examples
### Application Lifecycle
```csharp
// Handle app startup
Electron.App.Ready += () =>
{
Console.WriteLine("App is ready!");
};
// Handle window management
Electron.App.WindowAllClosed += () =>
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Electron.App.Quit();
}
};
// Prevent quit
Electron.App.BeforeQuit += async (args) =>
{
var result = await Electron.Dialog.ShowMessageBoxAsync("Do you want to quit?");
if (result.Response == 1) // Cancel
{
args.PreventDefault = true;
}
};
```
### Protocol Handling
```csharp
// Register custom protocol
var success = await Electron.App.SetAsDefaultProtocolClientAsync("myapp");
// Check if registered
var isDefault = await Electron.App.IsDefaultProtocolClientAsync("myapp");
```
### Jump List (Windows)
```csharp
// Set user tasks
await Electron.App.SetUserTasksAsync(new[]
{
new UserTask
{
Program = "myapp.exe",
Arguments = "--new-document",
Title = "New Document",
Description = "Create a new document"
}
});
```
### Application Information
```csharp
// Get app information
var appPath = await Electron.App.GetAppPathAsync();
var version = await Electron.App.GetVersionAsync();
var locale = await Electron.App.GetLocaleAsync();
// Set app name
await Electron.App.NameAsync; // Get current name
Electron.App.Name = "My Custom App Name";
```
### Badge Count (macOS/Linux)
```csharp
// Set badge count
await Electron.App.SetBadgeCountAsync(5);
// Get current badge count
var count = await Electron.App.GetBadgeCountAsync();
```
## Related APIs
- [Electron.WindowManager](WindowManager.md) - Window creation and management
- [Electron.Dialog](Dialog.md) - User interaction dialogs
- [Electron.Menu](Menu.md) - Application menus
## Additional Resources
- [Electron App Documentation](https://electronjs.org/docs/api/app) - Official Electron app API
- [Startup Methods](../Using/Startup-Methods.md) - Different application startup modes

243
docs/API/AutoUpdater.md Normal file
View File

@@ -0,0 +1,243 @@
# Electron.AutoUpdater
Handle application updates and installation processes.
## Overview
The `Electron.AutoUpdater` API provides comprehensive functionality for handling application updates, including checking for updates, downloading, and installation. It supports multiple update providers and platforms with automatic update capabilities.
## Properties
#### 📋 `bool AllowDowngrade`
Whether to allow version downgrade. Default is false.
#### 📋 `bool AllowPrerelease`
GitHub provider only. Whether to allow update to pre-release versions. Defaults to true if application version contains prerelease components.
#### 📋 `bool AutoDownload`
Whether to automatically download an update when it is found. Default is true.
#### 📋 `bool AutoInstallOnAppQuit`
Whether to automatically install a downloaded update on app quit. Applicable only on Windows and Linux.
#### 📋 `string Channel`
Get the update channel. Not applicable for GitHub. Doesn't return channel from the update configuration, only if was previously set.
#### 📋 `Task<string> ChannelAsync`
Get the update channel. Not applicable for GitHub. Doesn't return channel from the update configuration, only if was previously set.
#### 📋 `Task<SemVer> CurrentVersionAsync`
Get the current application version.
#### 📋 `bool FullChangelog`
GitHub provider only. Get all release notes (from current version to latest), not just the latest. Default is false.
#### 📋 `Dictionary<string, string> RequestHeaders`
The request headers.
#### 📋 `Task<Dictionary<string, string>> RequestHeadersAsync`
Get the current request headers.
#### 📋 `string UpdateConfigPath`
For test only. Configuration path for updates.
## Methods
#### 🧊 `Task<UpdateCheckResult> CheckForUpdatesAndNotifyAsync()`
Asks the server whether there is an update and notifies the user if an update is available.
#### 🧊 `Task<UpdateCheckResult> CheckForUpdatesAsync()`
Asks the server whether there is an update.
#### 🧊 `Task<string> DownloadUpdateAsync()`
Start downloading update manually. Use this method if AutoDownload option is set to false.
**Returns:**
Path to downloaded file.
#### 🧊 `Task<string> GetFeedURLAsync()`
Get the current feed URL.
**Returns:**
Feed URL.
#### 🧊 `void QuitAndInstall(bool isSilent = false, bool isForceRunAfter = false)`
Restarts the app and installs the update after it has been downloaded. Should only be called after update-downloaded has been emitted.
Note: QuitAndInstall() will close all application windows first and only emit before-quit event on app after that. This is different from the normal quit event sequence.
**Parameters:**
- `isSilent` - Windows-only: Runs the installer in silent mode. Defaults to false
- `isForceRunAfter` - Run the app after finish even on silent install. Not applicable for macOS
## Events
#### ⚡ `OnCheckingForUpdate`
Emitted when checking if an update has started.
#### ⚡ `OnDownloadProgress`
Emitted on download progress.
#### ⚡ `OnError`
Emitted when there is an error while updating.
#### ⚡ `OnUpdateAvailable`
Emitted when there is an available update. The update is downloaded automatically if AutoDownload is true.
#### ⚡ `OnUpdateDownloaded`
Emitted on download complete.
#### ⚡ `OnUpdateNotAvailable`
Emitted when there is no available update.
## Usage Examples
### Basic Auto-Update Setup
```csharp
// Configure auto-updater
Electron.AutoUpdater.AutoDownload = true;
Electron.AutoUpdater.AutoInstallOnAppQuit = true;
// Check for updates
var updateCheck = await Electron.AutoUpdater.CheckForUpdatesAsync();
if (updateCheck.UpdateInfo != null)
{
Console.WriteLine($"Update available: {updateCheck.UpdateInfo.Version}");
}
```
### Manual Update Management
```csharp
// Disable auto-download for manual control
Electron.AutoUpdater.AutoDownload = false;
// Check for updates
var result = await Electron.AutoUpdater.CheckForUpdatesAsync();
if (result.UpdateInfo != null)
{
Console.WriteLine($"Update found: {result.UpdateInfo.Version}");
// Ask user confirmation
var confirmResult = await Electron.Dialog.ShowMessageBoxAsync(
"Update Available",
$"Version {result.UpdateInfo.Version} is available. Download now?");
if (confirmResult.Response == 1) // Yes
{
// Download update manually
var downloadPath = await Electron.AutoUpdater.DownloadUpdateAsync();
Console.WriteLine($"Downloaded to: {downloadPath}");
// Install update
Electron.AutoUpdater.QuitAndInstall();
}
}
```
### Update Event Handling
```csharp
// Handle update events
Electron.AutoUpdater.OnCheckingForUpdate += () =>
{
Console.WriteLine("Checking for updates...");
};
Electron.AutoUpdater.OnUpdateAvailable += (updateInfo) =>
{
Console.WriteLine($"Update available: {updateInfo.Version}");
};
Electron.AutoUpdater.OnUpdateNotAvailable += (updateInfo) =>
{
Console.WriteLine("No updates available");
};
Electron.AutoUpdater.OnDownloadProgress += (progressInfo) =>
{
Console.WriteLine($"Download progress: {progressInfo.Percent}%");
};
Electron.AutoUpdater.OnUpdateDownloaded += (updateInfo) =>
{
Console.WriteLine($"Update downloaded: {updateInfo.Version}");
// Show notification to user
Electron.Notification.Show(new NotificationOptions
{
Title = "Update Downloaded",
Body = $"Version {updateInfo.Version} is ready to install.",
Actions = new[]
{
new NotificationAction { Text = "Install Now", Type = NotificationActionType.Button },
new NotificationAction { Text = "Later", Type = NotificationActionType.Button }
}
});
};
Electron.AutoUpdater.OnError += (error) =>
{
Console.WriteLine($"Update error: {error}");
Electron.Dialog.ShowErrorBox("Update Error", $"Failed to update: {error}");
};
```
### GitHub Provider Configuration
```csharp
// Configure for GitHub releases
Electron.AutoUpdater.AllowPrerelease = true; // Allow pre-release versions
Electron.AutoUpdater.FullChangelog = true; // Get full changelog
Electron.AutoUpdater.AllowDowngrade = false; // Prevent downgrades
// Set request headers if needed
Electron.AutoUpdater.RequestHeaders = new Dictionary<string, string>
{
["Authorization"] = "token your-github-token",
["User-Agent"] = "MyApp-Updater"
};
```
### Update Installation
```csharp
// Install update immediately
if (updateDownloaded)
{
Electron.AutoUpdater.QuitAndInstall();
}
// Silent install (Windows only)
Electron.AutoUpdater.QuitAndInstall(isSilent: true, isForceRunAfter: true);
```
### Version Management
```csharp
// Get current version
var currentVersion = await Electron.AutoUpdater.CurrentVersionAsync;
Console.WriteLine($"Current version: {currentVersion}");
// Get update channel
var channel = await Electron.AutoUpdater.ChannelAsync;
Console.WriteLine($"Update channel: {channel}");
// Set custom feed URL
// Note: This would typically be configured in electron-builder.json
var feedUrl = await Electron.AutoUpdater.GetFeedURLAsync();
Console.WriteLine($"Feed URL: {feedUrl}");
```
## Related APIs
- [Electron.App](App.md) - Application lifecycle events during updates
- [Electron.Notification](Notification.md) - Notify users about update status
- [Electron.Dialog](Dialog.md) - Show update confirmation dialogs
## Additional Resources
- [Electron AutoUpdater Documentation](https://electronjs.org/docs/api/auto-updater) - Official Electron auto-updater API

231
docs/API/Clipboard.md Normal file
View File

@@ -0,0 +1,231 @@
# Electron.Clipboard
Perform copy and paste operations on the system clipboard.
## Overview
The `Electron.Clipboard` API provides comprehensive access to the system clipboard, supporting multiple data formats including text, HTML, RTF, images, and custom data. It enables reading from and writing to the clipboard with platform-specific behavior.
## Methods
#### 🧊 `Task<string[]> AvailableFormatsAsync(string type = "")`
Get an array of supported formats for the clipboard type.
**Parameters:**
- `type` - Clipboard type
**Returns:**
An array of supported formats for the clipboard type.
#### 🧊 `void Clear(string type = "")`
Clears the clipboard content.
**Parameters:**
- `type` - Clipboard type
#### 🧊 `Task<ReadBookmark> ReadBookmarkAsync()`
Returns an Object containing title and url keys representing the bookmark in the clipboard. The title and url values will be empty strings when the bookmark is unavailable.
**Returns:**
Object containing title and url keys representing the bookmark in the clipboard.
#### 🧊 `Task<string> ReadFindTextAsync()`
macOS: The text on the find pasteboard. This method uses synchronous IPC when called from the renderer process. The cached value is reread from the find pasteboard whenever the application is activated.
**Returns:**
The text on the find pasteboard.
#### 🧊 `Task<string> ReadHTMLAsync(string type = "")`
Read the content in the clipboard as HTML markup.
**Parameters:**
- `type` - Clipboard type
**Returns:**
The content in the clipboard as markup.
#### 🧊 `Task<NativeImage> ReadImageAsync(string type = "")`
Read an image from the clipboard.
**Parameters:**
- `type` - Clipboard type
**Returns:**
An image from the clipboard.
#### 🧊 `Task<string> ReadRTFAsync(string type = "")`
Read the content in the clipboard as RTF.
**Parameters:**
- `type` - Clipboard type
**Returns:**
The content in the clipboard as RTF.
#### 🧊 `Task<string> ReadTextAsync(string type = "")`
Read the content in the clipboard as plain text.
**Parameters:**
- `type` - Clipboard type
**Returns:**
The content in the clipboard as plain text.
#### 🧊 `void Write(Data data, string type = "")`
Writes data to the clipboard.
**Parameters:**
- `data` - Data object to write
- `type` - Clipboard type
#### 🧊 `void WriteBookmark(string title, string url, string type = "")`
Writes the title and url into the clipboard as a bookmark.
Note: Most apps on Windows don't support pasting bookmarks into them so you can use clipboard.write to write both a bookmark and fallback text to the clipboard.
**Parameters:**
- `title` - Bookmark title
- `url` - Bookmark URL
- `type` - Clipboard type
#### 🧊 `void WriteFindText(string text)`
macOS: Writes the text into the find pasteboard as plain text. This method uses synchronous IPC when called from the renderer process.
**Parameters:**
- `text` - Text to write to find pasteboard
#### 🧊 `void WriteHTML(string markup, string type = "")`
Writes markup to the clipboard.
**Parameters:**
- `markup` - HTML markup to write
- `type` - Clipboard type
#### 🧊 `void WriteImage(NativeImage image, string type = "")`
Writes an image to the clipboard.
**Parameters:**
- `image` - Image to write to clipboard
- `type` - Clipboard type
#### 🧊 `void WriteRTF(string text, string type = "")`
Writes the text into the clipboard in RTF.
**Parameters:**
- `text` - RTF content to write
- `type` - Clipboard type
#### 🧊 `void WriteText(string text, string type = "")`
Writes the text into the clipboard as plain text.
**Parameters:**
- `text` - Text content to write
- `type` - Clipboard type
## Usage Examples
### Basic Text Operations
```csharp
// Read text from clipboard
var text = await Electron.Clipboard.ReadTextAsync();
Console.WriteLine($"Clipboard text: {text}");
// Write text to clipboard
Electron.Clipboard.WriteText("Hello, Electron.NET!");
// Read with specific type
var html = await Electron.Clipboard.ReadHTMLAsync("public.main");
```
### Rich Content Handling
```csharp
// Copy formatted text
var htmlContent = "<h1>Title</h1><p>Some <strong>bold</strong> text</p>";
Electron.Clipboard.WriteHTML(htmlContent);
// Read RTF content
var rtf = await Electron.Clipboard.ReadRTFAsync();
Console.WriteLine($"RTF content: {rtf}");
```
### Image Operations
```csharp
// Read image from clipboard
var image = await Electron.Clipboard.ReadImageAsync();
if (image != null)
{
Console.WriteLine($"Image size: {image.Size.Width}x{image.Size.Height}");
}
// Write image to clipboard
var nativeImage = NativeImage.CreateFromPath("screenshot.png");
Electron.Clipboard.WriteImage(nativeImage);
```
### Bookmark Management
```csharp
// Read bookmark from clipboard
var bookmark = await Electron.Clipboard.ReadBookmarkAsync();
if (!string.IsNullOrEmpty(bookmark.Title))
{
Console.WriteLine($"Bookmark: {bookmark.Title} -> {bookmark.Url}");
}
// Write bookmark to clipboard
Electron.Clipboard.WriteBookmark("Electron.NET", "https://github.com/ElectronNET/Electron.NET");
```
### Advanced Clipboard Operations
```csharp
// Check available formats
var formats = await Electron.Clipboard.AvailableFormatsAsync();
Console.WriteLine($"Available formats: {string.Join(", ", formats)}");
// Clear clipboard
Electron.Clipboard.Clear();
// Write custom data
var data = new Data
{
Text = "Custom data",
Html = "<p>Custom HTML</p>",
Image = nativeImage
};
Electron.Clipboard.Write(data);
```
### macOS Find Pasteboard
```csharp
// macOS specific find pasteboard operations
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// Read find text
var findText = await Electron.Clipboard.ReadFindTextAsync();
Console.WriteLine($"Find text: {findText}");
// Write find text
Electron.Clipboard.WriteFindText("search term");
}
```
## Related APIs
- [Electron.Shell](Shell.md) - Work with file paths from clipboard
- [Electron.Notification](Notification.md) - Show clipboard operation results
## Additional Resources
- [Electron Clipboard Documentation](https://electronjs.org/docs/api/clipboard) - Official Electron clipboard API

160
docs/API/Dialog.md Normal file
View File

@@ -0,0 +1,160 @@
# Electron.Dialog
Display native system dialogs for opening and saving files, alerting, etc.
## Overview
The `Electron.Dialog` API provides access to native system dialogs for file operations, message boxes, and certificate trust dialogs. These dialogs are modal and provide a consistent user experience across different platforms.
## Methods
#### 🧊 `Task<MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, MessageBoxOptions messageBoxOptions)`
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. If a callback is passed, the dialog will not block the process.
**Parameters:**
- `browserWindow` - The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.
- `messageBoxOptions` - Message content and configuration
**Returns:**
The API call will be asynchronous and the result will be passed via MessageBoxResult.
#### 🧊 `Task<MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, string message)`
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. If a callback is passed, the dialog will not block the process.
**Parameters:**
- `browserWindow` - The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.
- `message` - Message content
**Returns:**
The API call will be asynchronous and the result will be passed via MessageBoxResult.
#### 🧊 `Task<MessageBoxResult> ShowMessageBoxAsync(MessageBoxOptions messageBoxOptions)`
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. If a callback is passed, the dialog will not block the process.
**Parameters:**
- `messageBoxOptions` - Message content and configuration
**Returns:**
The API call will be asynchronous and the result will be passed via MessageBoxResult.
#### 🧊 `Task<MessageBoxResult> ShowMessageBoxAsync(string message)`
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. If a callback is passed, the dialog will not block the process.
**Parameters:**
- `message` - Message content
**Returns:**
The API call will be asynchronous and the result will be passed via MessageBoxResult.
#### 🧊 `Task<string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options)`
Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown.
**Parameters:**
- `browserWindow` - The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.
- `options` - Dialog configuration options
**Returns:**
An array of file paths chosen by the user
#### 🧊 `Task<string> ShowSaveDialogAsync(BrowserWindow browserWindow, SaveDialogOptions options)`
Dialog for save files.
**Parameters:**
- `browserWindow` - The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.
- `options` - Dialog configuration options
**Returns:**
Returns String, the path of the file chosen by the user, if a callback is provided it returns an empty string.
#### 🧊 `void ShowErrorBox(string title, string content)`
Displays a modal dialog that shows an error message.
This API can be called safely before the ready event the app module emits, it is usually used to report errors in early stage of startup.If called before the app readyevent on Linux, the message will be emitted to stderr, and no GUI dialog will appear.
**Parameters:**
- `title` - The title to display in the error box.
- `content` - The text content to display in the error box.
#### 🧊 `Task ShowCertificateTrustDialogAsync(BrowserWindow browserWindow, CertificateTrustDialogOptions options)`
On macOS, this displays a modal dialog that shows a message and certificate information, and gives the user the option of trusting/importing the certificate. If you provide a browserWindow argument the dialog will be attached to the parent window, making it modal.
**Parameters:**
- `browserWindow` - Parent window for modal behavior
- `options` - Certificate trust dialog options
#### 🧊 `Task ShowCertificateTrustDialogAsync(CertificateTrustDialogOptions options)`
On macOS, this displays a modal dialog that shows a message and certificate information, and gives the user the option of trusting/importing the certificate. If you provide a browserWindow argument the dialog will be attached to the parent window, making it modal.
**Parameters:**
- `options` - Certificate trust dialog options
## Usage Examples
### File Operations
```csharp
// Open multiple files
var files = await Electron.Dialog.ShowOpenDialogAsync(window, new OpenDialogOptions
{
Properties = new[] { OpenDialogProperty.OpenFile, OpenDialogProperty.MultiSelections }
});
// Save with custom extension
var path = await Electron.Dialog.ShowSaveDialogAsync(window, new SaveDialogOptions
{
DefaultPath = "backup.json",
Filters = new[] { new FileFilter { Name = "JSON", Extensions = new[] { "json" } } }
});
```
### User Confirmation
```csharp
// Confirmation dialog
var result = await Electron.Dialog.ShowMessageBoxAsync(window, new MessageBoxOptions
{
Type = MessageBoxType.Question,
Title = "Confirm Delete",
Message = $"Delete {filename}?",
Buttons = new[] { "Cancel", "Delete" },
DefaultId = 0,
CancelId = 0
});
if (result.Response == 1)
{
// Delete file
}
```
### Error Handling
```csharp
// Error dialog
Electron.Dialog.ShowErrorBox("Save Failed", "Could not save file. Please check permissions and try again.");
// Warning dialog
await Electron.Dialog.ShowMessageBoxAsync(new MessageBoxOptions
{
Type = MessageBoxType.Warning,
Title = "Warning",
Message = "This operation may take several minutes.",
Buttons = new[] { "Continue", "Cancel" }
});
```
## Related APIs
- [Electron.WindowManager](WindowManager.md) - Parent windows for modal dialogs
- [Electron.App](App.md) - Application lifecycle events
- [Electron.Shell](Shell.md) - File operations with selected paths
## Additional Resources
- [Electron Dialog Documentation](https://electronjs.org/docs/api/dialog) - Official Electron dialog API

209
docs/API/Dock.md Normal file
View File

@@ -0,0 +1,209 @@
# Electron.Dock
Control your app in the macOS dock.
## Overview
The `Electron.Dock` API provides control over your application's appearance and behavior in the macOS dock. This includes bouncing the dock icon, setting badges, managing menus, and controlling visibility.
## Properties
#### 📋 `IReadOnlyCollection<MenuItem> MenuItems`
Gets a read-only collection of all current dock menu items.
## Methods
#### 🧊 `Task<int> BounceAsync(DockBounceType type, CancellationToken cancellationToken = default)`
When `DockBounceType.Critical` is passed, the dock icon will bounce until either the application becomes active or the request is canceled. When `DockBounceType.Informational` is passed, the dock icon will bounce for one second. However, the request remains active until either the application becomes active or the request is canceled.
Note: This method can only be used while the app is not focused; when the app is focused it will return -1.
**Parameters:**
- `type` - Can be critical or informational. The default is informational.
- `cancellationToken` - The cancellation token
**Returns:**
An ID representing the request.
#### 🧊 `void CancelBounce(int id)`
Cancel the bounce of id.
**Parameters:**
- `id` - Id of the request
#### 🧊 `void DownloadFinished(string filePath)`
Bounces the Downloads stack if the filePath is inside the Downloads folder.
**Parameters:**
- `filePath` - Path to the downloaded file
#### 🧊 `Task<string> GetBadgeAsync(CancellationToken cancellationToken = default)`
Gets the string to be displayed in the dock's badging area.
**Returns:**
The badge string of the dock.
#### 🧊 `Task<Menu> GetMenu(CancellationToken cancellationToken = default)`
Gets the application's dock menu.
**Returns:**
The application's dock menu.
#### 🧊 `void Hide()`
Hides the dock icon.
#### 🧊 `Task<bool> IsVisibleAsync(CancellationToken cancellationToken = default)`
Whether the dock icon is visible. The app.dock.show() call is asynchronous so this method might not return true immediately after that call.
**Returns:**
Whether the dock icon is visible.
#### 🧊 `void SetBadge(string text)`
Sets the string to be displayed in the dock's badging area.
**Parameters:**
- `text` - Badge text to display
#### 🧊 `void SetIcon(string image)`
Sets the image associated with this dock icon.
**Parameters:**
- `image` - Icon image path
#### 🧊 `void SetMenu(MenuItem[] menuItems)`
Sets the application's dock menu.
**Parameters:**
- `menuItems` - Array of menu items for the dock menu
#### 🧊 `void Show()`
Shows the dock icon.
## Usage Examples
### Basic Dock Operations
```csharp
// Hide/Show dock icon
Electron.Dock.Hide();
await Task.Delay(2000);
Electron.Dock.Show();
// Check visibility
var isVisible = await Electron.Dock.IsVisibleAsync();
Console.WriteLine($"Dock visible: {isVisible}");
```
### Badge Notifications
```csharp
// Set badge count
Electron.Dock.SetBadge("5");
// Get current badge
var badge = await Electron.Dock.GetBadgeAsync();
Console.WriteLine($"Current badge: {badge}");
// Clear badge
Electron.Dock.SetBadge("");
```
### Dock Icon Animation
```csharp
// Bounce for attention
var bounceId = await Electron.Dock.BounceAsync(DockBounceType.Critical);
Console.WriteLine($"Bounce ID: {bounceId}");
// Cancel bounce after 3 seconds
await Task.Delay(3000);
Electron.Dock.CancelBounce(bounceId);
// Informational bounce
await Electron.Dock.BounceAsync(DockBounceType.Informational);
```
### Dock Menu
```csharp
// Create dock menu
var dockMenuItems = 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() }
};
// Set dock menu
Electron.Dock.SetMenu(dockMenuItems);
// Get current menu
var currentMenu = await Electron.Dock.GetMenu();
Console.WriteLine($"Menu items: {Electron.Dock.MenuItems.Count}");
```
### Download Notifications
```csharp
// Notify about completed download
var downloadPath = "/Users/username/Downloads/document.pdf";
Electron.Dock.DownloadFinished(downloadPath);
```
### Custom Dock Icon
```csharp
// Set custom dock icon
Electron.Dock.SetIcon("assets/custom-dock-icon.png");
// Set icon based on status
if (isConnected)
{
Electron.Dock.SetIcon("assets/connected-icon.png");
}
else
{
Electron.Dock.SetIcon("assets/disconnected-icon.png");
}
```
### Application Integration
```csharp
// Update dock badge based on unread count
UpdateDockBadge(unreadMessageCount);
void UpdateDockBadge(int count)
{
if (count > 0)
{
Electron.Dock.SetBadge(count.ToString());
}
else
{
Electron.Dock.SetBadge("");
}
}
// Animate dock when receiving message
private async void OnMessageReceived()
{
await Electron.Dock.BounceAsync(DockBounceType.Informational);
Electron.Dock.SetBadge((unreadCount + 1).ToString());
}
```
## Related APIs
- [Electron.App](App.md) - Application lifecycle events
- [Electron.Notification](Notification.md) - Desktop notifications
- [Electron.Menu](Menu.md) - Menu items for dock menu
## Additional Resources
- [Electron Dock Documentation](https://electronjs.org/docs/api/dock) - Official Electron dock API

189
docs/API/GlobalShortcut.md Normal file
View File

@@ -0,0 +1,189 @@
# Electron.GlobalShortcut
Register global keyboard shortcuts that work even when the application is not focused.
## Overview
The `Electron.GlobalShortcut` API provides the ability to register global keyboard shortcuts that can be triggered even when the application does not have keyboard focus. This is useful for creating system-wide hotkeys and shortcuts.
## Methods
#### 🧊 `Task<bool> IsRegisteredAsync(string accelerator)`
Check if the accelerator is registered.
**Parameters:**
- `accelerator` - Keyboard shortcut to check
**Returns:**
Whether this application has registered the accelerator.
#### 🧊 `void Register(string accelerator, Action function)`
Registers a global shortcut of accelerator. The callback is called when the registered shortcut is pressed by the user.
**Parameters:**
- `accelerator` - Keyboard shortcut combination
- `function` - Callback function to execute when shortcut is pressed
#### 🧊 `void Unregister(string accelerator)`
Unregisters the global shortcut of accelerator.
**Parameters:**
- `accelerator` - Keyboard shortcut to unregister
#### 🧊 `void UnregisterAll()`
Unregisters all of the global shortcuts.
## Usage Examples
### Basic Global Shortcuts
```csharp
// Register global shortcuts
Electron.GlobalShortcut.Register("CommandOrControl+N", () =>
{
CreateNewDocument();
});
Electron.GlobalShortcut.Register("CommandOrControl+O", () =>
{
OpenDocument();
});
Electron.GlobalShortcut.Register("CommandOrControl+S", () =>
{
SaveDocument();
});
```
### Media Control Shortcuts
```csharp
// Media playback shortcuts
Electron.GlobalShortcut.Register("MediaPlayPause", () =>
{
TogglePlayback();
});
Electron.GlobalShortcut.Register("MediaNextTrack", () =>
{
NextTrack();
});
Electron.GlobalShortcut.Register("MediaPreviousTrack", () =>
{
PreviousTrack();
});
```
### Application Control Shortcuts
```csharp
// Application control shortcuts
Electron.GlobalShortcut.Register("CommandOrControl+Shift+Q", async () =>
{
var result = await Electron.Dialog.ShowMessageBoxAsync("Quit Application?", "Are you sure you want to quit?");
if (result.Response == 1) // Yes
{
Electron.App.Quit();
}
});
Electron.GlobalShortcut.Register("CommandOrControl+Shift+H", () =>
{
ToggleMainWindow();
});
```
### Dynamic Shortcut Management
```csharp
// Register shortcuts based on user preferences
public void RegisterUserShortcuts(Dictionary<string, Action> shortcuts)
{
foreach (var shortcut in shortcuts)
{
Electron.GlobalShortcut.Register(shortcut.Key, shortcut.Value);
}
}
// Check if shortcut is available
public async Task<bool> IsShortcutAvailable(string accelerator)
{
return await Electron.GlobalShortcut.IsRegisteredAsync(accelerator);
}
// Unregister specific shortcut
public void UnregisterShortcut(string accelerator)
{
Electron.GlobalShortcut.Unregister(accelerator);
}
```
### Platform-Specific Shortcuts
```csharp
// macOS specific shortcuts
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Electron.GlobalShortcut.Register("Command+Comma", () =>
{
OpenPreferences();
});
Electron.GlobalShortcut.Register("Command+H", () =>
{
Electron.App.Hide();
});
}
// Windows/Linux shortcuts
else
{
Electron.GlobalShortcut.Register("Ctrl+Shift+P", () =>
{
OpenPreferences();
});
Electron.GlobalShortcut.Register("Alt+F4", () =>
{
Electron.App.Quit();
});
}
```
### Shortcut Validation
```csharp
// Validate shortcuts before registration
public async Task<bool> TryRegisterShortcut(string accelerator, Action callback)
{
if (await Electron.GlobalShortcut.IsRegisteredAsync(accelerator))
{
Console.WriteLine($"Shortcut {accelerator} is already registered");
return false;
}
try
{
Electron.GlobalShortcut.Register(accelerator, callback);
Console.WriteLine($"Successfully registered shortcut: {accelerator}");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to register shortcut {accelerator}: {ex.Message}");
return false;
}
}
```
## Related APIs
- [Electron.App](App.md) - Application lifecycle events
- [Electron.Menu](Menu.md) - Menu-based shortcuts
- [Electron.WindowManager](WindowManager.md) - Window focus management
## Additional Resources
- [Electron GlobalShortcut Documentation](https://electronjs.org/docs/api/global-shortcut) - Official Electron global shortcut API

152
docs/API/HostHook.md Normal file
View File

@@ -0,0 +1,152 @@
# Electron.HostHook
Execute native JavaScript/TypeScript code from the host process.
## Overview
The `Electron.HostHook` API allows you to execute native JavaScript/TypeScript code from the host process. This enables advanced integration scenarios where you need to run custom JavaScript code or access Node.js APIs directly.
## Methods
#### 🧊 `void Call(string socketEventName, params dynamic[] arguments)`
Execute native JavaScript/TypeScript code synchronously.
**Parameters:**
- `socketEventName` - Socket name registered on the host
- `arguments` - Optional parameters
#### 🧊 `Task<T> CallAsync<T>(string socketEventName, params dynamic[] arguments)`
Execute native JavaScript/TypeScript code asynchronously with type-safe return values.
**Parameters:**
- `T` - Expected return type
- `socketEventName` - Socket name registered on the host
- `arguments` - Optional parameters
**Returns:**
Task<T> with the result from the executed host code.
## Usage Examples
### Basic Host Hook Execution
```csharp
// Execute simple JavaScript function
Electron.HostHook.Call("myFunction", "parameter1", 42);
// Execute with callback-style result
var result = await Electron.HostHook.CallAsync<string>("getUserName", userId);
Console.WriteLine($"User name: {result}");
```
### Advanced Integration
```csharp
// Call custom Electron API
var fileContent = await Electron.HostHook.CallAsync<string>("readFile", "config.json");
Console.WriteLine($"Config: {fileContent}");
// Execute with multiple parameters
var processedData = await Electron.HostHook.CallAsync<object[]>("processData", rawData, options);
// Call with complex objects
var settings = new { theme = "dark", language = "en" };
var updatedSettings = await Electron.HostHook.CallAsync<object>("updateSettings", settings);
```
### Error Handling
```csharp
try
{
// Execute host function with error handling
var result = await Electron.HostHook.CallAsync<string>("riskyOperation", inputData);
Console.WriteLine($"Success: {result}");
}
catch (Exception ex)
{
// Handle execution errors
Console.WriteLine($"Host hook error: {ex.Message}");
Electron.Dialog.ShowErrorBox("Operation Failed", "Could not execute host function.");
}
```
### Type-Safe Operations
```csharp
// Strongly typed return values
var userInfo = await Electron.HostHook.CallAsync<UserInfo>("getUserInfo", userId);
Console.WriteLine($"User: {userInfo.Name}, Email: {userInfo.Email}");
// Array results
var fileList = await Electron.HostHook.CallAsync<string[]>("listFiles", directoryPath);
foreach (var file in fileList)
{
Console.WriteLine($"File: {file}");
}
// Complex object results
var systemStats = await Electron.HostHook.CallAsync<SystemStatistics>("getSystemStats");
Console.WriteLine($"CPU: {systemStats.CpuUsage}%, Memory: {systemStats.MemoryUsage}%");
```
### Custom ElectronHostHook Setup
```csharp
// In your ElectronHostHook/index.ts
import { app } from 'electron';
export function getAppVersion(): string {
return app.getVersion();
}
export async function readConfigFile(): Promise<string> {
const fs = require('fs').promises;
return await fs.readFile('config.json', 'utf8');
}
export function customNotification(message: string): void {
// Custom notification logic
console.log(`Custom notification: ${message}`);
}
```
### Integration with .NET Code
```csharp
// Use host hook in your application logic
public async Task<string> GetApplicationVersion()
{
return await Electron.HostHook.CallAsync<string>("getAppVersion");
}
public async Task LoadConfiguration()
{
try
{
var config = await Electron.HostHook.CallAsync<ConfigObject>("readConfigFile");
ApplyConfiguration(config);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to load config: {ex.Message}");
UseDefaultConfiguration();
}
}
public void ShowCustomNotification(string message)
{
Electron.HostHook.Call("customNotification", message);
}
```
## Related APIs
- [Electron.IpcMain](IpcMain.md) - Inter-process communication
- [Electron.App](App.md) - Application lifecycle events
- [Electron.WebContents](WebContents.md) - Web content integration
## Additional Resources
- [Host Hook Documentation](../Core/Advanced-Migration-Topics.md) - Setting up custom host hooks

167
docs/API/IpcMain.md Normal file
View File

@@ -0,0 +1,167 @@
# Electron.IpcMain
Communicate asynchronously from the main process to renderer processes.
## Overview
The `Electron.IpcMain` API provides inter-process communication between the main process and renderer processes. It allows you to send messages, listen for events, and handle communication between different parts of your Electron application.
## Methods
#### 🧊 `Task On(string channel, Action<object> listener)`
Listens to channel, when a new message arrives listener would be called with listener(event, args...).
**Parameters:**
- `channel` - Channel name to listen on
- `listener` - Callback method to handle incoming messages
#### 🧊 `void OnSync(string channel, Func<object, object> listener)`
Send a message to the renderer process synchronously via channel. Note: Sending a synchronous message will block the whole renderer process.
**Parameters:**
- `channel` - Channel name to listen on
- `listener` - Synchronous callback method
#### 🧊 `void Once(string channel, Action<object> listener)`
Adds a one time listener method for the event. This listener is invoked only the next time a message is sent to channel, after which it is removed.
**Parameters:**
- `channel` - Channel name to listen on
- `listener` - Callback method to handle the message once
#### 🧊 `void RemoveAllListeners(string channel)`
Removes all listeners of the specified channel.
**Parameters:**
- `channel` - Channel name to remove listeners from
#### 🧊 `void Send(BrowserView browserView, string channel, params object[] data)`
Send a message to the BrowserView renderer process asynchronously via channel.
**Parameters:**
- `browserView` - Target browser view
- `channel` - Channel name to send on
- `data` - Arguments to send
#### 🧊 `void Send(BrowserWindow browserWindow, string channel, params object[] data)`
Send a message to the renderer process asynchronously via channel.
**Parameters:**
- `browserWindow` - Target browser window
- `channel` - Channel name to send on
- `data` - Arguments to send
## Usage Examples
### Basic Message Handling
```csharp
// Listen for messages from renderer
await Electron.IpcMain.On("request-data", (args) =>
{
Console.WriteLine($"Received request: {args}");
// Process the request and send response
});
// Send response back to renderer
Electron.IpcMain.Send(mainWindow, "data-response", processedData);
```
### Synchronous Communication
```csharp
// Handle synchronous requests
Electron.IpcMain.OnSync("get-user-info", (request) =>
{
var userId = request.ToString();
var userInfo = GetUserInfo(userId);
return userInfo;
});
```
### One-time Event Handling
```csharp
// Handle initialization request once
Electron.IpcMain.Once("app-initialized", (args) =>
{
Console.WriteLine("App initialized, setting up...");
InitializeApplication();
});
```
### Complex Data Exchange
```csharp
// Send complex data to renderer
var appData = new
{
Version = "1.0.0",
Features = new[] { "feature1", "feature2" },
Settings = new { Theme = "dark", Language = "en" }
};
Electron.IpcMain.Send(mainWindow, "app-config", appData);
// Listen for settings updates
await Electron.IpcMain.On("update-settings", (settings) =>
{
var config = JsonConvert.DeserializeObject<AppSettings>(settings.ToString());
ApplySettings(config);
});
```
### Multi-Window Communication
```csharp
// Send message to specific window
var settingsWindow = await Electron.WindowManager.CreateWindowAsync();
Electron.IpcMain.Send(settingsWindow, "show-settings", currentSettings);
// Broadcast to all windows
foreach (var window in Electron.WindowManager.BrowserWindows)
{
Electron.IpcMain.Send(window, "notification", message);
}
```
### Error Handling
```csharp
// Handle IPC errors gracefully
await Electron.IpcMain.On("risky-operation", async (args) =>
{
try
{
var result = await PerformRiskyOperation(args);
Electron.IpcMain.Send(mainWindow, "operation-success", result);
}
catch (Exception ex)
{
Electron.IpcMain.Send(mainWindow, "operation-error", ex.Message);
}
});
```
### Integration with Host Hooks
```csharp
// Use with custom host functionality
await Electron.IpcMain.On("execute-host-function", async (args) =>
{
var functionName = args.ToString();
var result = await Electron.HostHook.CallAsync<string>(functionName);
Electron.IpcMain.Send(mainWindow, "function-result", result);
});
```
## Related APIs
- [Electron.HostHook](HostHook.md) - Execute custom JavaScript functions
- [Electron.WindowManager](WindowManager.md) - Target specific windows for communication
- [Electron.WebContents](WebContents.md) - Send messages to web content
## Additional Resources
- [Electron IPC Documentation](https://electronjs.org/docs/api/ipc-main) - Official Electron IPC API

210
docs/API/Menu.md Normal file
View File

@@ -0,0 +1,210 @@
# Electron.Menu
Create application menus, context menus, and menu items with full keyboard shortcut support.
## Overview
The `Electron.Menu` API provides comprehensive control over application menus and context menus. It supports native platform menus with custom menu items, submenus, keyboard shortcuts, and role-based menu items.
## Properties
#### 📋 `IReadOnlyDictionary<int, ReadOnlyCollection<MenuItem>> ContextMenuItems`
Gets a read-only dictionary of all current context menu items, keyed by browser window ID.
#### 📋 `IReadOnlyCollection<MenuItem> MenuItems`
Gets a read-only collection of all current application menu items.
## Methods
#### 🧊 `void ContextMenuPopup(BrowserWindow browserWindow)`
Shows the context menu for the specified browser window.
**Parameters:**
- `browserWindow` - The browser window to show the context menu for
#### 🧊 `void SetApplicationMenu(MenuItem[] menuItems)`
Sets the application menu for the entire application.
**Parameters:**
- `menuItems` - Array of MenuItem objects defining the application menu
#### 🧊 `void SetContextMenu(BrowserWindow browserWindow, MenuItem[] menuItems)`
Sets a context menu for a specific browser window.
**Parameters:**
- `browserWindow` - The browser window to attach the context menu to
- `menuItems` - Array of MenuItem objects defining the context menu
## Usage Examples
### Application Menu
```csharp
// Create application menu
var menuItems = new[]
{
new MenuItem
{
Label = "File",
Submenu = new[]
{
new MenuItem { Label = "New", Click = () => CreateNewDocument() },
new MenuItem { Label = "Open", Click = () => OpenDocument() },
new MenuItem { Type = MenuType.Separator },
new MenuItem { Label = "Exit", Click = () => Electron.App.Quit() }
}
},
new MenuItem
{
Label = "Edit",
Submenu = new[]
{
new MenuItem { Role = MenuRole.Undo },
new MenuItem { Role = MenuRole.Redo },
new MenuItem { Type = MenuType.Separator },
new MenuItem { Role = MenuRole.Cut },
new MenuItem { Role = MenuRole.Copy },
new MenuItem { Role = MenuRole.Paste }
}
},
new MenuItem
{
Label = "View",
Submenu = new[]
{
new MenuItem { Role = MenuRole.Reload },
new MenuItem { Role = MenuRole.ForceReload },
new MenuItem { Role = MenuRole.ToggleDevTools },
new MenuItem { Type = MenuType.Separator },
new MenuItem { Role = MenuRole.ResetZoom },
new MenuItem { Role = MenuRole.ZoomIn },
new MenuItem { Role = MenuRole.ZoomOut }
}
},
new MenuItem
{
Label = "Window",
Submenu = new[]
{
new MenuItem { Role = MenuRole.Minimize },
new MenuItem { Role = MenuRole.Close }
}
}
};
// Set application menu
Electron.Menu.SetApplicationMenu(menuItems);
```
### Context Menu
```csharp
// Create context menu for specific window
var contextMenuItems = new[]
{
new MenuItem { Label = "Copy", Click = () => CopySelectedText() },
new MenuItem { Label = "Paste", Click = () => PasteText() },
new MenuItem { Type = MenuType.Separator },
new MenuItem { Label = "Inspect Element", Click = () => InspectElement() }
};
// Set context menu for window
Electron.Menu.SetContextMenu(mainWindow, contextMenuItems);
// Show context menu programmatically
Electron.Menu.ContextMenuPopup(mainWindow);
```
### Menu with Keyboard Shortcuts
```csharp
// Create menu with keyboard shortcuts
var menuItems = new[]
{
new MenuItem
{
Label = "File",
Submenu = new[]
{
new MenuItem
{
Label = "New",
Accelerator = "CmdOrCtrl+N",
Click = () => CreateNewDocument()
},
new MenuItem
{
Label = "Open",
Accelerator = "CmdOrCtrl+O",
Click = () => OpenDocument()
},
new MenuItem
{
Label = "Save",
Accelerator = "CmdOrCtrl+S",
Click = () => SaveDocument()
}
}
}
};
Electron.Menu.SetApplicationMenu(menuItems);
```
### Dynamic Menu Updates
```csharp
// Update menu items dynamically
var fileMenu = Electron.Menu.MenuItems.FirstOrDefault(m => m.Label == "File");
if (fileMenu?.Submenu != null)
{
var saveItem = fileMenu.Submenu.FirstOrDefault(m => m.Label == "Save");
if (saveItem != null)
{
saveItem.Enabled = HasUnsavedChanges;
}
}
```
### Platform-Specific Menus
```csharp
// macOS specific menu items
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var macMenuItems = new[]
{
new MenuItem
{
Label = "MyApp",
Submenu = new[]
{
new MenuItem { Role = MenuRole.About },
new MenuItem { Type = MenuType.Separator },
new MenuItem { Role = MenuRole.Services },
new MenuItem { Type = MenuType.Separator },
new MenuItem { Role = MenuRole.Hide },
new MenuItem { Role = MenuRole.HideOthers },
new MenuItem { Role = MenuRole.Unhide },
new MenuItem { Type = MenuType.Separator },
new MenuItem { Role = MenuRole.Quit }
}
}
};
// Insert before File menu
var allMenus = new List<MenuItem>(macMenuItems);
allMenus.AddRange(menuItems);
Electron.Menu.SetApplicationMenu(allMenus.ToArray());
}
```
## Related APIs
- [Electron.WindowManager](WindowManager.md) - Windows for context menus
- [Electron.App](App.md) - Application lifecycle events
- [Electron.GlobalShortcut](GlobalShortcut.md) - Global keyboard shortcuts
## Additional Resources
- [Electron Menu Documentation](https://electronjs.org/docs/api/menu) - Official Electron menu API

189
docs/API/NativeTheme.md Normal file
View File

@@ -0,0 +1,189 @@
# Electron.NativeTheme
Detect and respond to changes in Chromium's native color theme.
## Overview
The `Electron.NativeTheme` API provides access to Chromium's native color theme information and allows you to detect and respond to changes in the system's dark/light mode settings. This enables your application to automatically adapt to the user's theme preferences.
## Methods
#### 🧊 `Task<ThemeSourceMode> GetThemeSourceAsync()`
Get the current theme source setting.
**Returns:**
A `ThemeSourceMode` property that can be `ThemeSourceMode.System`, `ThemeSourceMode.Light` or `ThemeSourceMode.Dark`.
#### 🧊 `void SetThemeSource(ThemeSourceMode themeSourceMode)`
Setting this property to `ThemeSourceMode.System` will remove the override and everything will be reset to the OS default. By default 'ThemeSource' is `ThemeSourceMode.System`.
**Parameters:**
- `themeSourceMode` - The new ThemeSource
#### 🧊 `Task<bool> ShouldUseDarkColorsAsync()`
Check if the system is currently using dark colors.
**Returns:**
A bool for if the OS / Chromium currently has a dark mode enabled or is being instructed to show a dark-style UI.
#### 🧊 `Task<bool> ShouldUseHighContrastColorsAsync()`
Check if the system is currently using high contrast colors.
**Returns:**
A bool for if the OS / Chromium currently has high-contrast mode enabled or is being instructed to show a high-contrast UI.
#### 🧊 `Task<bool> ShouldUseInvertedColorSchemeAsync()`
Check if the system is currently using an inverted color scheme.
**Returns:**
A bool for if the OS / Chromium currently has an inverted color scheme or is being instructed to use an inverted color scheme.
## Events
#### ⚡ `Updated`
Emitted when something in the underlying NativeTheme has changed. This normally means that either the value of ShouldUseDarkColorsAsync, ShouldUseHighContrastColorsAsync or ShouldUseInvertedColorSchemeAsync has changed.
## Usage Examples
### Basic Theme Detection
```csharp
// Check current theme
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
Console.WriteLine($"Dark mode: {isDarkMode}");
// Get current theme source
var themeSource = await Electron.NativeTheme.GetThemeSourceAsync();
Console.WriteLine($"Theme source: {themeSource}");
```
### Theme Change Monitoring
```csharp
// Monitor theme changes
Electron.NativeTheme.Updated += () =>
{
Console.WriteLine("Theme updated");
UpdateApplicationTheme();
};
async void UpdateApplicationTheme()
{
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
var isHighContrast = await Electron.NativeTheme.ShouldUseHighContrastColorsAsync();
// Update application appearance
ApplyTheme(isDarkMode, isHighContrast);
}
```
### Manual Theme Control
```csharp
// Force dark theme
Electron.NativeTheme.SetThemeSource(ThemeSourceMode.Dark);
// Force light theme
Electron.NativeTheme.SetThemeSource(ThemeSourceMode.Light);
// Follow system theme
Electron.NativeTheme.SetThemeSource(ThemeSourceMode.System);
```
### Application Theme Integration
```csharp
public async Task InitializeThemeSupport()
{
// Set initial theme based on system preference
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
ApplyTheme(isDarkMode);
// Monitor theme changes
Electron.NativeTheme.Updated += async () =>
{
var darkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
ApplyTheme(darkMode);
};
}
private void ApplyTheme(bool isDarkMode)
{
if (isDarkMode)
{
// Apply dark theme
SetDarkThemeColors();
UpdateWindowTheme("dark");
}
else
{
// Apply light theme
SetLightThemeColors();
UpdateWindowTheme("light");
}
}
```
### Advanced Theme Management
```csharp
// Check all theme properties
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
var isHighContrast = await Electron.NativeTheme.ShouldUseHighContrastColorsAsync();
var isInverted = await Electron.NativeTheme.ShouldUseInvertedColorSchemeAsync();
Console.WriteLine($"Dark mode: {isDarkMode}");
Console.WriteLine($"High contrast: {isHighContrast}");
Console.WriteLine($"Inverted: {isInverted}");
// Apply appropriate theme
if (isHighContrast)
{
ApplyHighContrastTheme();
}
else if (isDarkMode)
{
ApplyDarkTheme();
}
else
{
ApplyLightTheme();
}
```
### Theme-Aware Window Creation
```csharp
// Create window with theme-appropriate settings
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
var windowOptions = new BrowserWindowOptions
{
Width = 1200,
Height = 800,
Title = "My Application",
BackgroundColor = isDarkMode ? "#1a1a1a" : "#ffffff",
WebPreferences = new WebPreferences
{
// Additional web preferences based on theme
}
};
var window = await Electron.WindowManager.CreateWindowAsync(windowOptions);
```
## Related APIs
- [Electron.WindowManager](WindowManager.md) - Apply theme to windows
- [Electron.Screen](Screen.md) - Screen-related theme considerations
- [Electron.App](App.md) - Application-level theme events
## Additional Resources
- [Electron NativeTheme Documentation](https://electronjs.org/docs/api/native-theme) - Official Electron native theme API
- [Theme Support](../Core/What's-New.md) - Understanding theme functionality
- [User Experience](../Using/Configuration.md) - Design theme-aware applications

164
docs/API/Notification.md Normal file
View File

@@ -0,0 +1,164 @@
# Electron.Notification
Show native desktop notifications with custom content and actions.
## Overview
The `Electron.Notification` API provides the ability to show native desktop notifications with custom titles, bodies, icons, and actions. Notifications work across Windows, macOS, and Linux with platform-specific behavior.
## Methods
#### 🧊 `Task<bool> IsSupportedAsync()`
Check if desktop notifications are supported on the current platform.
**Returns:**
Whether or not desktop notifications are supported on the current system.
#### 🧊 `void Show(NotificationOptions notificationOptions)`
Create OS desktop notifications with the specified options.
**Parameters:**
- `notificationOptions` - Notification configuration options
## Usage Examples
### Basic Notification
```csharp
// Simple notification
Electron.Notification.Show(new NotificationOptions
{
Title = "My Application",
Body = "This is a notification message",
Icon = "assets/notification-icon.png"
});
```
### Notification with Actions
```csharp
// Notification with reply action
Electron.Notification.Show(new NotificationOptions
{
Title = "New Message",
Body = "You have a new message from John",
Icon = "assets/message-icon.png",
Actions = new[]
{
new NotificationAction { Text = "Reply", Type = NotificationActionType.Button },
new NotificationAction { Text = "View", Type = NotificationActionType.Button }
},
OnClick = () => OpenMessageWindow(),
OnAction = (action) =>
{
if (action == "Reply")
{
ShowReplyDialog();
}
else if (action == "View")
{
OpenMessageWindow();
}
}
});
```
### Rich Notifications
```csharp
// Rich notification with all options
Electron.Notification.Show(new NotificationOptions
{
Title = "Download Complete",
Subtitle = "Your file has finished downloading",
Body = "document.pdf has been downloaded to your Downloads folder.",
Icon = "assets/download-icon.png",
ImageUrl = "file://" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets/preview.png"),
Sound = NotificationSound.Default,
Urgency = NotificationUrgency.Normal,
Category = "transfer.complete",
Tag = "download-123",
Actions = new[]
{
new NotificationAction { Text = "Open", Type = NotificationActionType.Button },
new NotificationAction { Text = "Show in Folder", Type = NotificationActionType.Button }
},
OnShow = () => Console.WriteLine("Notification shown"),
OnClick = () => OpenDownloadedFile(),
OnClose = () => Console.WriteLine("Notification closed"),
OnAction = (action) =>
{
if (action == "Open")
{
OpenDownloadedFile();
}
else if (action == "Show in Folder")
{
ShowInFolder();
}
}
});
```
### Platform-Specific Notifications
```csharp
// Windows toast notification
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Electron.Notification.Show(new NotificationOptions
{
Title = "Background Task",
Body = "Your backup is complete",
Icon = "assets/app-icon.ico",
Tag = "backup-complete",
RequireInteraction = true
});
}
// macOS notification with sound
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Electron.Notification.Show(new NotificationOptions
{
Title = "Alert",
Body = "Something needs your attention",
Sound = NotificationSound.Default,
Actions = new[]
{
new NotificationAction { Text = "View", Type = NotificationActionType.Button }
}
});
}
```
### Notification Management
```csharp
// Check notification support
var isSupported = await Electron.Notification.IsSupportedAsync();
Console.WriteLine($"Notifications supported: {isSupported}");
// Create notification with events
var notification = new NotificationOptions
{
Title = "Task Complete",
Body = "Your long-running task has finished",
OnShow = () => Console.WriteLine("Notification displayed"),
OnClick = () => OpenTaskResults(),
OnClose = () => Console.WriteLine("Notification dismissed")
};
Electron.Notification.Show(notification);
```
## Related APIs
- [Electron.App](App.md) - Application lifecycle events
- [Electron.Tray](Tray.md) - System tray integration with notifications
- [Electron.Screen](Screen.md) - Position notifications based on screen layout
## Additional Resources
- [Electron Notification Documentation](https://electronjs.org/docs/api/notification) - Official Electron notification API

62
docs/API/Overview.md Normal file
View File

@@ -0,0 +1,62 @@
# API Reference Overview
The ElectronNET.Core API provides comprehensive access to Electron's native desktop functionality through a .NET interface. This section documents all the available API classes and their methods, events, and usage patterns.
## API Classes
### Core Application Management
- **[Electron.App](App.md)** - Control your application's event lifecycle, manage app metadata, and handle system-level operations
- **[Electron.WindowManager](WindowManager.md)** - Create and manage browser windows, control window behavior and appearance
- **[Electron.Menu](Menu.md)** - Create application menus, context menus, and menu items with full keyboard shortcut support
### User Interface & Interaction
- **[Electron.Dialog](Dialog.md)** - Display native system dialogs for opening/saving files, showing messages and alerts
- **[Electron.Notification](Notification.md)** - Show native desktop notifications with custom content and actions
- **[Electron.Tray](Tray.md)** - Create system tray icons with context menus and tooltip support
- **[Electron.Dock](Dock.md)** - macOS dock integration for bounce effects and badge counts
### System Integration
- **[Electron.Shell](Shell.md)** - Desktop integration for opening files, URLs, and accessing system paths
- **[Electron.Clipboard](Clipboard.md)** - Read from and write to the system clipboard with multiple data formats
- **[Electron.Screen](Screen.md)** - Access display and screen information for responsive layouts
- **[Electron.NativeTheme](NativeTheme.md)** - Detect and respond to system theme changes (light/dark mode)
### Communication & Automation
- **[Electron.IpcMain](IpcMain.md)** - Inter-process communication between main process and renderer processes
- **[Electron.HostHook](HostHook.md)** - Custom host hook functionality for advanced integration scenarios
- **[Electron.GlobalShortcut](GlobalShortcut.md)** - Register global keyboard shortcuts that work even when app is not focused
- **[Electron.AutoUpdater](AutoUpdater.md)** - Handle application updates and installation processes
### System Monitoring
- **[Electron.PowerMonitor](PowerMonitor.md)** - Monitor system power events like sleep, wake, and battery status
## API Relationships
### Window and Dialog Integration
- Use `BrowserWindow` instances as parent windows for dialogs
- Dialogs automatically become modal when parent window is provided
- Window events coordinate with application lifecycle events
### IPC Communication
- `IpcMain` handles communication from renderer processes
- Use with `Electron.WindowManager` for window-specific messaging
- Coordinate with `Electron.App` events for application-wide communication
### System Integration
- `Shell` operations work with file paths from `Dialog` operations
- `Screen` information helps create properly sized windows
- `Notification` and `Tray` provide complementary user interaction methods
## 🚀 Next Steps
- **[Electron.App](App.md)** - Start with application lifecycle management
- **[Electron.WindowManager](WindowManager.md)** - Learn window creation and management
- **[Electron.Dialog](Dialog.md)** - Add file operations and user interactions
- **[Electron.Menu](Menu.md)** - Implement application menus and shortcuts
## 📚 Additional Resources
- **[Electron Documentation](https://electronjs.org/docs)** - Official Electron API reference
- **[Getting Started](../GettingStarted/ASP.Net.md)** - Development setup guides
- **[Migration Guide](../Core/Migration-Guide.md)** - Moving from previous versions

188
docs/API/PowerMonitor.md Normal file
View File

@@ -0,0 +1,188 @@
# Electron.PowerMonitor
Monitor system power events like sleep, wake, and battery status.
## Overview
The `Electron.PowerMonitor` API provides access to system power events and state changes. This includes monitoring when the system is going to sleep, waking up, or changing power sources.
## Events
#### ⚡ `OnAC`
Emitted when the system changes to AC power.
#### ⚡ `OnBattery`
Emitted when system changes to battery power.
#### ⚡ `OnLockScreen`
Emitted when the system is about to lock the screen.
#### ⚡ `OnResume`
Emitted when system is resuming.
#### ⚡ `OnShutdown`
Emitted when the system is about to reboot or shut down.
#### ⚡ `OnSuspend`
Emitted when the system is suspending.
#### ⚡ `OnUnLockScreen`
Emitted when the system is about to unlock the screen.
## Usage Examples
### Basic Power Event Monitoring
```csharp
// Monitor system sleep/wake
Electron.PowerMonitor.OnSuspend += () =>
{
Console.WriteLine("System going to sleep");
// Save application state
SaveApplicationState();
};
Electron.PowerMonitor.OnResume += () =>
{
Console.WriteLine("System waking up");
// Restore application state
RestoreApplicationState();
};
```
### Screen Lock/Unlock Monitoring
```csharp
// Handle screen lock events
Electron.PowerMonitor.OnLockScreen += () =>
{
Console.WriteLine("Screen locking");
// Pause real-time operations
PauseRealTimeOperations();
};
Electron.PowerMonitor.OnUnLockScreen += () =>
{
Console.WriteLine("Screen unlocking");
// Resume real-time operations
ResumeRealTimeOperations();
};
```
### Power Source Changes
```csharp
// Monitor power source changes
Electron.PowerMonitor.OnAC += () =>
{
Console.WriteLine("Switched to AC power");
// Adjust power-intensive operations
EnablePowerIntensiveFeatures();
};
Electron.PowerMonitor.OnBattery += () =>
{
Console.WriteLine("Switched to battery power");
// Reduce power consumption
EnablePowerSavingMode();
};
```
### System Shutdown Handling
```csharp
// Handle system shutdown
Electron.PowerMonitor.OnShutdown += () =>
{
Console.WriteLine("System shutting down");
// Save critical data and exit gracefully
SaveAndExit();
};
```
### Application State Management
```csharp
private bool isSuspended = false;
public void InitializePowerMonitoring()
{
// Track suspension state
Electron.PowerMonitor.OnSuspend += () =>
{
isSuspended = true;
OnSystemSleep();
};
Electron.PowerMonitor.OnResume += () =>
{
isSuspended = false;
OnSystemWake();
};
// Handle screen lock for security
Electron.PowerMonitor.OnLockScreen += () =>
{
OnScreenLocked();
};
}
private void OnSystemSleep()
{
// Pause network operations
PauseNetworkOperations();
// Save unsaved work
AutoSaveDocuments();
// Reduce resource usage
MinimizeResourceUsage();
}
private void OnSystemWake()
{
// Resume network operations
ResumeNetworkOperations();
// Check for updates
CheckForUpdates();
// Restore full functionality
RestoreFullFunctionality();
}
private void OnScreenLocked()
{
// Hide sensitive information
HideSensitiveData();
// Pause real-time features
PauseRealTimeFeatures();
}
```
### Battery Status Monitoring
```csharp
// Monitor battery status changes
Electron.PowerMonitor.OnAC += () =>
{
Console.WriteLine("Plugged in - full performance mode");
EnableFullPerformanceMode();
};
Electron.PowerMonitor.OnBattery += () =>
{
Console.WriteLine("On battery - power saving mode");
EnablePowerSavingMode();
};
```
## Related APIs
- [Electron.App](App.md) - Application lifecycle events
- [Electron.Notification](Notification.md) - Notify users about power events
## Additional Resources
- [Electron PowerMonitor Documentation](https://electronjs.org/docs/api/power-monitor) - Official Electron power monitor API

174
docs/API/Screen.md Normal file
View File

@@ -0,0 +1,174 @@
# Electron.Screen
Access display and screen information for responsive layouts.
## Overview
The `Electron.Screen` API provides access to screen and display information, including screen size, display metrics, cursor position, and multi-monitor configurations. This is essential for creating responsive applications that adapt to different screen configurations.
## Methods
#### 🧊 `Task<Display[]> GetAllDisplaysAsync()`
Gets information about all available displays.
**Returns:**
An array of displays that are currently available.
#### 🧊 `Task<Point> GetCursorScreenPointAsync()`
Gets the current position of the mouse cursor on screen.
**Returns:**
The current absolute position of the mouse pointer.
#### 🧊 `Task<Display> GetDisplayMatchingAsync(Rectangle rectangle)`
Gets the display that most closely intersects the provided bounds.
**Parameters:**
- `rectangle` - The rectangle to find the matching display for
**Returns:**
The display that most closely intersects the provided bounds.
#### 🧊 `Task<Display> GetDisplayNearestPointAsync(Point point)`
Gets the display that is closest to the specified point.
**Parameters:**
- `point` - The point to find the nearest display for
**Returns:**
The display nearest the specified point.
#### 🧊 `Task<int> GetMenuBarHeightAsync()`
macOS: The height of the menu bar in pixels.
**Returns:**
The height of the menu bar in pixels.
#### 🧊 `Task<Display> GetPrimaryDisplayAsync()`
Gets information about the primary display (main screen).
**Returns:**
The primary display.
## Events
#### ⚡ `OnDisplayAdded`
Emitted when a new Display has been added.
#### ⚡ `OnDisplayMetricsChanged`
Emitted when one or more metrics change in a display. The changedMetrics is an array of strings that describe the changes. Possible changes are bounds, workArea, scaleFactor and rotation.
#### ⚡ `OnDisplayRemoved`
Emitted when oldDisplay has been removed.
## Usage Examples
### Display Information
```csharp
// Get primary display
var primaryDisplay = await Electron.Screen.GetPrimaryDisplayAsync();
Console.WriteLine($"Primary display: {primaryDisplay.Size.Width}x{primaryDisplay.Size.Height}");
// Get all displays
var displays = await Electron.Screen.GetAllDisplaysAsync();
Console.WriteLine($"Available displays: {displays.Length}");
// Get display near cursor
var cursorPoint = await Electron.Screen.GetCursorScreenPointAsync();
var nearestDisplay = await Electron.Screen.GetDisplayNearestPointAsync(cursorPoint);
Console.WriteLine($"Nearest display scale factor: {nearestDisplay.ScaleFactor}");
```
### Multi-Monitor Setup
```csharp
// Get all displays for multi-monitor setup
var displays = await Electron.Screen.GetAllDisplaysAsync();
foreach (var display in displays)
{
Console.WriteLine($"Display {display.Id}:");
Console.WriteLine($" Size: {display.Size.Width}x{display.Size.Height}");
Console.WriteLine($" Position: {display.Bounds.X},{display.Bounds.Y}");
Console.WriteLine($" Scale Factor: {display.ScaleFactor}");
Console.WriteLine($" Work Area: {display.WorkArea.Width}x{display.WorkArea.Height}");
}
```
### Responsive Window Placement
```csharp
// Create window on appropriate display
var displays = await Electron.Screen.GetAllDisplaysAsync();
var targetDisplay = displays.FirstOrDefault(d => d.Bounds.X > 0) ?? displays.First();
var windowOptions = new BrowserWindowOptions
{
Width = Math.Min(1200, targetDisplay.WorkArea.Width),
Height = Math.Min(800, targetDisplay.WorkArea.Height),
X = targetDisplay.WorkArea.X + (targetDisplay.WorkArea.Width - 1200) / 2,
Y = targetDisplay.WorkArea.Y + (targetDisplay.WorkArea.Height - 800) / 2
};
var window = await Electron.WindowManager.CreateWindowAsync(windowOptions);
```
### Display Change Monitoring
```csharp
// Monitor display changes
Electron.Screen.OnDisplayAdded += (display) =>
{
Console.WriteLine($"Display added: {display.Id}");
UpdateWindowPositions();
};
Electron.Screen.OnDisplayRemoved += (display) =>
{
Console.WriteLine($"Display removed: {display.Id}");
UpdateWindowPositions();
};
Electron.Screen.OnDisplayMetricsChanged += (display, metrics) =>
{
Console.WriteLine($"Display {display.Id} metrics changed: {string.Join(", ", metrics)}");
UpdateWindowPositions();
};
void UpdateWindowPositions()
{
// Recalculate window positions based on current displays
}
```
### macOS Menu Bar Height
```csharp
// Account for menu bar height on macOS
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var menuBarHeight = await Electron.Screen.GetMenuBarHeightAsync();
var windowOptions = new BrowserWindowOptions
{
Y = menuBarHeight, // Position below menu bar
TitleBarStyle = TitleBarStyle.Hidden // Hide title bar for custom look
};
}
```
## Related APIs
- [Electron.WindowManager](WindowManager.md) - Position windows based on screen information
- [Electron.App](App.md) - Handle display-related application events
## Additional Resources
- [Electron Screen Documentation](https://electronjs.org/docs/api/screen) - Official Electron screen API

175
docs/API/Shell.md Normal file
View File

@@ -0,0 +1,175 @@
# Electron.Shell
Desktop integration for opening files, URLs, and accessing system paths.
## Overview
The `Electron.Shell` API provides system integration functionality for opening files and URLs with their default applications, managing trash/recycle bin, and creating/reading shortcut links.
## Methods
#### 🧊 `void Beep()`
Play the beep sound.
#### 🧊 `Task<string> OpenExternalAsync(string url)`
Open the given external protocol URL in the desktop's default manner (e.g., mailto: URLs in the user's default mail agent).
**Parameters:**
- `url` - Max 2081 characters on windows
**Returns:**
The error message corresponding to the failure if a failure occurred, otherwise empty string.
#### 🧊 `Task<string> OpenExternalAsync(string url, OpenExternalOptions options)`
Open the given external protocol URL with additional options.
**Parameters:**
- `url` - Max 2081 characters on windows
- `options` - Controls the behavior of OpenExternal
**Returns:**
The error message corresponding to the failure if a failure occurred, otherwise empty string.
#### 🧊 `Task<string> OpenPathAsync(string path)`
Open the given file in the desktop's default manner.
**Parameters:**
- `path` - The path to the directory or file
**Returns:**
The error message corresponding to the failure if a failure occurred, otherwise empty string.
#### 🧊 `Task<ShortcutDetails> ReadShortcutLinkAsync(string shortcutPath)`
Resolves the shortcut link at shortcutPath. An exception will be thrown when any error happens.
**Parameters:**
- `shortcutPath` - The path to the shortcut
**Returns:**
ShortcutDetails of the shortcut.
#### 🧊 `Task ShowItemInFolderAsync(string fullPath)`
Show the given file in a file manager. If possible, select the file.
**Parameters:**
- `fullPath` - The full path to the directory or file
#### 🧊 `Task<bool> TrashItemAsync(string fullPath)`
Move the given file to trash and returns a bool status for the operation.
**Parameters:**
- `fullPath` - The full path to the directory or file
**Returns:**
Whether the item was successfully moved to the trash.
#### 🧊 `Task<bool> WriteShortcutLinkAsync(string shortcutPath, ShortcutLinkOperation operation, ShortcutDetails options)`
Creates or updates a shortcut link at shortcutPath.
**Parameters:**
- `shortcutPath` - The path to the shortcut
- `operation` - Default is ShortcutLinkOperation.Create
- `options` - Structure of a shortcut
**Returns:**
Whether the shortcut was created successfully.
## Usage Examples
### File Operations
```csharp
// Open file with default application
var error = await Electron.Shell.OpenPathAsync(filePath);
if (string.IsNullOrEmpty(error))
{
Console.WriteLine("File opened successfully");
}
else
{
Console.WriteLine($"Failed to open file: {error}");
}
// Show file in file manager
await Electron.Shell.ShowItemInFolderAsync(filePath);
// Move file to trash
var trashed = await Electron.Shell.TrashItemAsync(filePath);
Console.WriteLine($"File trashed: {trashed}");
```
### URL Operations
```csharp
// Open URL in default browser
var error = await Electron.Shell.OpenExternalAsync("https://electron.net");
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine($"Failed to open URL: {error}");
}
// Open email client
await Electron.Shell.OpenExternalAsync("mailto:user@example.com");
// Open with options
var error = await Electron.Shell.OpenExternalAsync("https://example.com", new OpenExternalOptions
{
Activate = true
});
```
### System Integration
```csharp
// Play system beep
Electron.Shell.Beep();
// Create desktop shortcut
var success = await Electron.Shell.WriteShortcutLinkAsync(
@"C:\Users\Public\Desktop\MyApp.lnk",
ShortcutLinkOperation.Create,
new ShortcutDetails
{
Target = "C:\\Program Files\\MyApp\\MyApp.exe",
Description = "My Application",
WorkingDirectory = "C:\\Program Files\\MyApp"
}
);
// Read shortcut information
var details = await Electron.Shell.ReadShortcutLinkAsync(@"C:\Users\Public\Desktop\MyApp.lnk");
Console.WriteLine($"Target: {details.Target}");
```
### Integration with Dialog API
```csharp
// Use with file dialog results
var files = await Electron.Dialog.ShowOpenDialogAsync(window, options);
if (files.Length > 0)
{
var selectedFile = files[0];
// Open the selected file
await Electron.Shell.OpenPathAsync(selectedFile);
// Show in file manager
await Electron.Shell.ShowItemInFolderAsync(selectedFile);
}
```
## Related APIs
- [Electron.Dialog](Dialog.md) - Select files to open with Shell
- [Electron.App](App.md) - Application lifecycle events
- [Electron.Clipboard](Clipboard.md) - Copy file paths for Shell operations
## Additional Resources
- [Electron Shell Documentation](https://electronjs.org/docs/api/shell) - Official Electron shell API

232
docs/API/Tray.md Normal file
View File

@@ -0,0 +1,232 @@
# Electron.Tray
Add icons and context menus to the system's notification area.
## Overview
The `Electron.Tray` API provides the ability to add icons and context menus to the system's notification area (system tray). This allows applications to provide quick access to common functions and maintain a presence in the system even when windows are closed.
## Properties
#### 📋 `IReadOnlyCollection<MenuItem> MenuItems`
Gets a read-only collection of all current tray menu items.
## Methods
#### 🧊 `void Destroy()`
Destroys the tray icon immediately.
#### 🧊 `void DisplayBalloon(DisplayBalloonOptions options)`
Windows: Displays a tray balloon notification.
**Parameters:**
- `options` - Balloon notification options
#### 🧊 `Task<bool> IsDestroyedAsync()`
Check if the tray icon has been destroyed.
**Returns:**
Whether the tray icon is destroyed.
#### 🧊 `void SetImage(string image)`
Sets the image associated with this tray icon.
**Parameters:**
- `image` - New image for the tray icon
#### 🧊 `void SetPressedImage(string image)`
Sets the image associated with this tray icon when pressed on macOS.
**Parameters:**
- `image` - Image for pressed state
#### 🧊 `void SetTitle(string title)`
macOS: Sets the title displayed aside of the tray icon in the status bar.
**Parameters:**
- `title` - Title text
#### 🧊 `void SetToolTip(string toolTip)`
Sets the hover text for this tray icon.
**Parameters:**
- `toolTip` - Tooltip text
#### 🧊 `void Show(string image)`
Shows the tray icon without a context menu.
**Parameters:**
- `image` - The image to use for the tray icon
#### 🧊 `void Show(string image, MenuItem menuItem)`
Shows the tray icon with a single menu item.
**Parameters:**
- `image` - The image to use for the tray icon
- `menuItem` - Single menu item for the tray context menu
#### 🧊 `void Show(string image, MenuItem[] menuItems)`
Shows the tray icon with multiple menu items.
**Parameters:**
- `image` - The image to use for the tray icon
- `menuItems` - Array of menu items for the tray context menu
## Events
#### ⚡ `OnBalloonClick`
Windows: Emitted when the tray balloon is clicked.
#### ⚡ `OnBalloonClosed`
Windows: Emitted when the tray balloon is closed because of timeout or user manually closes it.
#### ⚡ `OnBalloonShow`
Windows: Emitted when the tray balloon shows.
#### ⚡ `OnClick`
Emitted when the tray icon is clicked.
#### ⚡ `OnDoubleClick`
macOS, Windows: Emitted when the tray icon is double clicked.
#### ⚡ `OnRightClick`
macOS, Windows: Emitted when the tray icon is right clicked.
## Usage Examples
### Basic Tray Icon
```csharp
// Simple tray icon
await Electron.Tray.Show("assets/tray-icon.png");
// Tray icon with single menu item
await Electron.Tray.Show("assets/tray-icon.png", new MenuItem
{
Label = "Show Window",
Click = () => ShowMainWindow()
});
```
### Tray with Context Menu
```csharp
// Tray 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);
```
### Dynamic Tray Updates
```csharp
// Update tray tooltip based on status
await Electron.Tray.SetToolTip("MyApp - Connected");
// Change tray icon based on state
if (isConnected)
{
await Electron.Tray.SetImage("assets/connected.png");
}
else
{
await Electron.Tray.SetImage("assets/disconnected.png");
}
```
### Tray Event Handling
```csharp
// Handle tray clicks
Electron.Tray.OnClick += (clickArgs, bounds) =>
{
if (clickArgs.AltKey || clickArgs.ShiftKey)
{
// Alt+Click or Shift+Click - show context menu
Electron.Menu.ContextMenuPopup(Electron.WindowManager.BrowserWindows.First());
}
else
{
// Regular click - toggle main window
ToggleMainWindow();
}
};
Electron.Tray.OnRightClick += (clickArgs, bounds) =>
{
// Show context menu on right click
Electron.Menu.ContextMenuPopup(Electron.WindowManager.BrowserWindows.First());
};
```
### Windows Balloon Notifications
```csharp
// Show Windows balloon notification
await Electron.Tray.DisplayBalloon(new DisplayBalloonOptions
{
Title = "Background Task Complete",
Content = "Your file has been processed successfully.",
Icon = "assets/notification-icon.ico"
});
// Handle balloon events
Electron.Tray.OnBalloonClick += () =>
{
ShowMainWindow();
Electron.WindowManager.BrowserWindows.First().Focus();
};
```
### macOS Tray Features
```csharp
// macOS specific tray features
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
await Electron.Tray.SetTitle("MyApp");
// Use template image for dark mode support
await Electron.Tray.SetImage("assets/tray-template.png");
await Electron.Tray.SetPressedImage("assets/tray-pressed-template.png");
}
```
### Application Integration
```csharp
// Integrate with application lifecycle
Electron.App.WindowAllClosed += () =>
{
// Keep app running in tray when windows are closed
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Electron.App.Hide();
}
};
// Handle tray double-click
Electron.Tray.OnDoubleClick += (clickArgs, bounds) =>
{
ShowMainWindow();
Electron.WindowManager.BrowserWindows.First().Focus();
};
```
## Related APIs
- [Electron.Menu](Menu.md) - Context menus for tray icons
- [Electron.Notification](Notification.md) - Desktop notifications
- [Electron.App](App.md) - Application lifecycle events
- [Electron.WindowManager](WindowManager.md) - Windows to show/hide from tray
## Additional Resources
- [Electron Tray Documentation](https://electronjs.org/docs/api/tray) - Official Electron tray API

292
docs/API/WebContents.md Normal file
View File

@@ -0,0 +1,292 @@
# Electron.WebContents
Render and control web pages.
## Overview
The `Electron.WebContents` API provides control over web page content within Electron windows. It handles page loading, navigation, JavaScript execution, and web page lifecycle events.
## Properties
#### 📋 `int Id`
Gets the unique identifier for this web contents.
#### 📋 `Session Session`
Manage browser sessions, cookies, cache, proxy settings, etc.
## Methods
#### 🧊 `void ExecuteJavaScriptAsync(string code, bool userGesture = false)`
Evaluates script code in page.
In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation.
Code execution will be suspended until web page stop loading.
**Parameters:**
- `code` - The code to execute
- `userGesture` - if set to `true` simulate a user gesture
**Returns:**
The result of the executed code.
#### 🧊 `Task<PrinterInfo[]> GetPrintersAsync()`
Get system printers.
**Returns:**
Array of available printers.
#### 🧊 `Task<string> GetUrl()`
Get the URL of the loaded page.
It's useful if a web-server redirects you and you need to know where it redirects. For instance, It's useful in case of Implicit Authorization.
**Returns:**
URL of the loaded page.
#### 🧊 `void InsertCSS(bool isBrowserWindow, string path)`
Inserts CSS into the web page.
See: https://www.electronjs.org/docs/api/web-contents#contentsinsertcsscss-options
Works for both BrowserWindows and BrowserViews.
**Parameters:**
- `isBrowserWindow` - Whether the webContents belong to a BrowserWindow or not (the other option is a BrowserView)
- `path` - Absolute path to the CSS file location
#### 🧊 `Task LoadURLAsync(string url)`
Loads the url in the window. The url must contain the protocol prefix.
The async method will resolve when the page has finished loading, and rejects if the page fails to load.
A noop rejection handler is already attached, which avoids unhandled rejection errors.
Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it.
**Parameters:**
- `url` - URL to load
#### 🧊 `Task LoadURLAsync(string url, LoadURLOptions options)`
Loads the url with additional options.
The async method will resolve when the page has finished loading, and rejects if the page fails to load.
A noop rejection handler is already attached, which avoids unhandled rejection errors.
Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it.
**Parameters:**
- `url` - URL to load
- `options` - Loading options
#### 🧊 `void OpenDevTools()`
Opens the devtools.
#### 🧊 `void OpenDevTools(OpenDevToolsOptions openDevToolsOptions)`
Opens the devtools with options.
**Parameters:**
- `openDevToolsOptions` - Developer tools options
#### 🧊 `Task<bool> PrintAsync(PrintOptions options = null)`
Prints window's web page.
**Parameters:**
- `options` - Print options
**Returns:**
Whether the print operation succeeded.
#### 🧊 `Task<bool> PrintToPDFAsync(string path, PrintToPDFOptions options = null)`
Prints window's web page as PDF with Chromium's preview printing custom settings.The landscape will be ignored if @page CSS at-rule is used in the web page. By default, an empty options will be regarded as: Use page-break-before: always; CSS style to force to print to a new page.
**Parameters:**
- `path` - Output file path
- `options` - PDF generation options
**Returns:**
Whether the PDF generation succeeded.
## Events
#### ⚡ `InputEvent`
Emitted when an input event is sent to the WebContents.
#### ⚡ `OnCrashed`
Emitted when the renderer process crashes or is killed.
#### ⚡ `OnDidFailLoad`
Emitted when the load failed.
#### ⚡ `OnDidFinishLoad`
Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the onload event was dispatched.
#### ⚡ `OnDidNavigate`
Emitted when a main frame navigation is done.
#### ⚡ `OnDidRedirectNavigation`
Emitted after a server side redirect occurs during navigation.
#### ⚡ `OnDidStartNavigation`
Emitted when any frame (including main) starts navigating.
#### ⚡ `OnDomReady`
Emitted when the document in the top-level frame is loaded.
#### ⚡ `OnWillRedirect`
Emitted when a server side redirect occurs during navigation.
## Usage Examples
### Page Loading
```csharp
// Load URL with options
await webContents.LoadURLAsync("https://example.com", new LoadURLOptions
{
UserAgent = "MyApp/1.0",
ExtraHeaders = "Authorization: Bearer token123"
});
// Load local file
await webContents.LoadURLAsync("file://" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app/index.html"));
// Get current URL
var currentUrl = await webContents.GetUrl();
Console.WriteLine($"Current URL: {currentUrl}");
```
### JavaScript Execution
```csharp
// Execute simple JavaScript
var result = await webContents.ExecuteJavaScriptAsync("document.title");
Console.WriteLine($"Page title: {result}");
// Execute with user gesture simulation
await webContents.ExecuteJavaScriptAsync("document.requestFullscreen()", true);
// Execute complex code
var userAgent = await webContents.ExecuteJavaScriptAsync("navigator.userAgent");
Console.WriteLine($"User agent: {userAgent}");
```
### Developer Tools
```csharp
// Open dev tools
webContents.OpenDevTools();
// Open with specific options
webContents.OpenDevTools(new OpenDevToolsOptions
{
Mode = DevToolsMode.Detached,
Activate = true
});
```
### CSS Injection
```csharp
// Inject CSS file
webContents.InsertCSS(true, "styles/custom-theme.css");
// Inject CSS for BrowserView
webContents.InsertCSS(false, "styles/browser-view.css");
```
### Printing Operations
```csharp
// Print web page
var printSuccess = await webContents.PrintAsync(new PrintOptions
{
Silent = false,
PrintBackground = true,
DeviceName = "My Printer"
});
if (printSuccess)
{
Console.WriteLine("Print job sent successfully");
}
```
### PDF Generation
```csharp
// Generate PDF
var pdfSuccess = await webContents.PrintToPDFAsync("document.pdf", new PrintToPDFOptions
{
MarginsType = PrintToPDFMarginsType.None,
PageSize = PrintToPDFPageSize.A4,
PrintBackground = true,
Landscape = false
});
if (pdfSuccess)
{
Console.WriteLine("PDF generated successfully");
}
```
### Navigation Monitoring
```csharp
// Monitor navigation events
webContents.OnDidStartNavigation += (url) =>
{
Console.WriteLine($"Starting navigation to: {url}");
};
webContents.OnDidNavigate += (navInfo) =>
{
Console.WriteLine($"Navigated to: {navInfo.Url}");
};
webContents.OnDidFinishLoad += () =>
{
Console.WriteLine("Page finished loading");
};
webContents.OnDidFailLoad += (failInfo) =>
{
Console.WriteLine($"Page failed to load: {failInfo.ErrorCode} - {failInfo.ErrorDescription}");
};
```
### Content Interaction
```csharp
// Wait for DOM ready
webContents.OnDomReady += () =>
{
Console.WriteLine("DOM is ready");
// Safe to execute DOM-related JavaScript now
};
// Handle page crashes
webContents.OnCrashed += (killed) =>
{
Console.WriteLine($"Renderer crashed, killed: {killed}");
// Optionally reload the page
};
```
## Related APIs
- [Electron.WindowManager](WindowManager.md) - Windows containing web contents
- [Electron.Session](Session.md) - Session management for web contents
- [Electron.IpcMain](IpcMain.md) - Communication with web contents
## Additional Resources
- [Electron WebContents Documentation](https://electronjs.org/docs/api/web-contents) - Official Electron web contents API
- [Web Content Management](../Core/What's-New.md) - Understanding web content handling
- [Security Considerations](../Using/Configuration.md) - Secure web content integration

208
docs/API/WindowManager.md Normal file
View File

@@ -0,0 +1,208 @@
# Electron.WindowManager
Create and manage browser windows, control window behavior and appearance.
## Overview
The `Electron.WindowManager` API provides comprehensive control over browser windows in your Electron application. It handles window creation, management, and coordination with the application lifecycle.
## Properties
#### 📋 `IReadOnlyCollection<BrowserView> BrowserViews`
Gets a read-only collection of all currently open browser views.
#### 📋 `IReadOnlyCollection<BrowserWindow> BrowserWindows`
Gets a read-only collection of all currently open browser windows.
#### 📋 `bool IsQuitOnWindowAllClosed`
Controls whether the application quits when all windows are closed. Default is true.
## Methods
#### 🧊 `Task<BrowserView> CreateBrowserViewAsync()`
Creates a new browser view with default options.
**Returns:**
The created BrowserView instance.
#### 🧊 `Task<BrowserView> CreateBrowserViewAsync(BrowserViewConstructorOptions options)`
Creates a new browser view with custom options.
**Parameters:**
- `options` - Browser view configuration options
**Returns:**
The created BrowserView instance.
#### 🧊 `Task<BrowserWindow> CreateWindowAsync(string loadUrl = "http://localhost")`
Creates a new browser window with default options.
**Parameters:**
- `loadUrl` - URL to load in the window. Defaults to "http://localhost"
**Returns:**
The created BrowserWindow instance.
#### 🧊 `Task<BrowserWindow> CreateWindowAsync(BrowserWindowOptions options, string loadUrl = "http://localhost")`
Creates a new browser window with custom options.
**Parameters:**
- `options` - Window configuration options
- `loadUrl` - URL to load in the window. Defaults to "http://localhost"
**Returns:**
The created BrowserWindow instance.
## Usage Examples
### Basic Window Creation
```csharp
// Create window with default options
var mainWindow = await Electron.WindowManager.CreateWindowAsync();
// Create window with custom options
var settingsWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions
{
Width = 800,
Height = 600,
Show = false,
Title = "Settings",
WebPreferences = new WebPreferences
{
NodeIntegration = false,
ContextIsolation = true
}
}, "https://localhost:5001/settings");
```
### Window Management
```csharp
// Get all windows
var windows = Electron.WindowManager.BrowserWindows;
Console.WriteLine($"Open windows: {windows.Count}");
// Configure quit behavior
Electron.WindowManager.IsQuitOnWindowAllClosed = false; // Keep app running when windows close
// Handle window lifecycle
Electron.App.WindowAllClosed += () =>
{
Console.WriteLine("All windows closed");
if (Electron.WindowManager.IsQuitOnWindowAllClosed)
{
Electron.App.Quit();
}
};
```
### Browser View Integration
```csharp
// Create browser view
var browserView = await Electron.WindowManager.CreateBrowserViewAsync(new BrowserViewConstructorOptions
{
WebPreferences = new WebPreferences
{
NodeIntegration = false,
ContextIsolation = true
}
});
// Add to window
await mainWindow.SetBrowserViewAsync(browserView);
await browserView.WebContents.LoadURLAsync("https://example.com");
// Set view bounds
await mainWindow.SetBoundsAsync(browserView, new Rectangle
{
X = 0,
Y = 100,
Width = 800,
Height = 400
});
```
### Window Options Configuration
```csharp
// Comprehensive window options
var options = new BrowserWindowOptions
{
Width = 1200,
Height = 800,
MinWidth = 600,
MinHeight = 400,
MaxWidth = 1920,
MaxHeight = 1080,
X = 100,
Y = 100,
Center = true,
Frame = true,
Title = "My Application",
Icon = "assets/app-icon.png",
Show = false,
AlwaysOnTop = false,
SkipTaskbar = false,
Kiosk = false,
TitleBarStyle = TitleBarStyle.Default,
BackgroundColor = "#FFFFFF",
DarkTheme = false,
Transparent = false,
WebPreferences = new WebPreferences
{
NodeIntegration = false,
ContextIsolation = true,
EnableWebSQL = false,
Partition = "persist:electron",
ZoomFactor = 1.0f,
DevTools = true
}
};
```
### Multi-Window Applications
```csharp
// Create main window
var mainWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions
{
Width = 1200,
Height = 800,
Show = false
});
// Create secondary window
var secondaryWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions
{
Width = 600,
Height = 400,
Parent = mainWindow,
Modal = true,
Show = false
});
// Load different content
await mainWindow.WebContents.LoadURLAsync("https://localhost:5001");
await secondaryWindow.WebContents.LoadURLAsync("https://localhost:5001/settings");
// Show windows when ready
mainWindow.OnReadyToShow += () => mainWindow.Show();
secondaryWindow.OnReadyToShow += () => secondaryWindow.Show();
```
## Related APIs
- [Electron.App](App.md) - Application lifecycle and window events
- [Electron.Dialog](Dialog.md) - Parent windows for modal dialogs
- [Electron.Menu](Menu.md) - Window-specific menus
- [Electron.WebContents](WebContents.md) - Window content management
## Additional Resources
- [Electron Window Management Documentation](https://electronjs.org/docs/api/browser-window) - Official Electron window API

51
docs/About.md Normal file
View File

@@ -0,0 +1,51 @@
# About this Project
Electron.NET has been developed by a small number of people in the hope that it may be useful for others.
Support for this project in all forms is very welcome, no matter whether in form of code contributions or donations.
## 💬 Community
[![Gitter](https://badges.gitter.im/ElectronNET/community.svg)](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
Besides the chat on Gitter and the issues [discussed here](https://github.com/ElectronNET/Electron.NET/issues) you can also use [StackOverflow](https://stackoverflow.com/questions/tagged/electron.net) with the tag `electron.net`.
## 🙋‍♀️🙋‍♂ Contributing
Feel free to submit a pull request if you find any bugs (to see a list of active issues, visit the [Issues section](https://github.com/ElectronNET/Electron.NET/issues).
Please make sure all commits are properly documented.
## 🙏 Donate
We do this open source work in our free time. If you'd like us to invest more time on it, please [donate](https://donorbox.org/electron-net). Donation can be used to increase some issue priority. Thank you!
[![donate](https://img.shields.io/badge/Donate-Donorbox-green.svg)](https://donorbox.org/electron-net)
Alternatively, consider using a GitHub sponsorship for the core maintainers:
- [Gregor Biswanger](https://github.com/sponsors/GregorBiswanger)
- [Florian Rappl](https://github.com/sponsors/FlorianRappl)
Any support appreciated! 🍻
## 👨‍💻 Authors
* **[Gregor Biswanger](https://github.com/GregorBiswanger)** - (Microsoft MVP, Intel Black Belt and Intel Software Innovator) is a freelance lecturer, consultant, trainer, author and speaker. He is a consultant for large and medium-sized companies, organizations and agencies for software architecture, web- and cross-platform development. You can find Gregor often on the road attending or speaking at international conferences. - [Cross-Platform-Blog](http://www.cross-platform-blog.com) - Twitter [@BFreakout](https://www.twitter.com/BFreakout)
&nbsp;
* **[Dr. Florian Rappl](https://github.com/FlorianRappl)** - Software Developer - from Munich, Germany. Microsoft MVP & Web Geek. - [The Art of Micro Frontends](https://microfrontends.art) - [Homepage](https://florian-rappl.de) - Twitter [@florianrappl](https://twitter.com/florianrappl)
&nbsp;
* [**softworkz**](https://github.com/softworkz) - full range developer - likes to start where others gave up - MS MVP alumni and Munich citizen as well. Has not been involved in the evolution of Electron.NET but rather dropped off the update and overhaul for ElectronNET.Core in a kind-of drive-by action.
&nbsp;
* **[Robert Muehsig](https://github.com/robertmuehsig)** - Software Developer - from Dresden, Germany, now living & working in Switzerland. Microsoft MVP & Web Geek. - [codeinside Blog](https://blog.codeinside.eu) - Twitter [@robert0muehsig](https://twitter.com/robert0muehsig)
See also the list of [contributors](https://github.com/ElectronNET/Electron.NET/graphs/contributors) who participated in this project.
## 🎉 License
MIT-licensed. See [LICENSE](https://github.com/ElectronNET/Electron.NET?tab=MIT-1-ov-file#readme) for details.

View File

@@ -0,0 +1,90 @@
# Advanced Migration Topics
This guide covers advanced scenarios and edge cases that may require additional configuration when migrating to ElectronNET.Core.
## Custom ASP.NET Port Configuration
### Port Configuration Changes
**Previous Approach:**
Specifying the WebPort in `electron.manifest.json` is no longer supported because the ASP.NET-first launch mode makes this timing-dependent.
**New Approach:**
Configure custom ASP.NET ports through MSBuild metadata:
```xml
<ItemGroup>
<AssemblyMetadata Include="AspNetHttpPort" Value="4000" />
</ItemGroup>
```
## Custom ElectronHostHook Configuration
> [!NOTE]
> These changes are only required in case you are using a custom ElectronHostHook implementation!
> If you have an ElectronHostHook folder in your project but you did not customize that code and aren't using its demo features (Excel and ZIP), you can also just remove that folder from your project.
### TypeScript and Node.js Updates
**Update package.json:**
This shows the relevant changes only: All shown versions are the new required minimum versions.
```json
{
"devDependencies": {
"@types/node": "^22.18",
"typescript": "^5.9.3"
},
"dependencies": {
"socket.io": "^4.8.1",
}
}
```
**Update Project File:**
The below modifications will allow you to use the latest TypeScript compiler in your ASP.Net project.
```xml
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="5.9.3" />
<PropertyGroup>
<TypeScriptModuleKind>commonjs</TypeScriptModuleKind>
<TypeScriptUseNodeJS>true</TypeScriptUseNodeJS>
<TypeScriptTSConfig>ElectronHostHook/tsconfig.json</TypeScriptTSConfig>
</PropertyGroup>
<ItemGroup>
<Compile Remove="publish\**" />
<Content Remove="publish\**" />
<EmbeddedResource Remove="publish\**" />
<None Remove="publish\**" />
<TypeScriptCompile Remove="**\node_modules\**" />
</ItemGroup>
```
### Integration Benefits
- **Modern TypeScript** - Latest language features and better type checking
- **Updated Node.js Types** - Compatibility with Node.js 22.x APIs
- **ESLint Integration** - Better code quality and consistency
- **MSBuild Compilation** - Integrated with Visual Studio build process
## Troubleshooting Advanced Scenarios
### Multi-Project Solutions
When using ElectronNET.Core in multi-project solutions:
1. **Install ElectronNET.Core.Api** in class library projects
2. **Install ElectronNET.Core and ElectronNET.Core.AspNet** only in the startup project
3. **Share configuration** through project references or shared files
## Next Steps
- **[Migration Guide](Migration-Guide.md)** - Complete migration process
- **[What's New?](What's-New.md)** - Overview of all ElectronNET.Core features
- **[Getting Started](../GettingStarted/ASP.Net.md)** - Development workflows

View File

@@ -0,0 +1,256 @@
# Migration Checks
Electron.NET includes automatic build-time validation checks that help users migrating from previous versions avoid common configuration issues. These checks run automatically during the build process and provide helpful guidance when problems are detected.
## Overview
When you build an Electron.NET project, the following validation checks are performed:
| Code | Check | Description |
|------|-------|-------------|
| [ELECTRON001](#1-packagejson-rules) | package.json location rules | Ensures `package.json`/`package-lock.json` arent present in unsupported locations (root `package.json` handled separately) |
| [ELECTRON008](#1-packagejson-rules) | root package.json contains electron | Warns when root `package.json` contains the word `electron` (case-insensitive) |
| [ELECTRON009](#1-packagejson-rules) | root package.json copied to output | Warns when root `package.json` is configured to be copied to output/publish |
| [ELECTRON002](#2-electron-manifestjson-not-allowed) | electron-manifest.json not allowed | Detects deprecated manifest files |
| [ELECTRON003](#3-electron-builderjson-location) | electron-builder.json location | Verifies electron-builder.json exists in Properties folder |
| [ELECTRON004](#3-electron-builderjson-location) | electron-builder.json wrong location | Warns if electron-builder.json is found in incorrect locations |
| [ELECTRON005](#4-parent-paths-not-allowed-in-electron-builderjson) | Parent paths not allowed | Checks for `..` references in config |
| [ELECTRON006](#5-publish-profile-validation) | ASP.NET publish profile mismatch | Warns when ASP.NET projects have console-style profiles |
| [ELECTRON007](#5-publish-profile-validation) | Console publish profile mismatch | Warns when console projects have ASP.NET-style profiles |
---
## 1. package.json rules
**Warning Codes:** `ELECTRON001`, `ELECTRON008`, `ELECTRON009`
### What is checked
The build system scans for `package.json` and `package-lock.json` files in your project directory.
Rules:
- **ELECTRON001**: `package.json` / `package-lock.json` must not exist in the project directory or subdirectories
- Exception: `ElectronHostHook` folder is allowed
- Note: a **root** `package.json` is **excluded** from `ELECTRON001` and validated by `ELECTRON008` / `ELECTRON009`
- **ELECTRON008**: If a root `package.json` exists, it must **not** contain electron-related dependencies or configuration.
- **ELECTRON009**: If a root `package.json` exists, it must **not** be configured to be copied to output/publish (for example via `CopyToOutputDirectory` / `CopyToPublishDirectory` metadata)
### Why this matters
Electron.NET generates its Electron-related `package.json` during publishing based on MSBuild properties. A user-maintained Electron-related `package.json` can conflict with that process.
Also, ensuring the root `package.json` is not copied prevents accidentally shipping it with the published app.
### Exception
A `package.json` / `package-lock.json` file **is allowed** in the `ElectronHostHook` folder if you're using custom host hooks.
### How to fix
If you have an Electron-related `package.json` from older Electron.NET versions:
1. **Open your project's `.csproj` file**
2. **Add the required properties** to a PropertyGroup with the label `ElectronNetCommon`:
```xml
<PropertyGroup Label="ElectronNetCommon">
<ElectronPackageId>my-electron-app</ElectronPackageId>
<Title>My Electron App</Title>
<Version>1.0.0</Version>
<Description>My awesome Electron.NET application</Description>
<Company>My Company</Company>
<Copyright>Copyright © 2025</Copyright>
<ElectronVersion>30.0.9</ElectronVersion>
</PropertyGroup>
```
3. **Delete** Electron-related `package.json` / `package-lock.json` files (except those under `ElectronHostHook` if applicable)
If you keep a root `package.json` for non-Electron reasons:
- Ensure it does **not** contain electron dependencies or configuration (fixes `ELECTRON008`)
- Ensure it is **not** copied to output/publish (fixes `ELECTRON009`)
> **See also:** [Migration Guide](Migration-Guide.md) for complete migration instructions.
---
## 2. electron-manifest.json not allowed
**Warning Code:** `ELECTRON002`
### What is checked
The build system checks for the presence of `electron.manifest.json` or `electron-manifest.json` files in your project.
### Why this matters
The `electron.manifest.json` file format is deprecated. All configuration should now be specified using:
- MSBuild properties in your `.csproj` file (for application metadata)
- The `electron-builder.json` file in the `Properties` folder (for build configuration)
### How to fix
1. **Migrate application properties** to your `.csproj` file (see [Migration Guide](Migration-Guide.md))
2. **Move the `build` section** from `electron.manifest.json` to `Properties/electron-builder.json`
3. **Delete the old `electron.manifest.json`** file
**Example electron-builder.json:**
```json
{
"compression": "maximum",
"win": {
"icon": "Assets/app.ico",
"target": ["nsis", "portable"]
},
"linux": {
"icon": "Assets/app.png",
"target": ["AppImage", "deb"]
},
"mac": {
"icon": "Assets/app.icns",
"target": ["dmg", "zip"]
}
}
```
---
## 3. electron-builder.json Location
**Warning Codes:** `ELECTRON003`, `ELECTRON004`
### What is checked
- `ELECTRON003`: Verifies that an `electron-builder.json` file exists in the `Properties` folder
- `ELECTRON004`: Warns if `electron-builder.json` is found in incorrect locations
### Why this matters
The `electron-builder.json` file must be located in the `Properties` folder so it can be properly copied to the output directory during publishing.
### How to fix
1. **Create the Properties folder** if it doesn't exist
2. **Move or create** `electron-builder.json` in `Properties/electron-builder.json`
3. **Remove** any `electron-builder.json` files from other locations
**Expected structure:**
```
MyProject/
├── Properties/
│ ├── electron-builder.json ✅ Correct location
│ ├── launchSettings.json
│ └── PublishProfiles/
├── MyProject.csproj
└── Program.cs
```
---
## 4. Parent paths not allowed in electron-builder.json
**Warning Code:** `ELECTRON005`
### What is checked
The build system scans the `electron-builder.json` file for parent-path references (`..`).
### Why this matters
During the publish process, the `electron-builder.json` file is copied to the build output directory. Any relative paths in this file are resolved from that location, not from your project directory. Parent-path references (`../`) will not work correctly because they would point outside the published application.
### How to fix
1. **Move resource files** (icons, installers, etc.) inside your project folder structure
2. **Configure the files** to be copied to the output directory in your `.csproj`:
```xml
<ItemGroup>
<Content Include="Assets\**\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
```
3. **Update paths** in `electron-builder.json` to use relative paths without `..`:
**Before (incorrect):**
```json
{
"win": {
"icon": "../SharedAssets/app.ico"
}
}
```
**After (correct):**
```json
{
"win": {
"icon": "Assets/app.ico"
}
}
```
---
## 5. Publish Profile Validation
**Warning Codes:** `ELECTRON006`, `ELECTRON007`
### What is checked
The build system examines `.pubxml` files in the `Properties/PublishProfiles` folder and validates that they match the project type:
- **ELECTRON006**: For **ASP.NET projects** (using `Microsoft.NET.Sdk.Web`), checks that publish profiles include `WebPublishMethod`. This property is required for proper ASP.NET publishing.
- **ELECTRON007**: For **console/other projects** (not using the Web SDK), checks that publish profiles do NOT include the `WebPublishMethod` property. These ASP.NET-specific properties are incorrect for non-web applications.
### Why this matters
Electron.NET supports both ASP.NET and console application project types, each requiring different publish profile configurations:
| Project Type | SDK | Expected Properties |
|--------------|-----|---------------------|
| ASP.NET (Razor Pages, MVC, Blazor) | `Microsoft.NET.Sdk.Web` | `WebPublishMethod`, no `PublishProtocol` |
| Console Application | `Microsoft.NET.Sdk` | `PublishProtocol`, no `WebPublishMethod` |
Using the wrong publish profile type can lead to incomplete or broken builds.
### How to fix
1. **Delete existing publish profiles** from `Properties/PublishProfiles/`
2. **Create new publish profiles** using the Visual Studio Publishing Wizard:
- Right-click on the project in Solution Explorer
- Select **Publish...**
- Follow the wizard to create a **Folder** publish profile
For correct publish profile examples for both ASP.NET and Console applications, see **[Package Building](../Using/Package-Building.md#step-1-create-publish-profiles)**.
---
## Disabling Migration Checks
If you need to disable specific migration checks (not recommended), you can set the following properties in your `.csproj` file:
```xml
<PropertyGroup>
<!-- Disable all migration checks -->
<ElectronSkipMigrationChecks>true</ElectronSkipMigrationChecks>
</PropertyGroup>
```
> ⚠️ **Warning:** Disabling migration checks may result in build or runtime errors. Only disable checks if you fully understand the implications.
---
## See Also
- [Migration Guide](Migration-Guide.md) - Complete step-by-step migration instructions
- [Advanced Migration Topics](Advanced-Migration-Topics.md) - Complex migration scenarios
- [Configuration](../Using/Configuration.md) - Project configuration options
- [Package Building](../Using/Package-Building.md) - Building distributable packages

View File

@@ -0,0 +1,173 @@
# Migration Guide
Migrating from previous versions of Electron.NET to ElectronNET.Core is straightforward but requires several important changes. This guide walks you through the process step by step.
## 📋 Prerequisites
Before starting the migration:
- **Backup your project** - Ensure you have a working backup
- **Update development tools** - Install Node.js 22.x and .NET 8.0+
- **Review current setup** - Note your current Electron and ASP.NET versions
## 🚀 Migration Steps
### Step 1: Update NuGet Packages
**Uninstall old packages:**
```powershell
dotnet remove package ElectronNET.API
```
**Install new packages:**
```powershell
dotnet add package ElectronNET.Core
dotnet add package ElectronNET.Core.AspNet # For ASP.NET projects
```
> **Note**: The API package is automatically included as a dependency of `ElectronNET.Core`. See [Package Description](../RelInfo/Package-Description.md) for details about the package structure.
### Step 2: Configure Project Settings
**Auto-generated Configuration:**
ElectronNET.Core automatically creates `electron-builder.json` in the `Properties` folder of your project during the first build or NuGet restore. No manual configuration is needed for basic setups.
**Migrate Existing Configuration:**
If you have an existing `electron.manifest.json` file:
1. **Open the generated `electron-builder.json`** file in your project
2. **Locate the 'build' section** in your old `electron.manifest.json`
3. **Copy the contents** of the build section (not the "build" key itself) into the new `electron-builder.json`
4. **Use Visual Studio Project Designer** to configure Electron settings through the UI
5. **Delete the old `electron.manifest.json`** file
**Alternative: Manual Configuration**
You can also manually edit `electron-builder.json`:
```json
{
"linux": {
"target": [
"tar.xz"
]
},
"win": {
"target": [
{
"target": "portable",
"arch": "x64"
}
]
}
}
```
**Modify Launch Settings:**
ElectronNET.Core no longer needs a separate CLI tool (electronize.exe) for launching. You should update your launch settings to use either the ASP.NET-first or Electron-first approach. See [Debugging](../Using/Debugging.md) for details.
## 🎯 Testing Migration
After completing the migration steps:
1. **Build your project** to ensure no compilation errors
2. **Test debugging** using the new ASP.NET-first approach
3. **Verify packaging** works with the new configuration
4. **Check cross-platform builds** if targeting multiple platforms
## 🚨 Common Migration Issues
### Build Errors
- **Node.js version**: Verify Node.js 22.x is installed and in PATH
- **Package conflicts**: Clean NuGet cache if needed
### Runtime Errors
- **Missing electron-builder.json**: Trigger rebuild or manual NuGet restore
- **Process termination**: Use .NET-first startup mode for better cleanup
## 🚀 Next Steps
- **[What's New?](What's-New.md)** - Complete overview of ElectronNET.Core features
- **[Advanced Migration Topics](Advanced-Migration-Topics.md)** - Handle complex scenarios
- **[Getting Started](../GettingStarted/ASP.Net.md)** - Learn about new development workflows
## 💡 Migration Benefits
**Simplified Configuration** - No more CLI tools or JSON files
**Better Debugging** - Native Visual Studio experience with Hot Reload
**Modern Architecture** - .NET-first process lifecycle
**Cross-Platform Ready** - Build Linux apps from Windows
**Future-Proof** - Flexible Electron version selection
### Step 3: Update Startup Code
**Update UseElectron() calls** to include the new callback parameter. This callback executes at the right moment to initialize your Electron UI.
#### Modern ASP.NET Core (WebApplication)
```csharp
using ElectronNET.API;
using ElectronNET.API.Entities;
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.UseElectron(args, ElectronAppReady);
var app = builder.Build();
app.Run();
}
public static async Task ElectronAppReady()
{
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions { Show = false });
browserWindow.OnReadyToShow += () => browserWindow.Show();
}
```
#### Traditional ASP.NET Core (IWebHostBuilder)
```csharp
using ElectronNET.API;
using ElectronNET.API.Entities;
public static void Main(string[] args)
{
WebHost.CreateDefaultBuilder(args)
.UseElectron(args, ElectronAppReady)
.UseStartup<Startup>()
.Build()
.Run();
}
public static async Task ElectronAppReady()
{
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions { Show = false });
browserWindow.OnReadyToShow += () => browserWindow.Show();
}
```
### Step 4: Update Development Tools
See [System Requirements](../GettingStarted/System-Requirements.md).
### Step 5: Update Debugging Setup
**Watch Feature Removal:**
The old 'watch' feature is no longer supported. Instead, use the new ASP.NET-first debugging with Hot Reload:
- **Old approach**: Manual process attachment and slow refresh
- **New approach**: Native Visual Studio debugging with Hot Reload
- **Benefits**: Faster development cycle, better debugging experience
**Update Launch Settings:**
Replace old watch configurations with new debugging profiles. See [Debugging](../GettingStarted/Debugging.md) for detailed setup instructions.

131
docs/Core/What's-New.md Normal file
View File

@@ -0,0 +1,131 @@
# What's New in ElectronNET.Core
## A Complete Transformation
ElectronNET.Core represents a fundamental modernization of Electron.NET, addressing years of accumulated pain points while preserving full API compatibility. This isn't just an update—it's a complete rethinking of how .NET developers build and debug cross-platform desktop applications with Electron.
## Complete Build System Overhaul
### From CLI Complexity to MSBuild Simplicity
The most visible change is the complete elimination of the CLI tool dependency. Where developers once needed to manage complex command-line operations and JSON configuration files, everything now flows through Visual Studio's native project system.
The old `electron.manifest.json` file is gone, replaced by clean MSBuild project properties that integrate seamlessly with Visual Studio's project designer. This provides not just a better development experience, but also eliminates entire categories of configuration errors that plagued earlier versions.
### Intelligent Package Structure
The new package architecture reflects a clearer separation of concerns:
- **ElectronNET.Core** - The main package containing build logic and project system integration
- **ElectronNET.Core.Api** - Pure API definitions for Electron integration
- **ElectronNET.Core.AspNet** - ASP.NET-specific runtime components
This modular approach allows projects to include only what they need while maintaining the flexibility to scale from simple console applications to complex web applications.
More about the available nuget packages: [Package Description](../RelInfo/Package-Description.md).
## Beyond ASP.NET: Console Application Support
### A Shift in Accessibility
A major new opportunity in ElectronNET.Core is the removal of the ASP.NET requirement. Developers can now build Electron solutions using simple DotNet console applications, expanding the use cases and removing a major barrier to adoption for a number of use cases.
### Flexible Content Sources
Console applications with ElectronNET.Core support multiple content scenarios:
- **File System HTML/JS**: Serve static web content directly from the file system
- **Remote Server Integration**: Connect to existing web servers or APIs
- **Lightweight Architecture**: Avoid the overhead of ASP.NET when it's not needed
- **Simplified Deployment**: Package and distribute with minimal dependencies
This capability transforms ElectronNET from a web-focused framework into a versatile platform that can integrate with any HTML/JS content source, making it accessible to a much broader range of development scenarios and team structures.
## Revolutionary Development Experience
### Debugging Reimagined
The debugging experience has been completely transformed. The new DotNet-first launch mode means developers can now debug their .NET code directly, with full access to familiar debugging tools and Hot Reload capabilities. No more attaching to processes or working around limited debugging scenarios — the development workflow now matches standard .NET development patterns.
### Cross-Platform Development Without Compromises
One of the most significant breakthroughs is the ability to build and debug Linux applications directly from Windows Visual Studio through WSL integration. Developers can now:
- Build Linux packages while working on Windows
- Debug Linux application behavior in real-time
- Test cross-platform functionality without context switching
- Deploy to Linux targets with confidence
This capability eliminates the traditional barriers between Windows development environments and Linux deployment targets.
### Flexible Runtime Identifier Support
Runtime Identifier (RID) selection is now a first-class part of the project configuration, allowing developers to explicitly target specific platforms and architectures. The build system automatically structures output folders using standard .NET conventions (`bin\net8.0\win-x64`) instead of the ambiguous `bin\Desktop` layout, making multi-target builds clean and predictable.
## Modernized Architecture
### Process Lifecycle Revolution
The underlying process architecture has been fundamentally redesigned. Instead of Electron launching first and managing the .NET process, ElectronNET.Core puts .NET in control. The .NET application launches first and runs Electron as a child process, providing:
- Better process lifecycle management
- More reliable application termination
- Enhanced error handling and recovery
- Cleaner separation between web and native concerns
This architecture supports eight different launch scenarios, covering every combination of packaged/unpackaged deployment, console/ASP.NET hosting, and dotnet-first/electron-first initialization. The Electron-first launch method is still available or course.
For more details, see: [Startup Methods](../GettingStarted/Startup-Methods.md).
### Unpackaged Development Mode
The new unpackaged run-mode transforms development workflows by using regular .NET builds with unpackaged Electron configurations. This approach leverages .NET's incremental build capabilities for both managed and native code, dramatically reducing rebuild times and improving the development feedback loop.
## Enhanced Technical Foundation
### TypeScript Integration
TypeScript compilation is now fully integrated with ASP.NET tooling, providing consistent builds across different development environments. The updated toolchain uses modern TypeScript versions with ESLint configuration, eliminating the compatibility issues that previously affected custom ElectronHostHook implementations.
### API Enhancements
The improved splash screen handling with automatic path resolution eliminates common configuration pitfalls, while maintaining full backward compatibility with existing ElectronHostHook code.
### Performance Optimizations
Package sizes have been reduced by eliminating unnecessary dependencies, while build performance has improved through intelligent incremental compilation. The new architecture also minimizes startup times through optimized build and launch procedures.
## Seamless Migration Path
### Backward Compatibility Focus
Despite the extensive changes, ElectronNET.Core maintains complete API compatibility with existing applications. The modular package structure allows for incremental adoption, and existing ElectronHostHook implementations continue to work without modification.
### Clear Upgrade Journey
The migration path is designed to be straightforward:
1. Update package references to the new structure
2. Remove the old manifest file
3. Configure project properties through Visual Studio
4. Adopt new debugging workflows at your own pace
Further reading: [Migration Guide](Migration-Guide.md).
## Future Horizons
### Unlocked Possibilities
This modernization removes the technical debt that was limiting Electron.NET's evolution. The flexible Electron versioning, integrated build system, and cross-platform capabilities create a foundation for:
- More frequent updates and feature additions
- Enhanced community contributions
- Better tooling and IDE integration
- Expanded platform support
### Version Independence
The removal of rigid Electron version coupling means developers can now choose the Electron version that best fits their needs, with build-time validation ensuring compatibility. This approach encourages community feedback and enables faster adoption of new Electron features.
## Conclusion
ElectronNET.Core represents more than just new features—it's a complete reimagining of what .NET + Electron development can be. By eliminating friction points, removing the ASP.NET requirement to support console applications, improving debugging experiences, and enabling true cross-platform development, it transforms Electron.NET from a challenging framework to work with into a modern, efficient platform for building cross-platform desktop applications.
The changes address the core issues that were driving developers away from Electron.NET while opening new possibilities for the future. This foundation will enable more rapid innovation and better support for the growing demands of cross-platform .NET development.

25
docs/Docs.shproj Normal file
View File

@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup Label="Globals">
<ProjectGuid>06caadc7-de5b-47b4-ab2a-e9501459a2d1</ProjectGuid>
</PropertyGroup>
<ItemGroup>
<Compile Remove="About\Azure\**" />
<Compile Remove="About\BuildBot\**" />
<Compile Remove="images\AzureDevOps\**" />
<Compile Remove="images\visualization\**" />
<Compile Remove="schema_printing\**" />
<EmbeddedResource Remove="About\Azure\**" />
<EmbeddedResource Remove="About\BuildBot\**" />
<EmbeddedResource Remove="images\AzureDevOps\**" />
<EmbeddedResource Remove="images\visualization\**" />
<EmbeddedResource Remove="schema_printing\**" />
<None Remove="About\Azure\**" />
<None Remove="About\BuildBot\**" />
<None Remove="images\AzureDevOps\**" />
<None Remove="images\visualization\**" />
<None Remove="schema_printing\**" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project=".docproj\DocProj.props" />
<Import Project=".docproj\DocProj.targets" />
</Project>

View File

@@ -0,0 +1,129 @@
# ASP.NET Core Setup
ASP.NET Core remains the recommended approach for complex web applications with ElectronNET.Core, providing all the benefits of the ASP.NET ecosystem along with enhanced Electron integration.
## 🛠 System Requirements
See [System Requirements](../GettingStarted/System-Requirements.md).
## 🚀 Quick Start
### 1. Create ASP.NET Core Project
#### Visual Studio
Create a new ASP.NET Core Web App in Visual Studio by selecting **New Project** and choosing one of the ASP.NET Core project templates.
#### From the command line
```bash
dotnet new webapp -n MyElectronWebApp
cd MyElectronWebApp
```
### 2. Install NuGet Packages
#### Visual Studio
Right-click the solution and select **Manage Nuget Packages**.
Finr and install `ElectronNET.Core` as well as `ElectronNET.Core.AspNet`.
#### From the command line
```powershell
dotnet add package ElectronNET.Core
dotnet add package ElectronNET.Core.AspNet
```
> [!Note]
> The API package is automatically included as a dependency of `ElectronNET.Core`.
### 3. Configure Program.cs
Update your `Program.cs` to enable Electron.NET:
```csharp
using ElectronNET.API;
using ElectronNET.API.Entities;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
// Add this line to enable Electron.NET:
builder.UseElectron(args, ElectronAppReady);
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
}
public static async Task ElectronAppReady()
{
var browserWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions { Show = false });
browserWindow.OnReadyToShow += () => browserWindow.Show();
}
}
```
#### ASP.NET Port
If you want to launch a specific URL, you can retrieve the actual ASP.NET port from the new `ElectronNetRuntime` static class, for example:
```csharp
await browserWindow.WebContents
.LoadURLAsync($"http://localhost:{ElectronNetRuntime.AspNetWebPort}/mypage.html");
```
### 4. Alternative: IWebHostBuilder Setup
For projects using the traditional `Startup.cs` pattern, please see "Traditional ASP.NET Core" in the [Migration Guide](../Core/Migration-Guide.md).
### 5. Dependency Injection
ElectronNET.API can be added to your DI container within the `Startup` class. All of the modules available in Electron will be added as Singletons.
```csharp
using ElectronNET.API;
public void ConfigureServices(IServiceCollection services)
{
services.AddElectron();
}
```
## 🚀 Next Steps
- **[Debugging](../Using/Debugging.md)** - Learn about ASP.NET debugging features
- **[Package Building](../Using/Package-Building.md)** - Create distributable packages
- **[Startup Methods](../Using/Startup-Methods.md)** - Understanding launch scenarios
## 💡 Benefits of ASP.NET + Electron
**Full Web Stack** - Use MVC, Razor Pages, Blazor, and all ASP.NET features
**Hot Reload** - Edit ASP.NET code and see changes instantly
**Rich Ecosystem** - Access to thousands of ASP.NET packages
**Modern Development** - Latest C# features and ASP.NET patterns
**Scalable Architecture** - Build complex, maintainable applications

View File

@@ -0,0 +1,166 @@
# Console Application Setup
A major benefit in ElectronNET.Core is the ability to build Electron applications using simple console applications instead of requiring ASP.NET Core. This removes a significant barrier and enables many more use cases.
## 🎯 What You Can Build
Console applications with ElectronNET.Core support multiple content scenarios:
- **File System HTML/JS** - Serve static web content directly from the file system
- **Remote Server Integration** - Connect to existing web servers or APIs
- **Lightweight Architecture** - Avoid ASP.NET overhead when not needed
- **Simplified Deployment** - Package and distribute with minimal dependencies
## 📋 Prerequisites
See [System Requirements](../GettingStarted/System-Requirements.md).
## 🚀 Quick Start
### 1. Create Console Application
#### Visual Studio
Create a new console application in Visual Studio by selecting **New Project** and choosing one of the project templates for console apps.
#### From the command line
```bash
dotnet new console -n MyElectronApp
cd MyElectronApp
```
### 2. Install NuGet Packages
```powershell
dotnet add package ElectronNET.Core
```
> [!Note]
> The API package is automatically included as a dependency of `ElectronNET.Core`.
### 3. Configure Project File
Add the Electron.NET configuration to your `.csproj` file:
```xml
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ElectronNET.Core" Version="0.4.1" />
</ItemGroup>
```
> [!WARNING]
> Specifying `OutputType` property is crucial in order to get the ability of WSL debugging. Especially it is not included in ASP.NET projects.
> When you migrate from ASP.NET to a console application, be sure to add this to the project file.
### 4. Implement Basic Structure
Here's a complete console application example:
```csharp
using System;
using System.Threading.Tasks;
using ElectronNET.API.Entities;
namespace MyElectronApp
public class Program
{
public static async Task Main(string[] args)
{
var runtimeController = ElectronNetRuntime.RuntimeController;
try
{
// Start Electron runtime
await runtimeController.Start();
await runtimeController.WaitReadyTask;
// Initialize your Electron app
await InitializeApp();
// Wait for shutdown
await runtimeController.WaitStoppedTask.ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
await runtimeController.Stop().ConfigureAwait(false);
await runtimeController.WaitStoppedTask.WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
}
}
private static async Task InitializeApp()
{
// Create main window
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions
{
Show = false,
WebPreferences = new WebPreferences
{
// Add these two when using file:// URLs
WebSecurity = false,
AllowRunningInsecureContent = true,
NodeIntegration = false,
ContextIsolation = true
}
});
// Load your content (file system, remote URL, etc.)
await browserWindow.WebContents.LoadURLAsync("https://example.com");
// Show window when ready
browserWindow.OnReadyToShow += () => browserWindow.Show();
}
}
```
## 📁 Content Sources
### File System Content
Serve HTML/JS files from your project:
```csharp
// In your project root, create wwwroot/index.html
var fileInfo = new FileInfo(Environment.ProcessPath);
var exeFolder = fileInfo.DirectoryName;
var htmlPath = Path.Combine(exeFolder, "wwwroot/index.html");
var url = new Uri(htmlPath, UriKind.Absolute);
await browserWindow.WebContents.LoadFileAsync(url.ToString());
```
### Remote Content
Load content from any web server:
```csharp
await browserWindow.WebContents.LoadURLAsync("https://your-server.com/app");
```
## 🚀 Next Steps
- **[Debugging](../Using/Debugging.md)** - Learn about debugging console applications
- **[Package Building](../Using/Package-Building.md)** - Create distributable packages
- **[Migration Guide](../Core/Migration-Guide.md)** - Moving from ASP.NET projects
## 💡 Benefits of Console Apps
**Simpler Architecture** - No ASP.NET complexity when not needed
**Flexible Content** - Use any HTML/JS source
**Faster Development** - Less overhead for simple applications
**Easy Deployment** - Minimal dependencies
**Better Performance** - Lighter weight than full web applications

View File

@@ -0,0 +1,53 @@
## 🛠 System Requirements
### Required Software
- **.NET 8.0** or later
- **Node.js 22.x** or later (see below)
- **Visual Studio 2022** (recommended) or other .NET IDE
### Supported Operating Systems
- **Windows 10/11** (x64, ARM64)
- **macOS 11+** (Intel, Apple Silicon)
- **Linux** (most distributions with glibc 2.31+)
> [!Note]
> For Linux development on Windows, install [WSL2](https://docs.microsoft.com/windows/wsl/install) to build and debug Linux packages.
> Do not forget to install NodeJS 22.x (LTS) on WSL.
> Visual Studio will automatically install .NET when debugging on WSL. In all other cases you will need to install a matching .NET SDK on WSL as well.
### NodeJS Installation
ElectronNET.Core requires Node.js 22.x. Update your installation:
**Windows:**
1. Download from [nodejs.org](https://nodejs.org)
2. Run the installer
3. Verify: `node --version` should show v22.x.x
**Linux:**
```bash
# Using Node Version Manager (recommended)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc
nvm install 22
nvm use 22
# Or using package manager
sudo apt update
sudo apt install nodejs=22.*
```
## 🚀 Next Steps
- **[Debugging](../Using/Debugging.md)** - Learn about ASP.NET debugging features
- **[Package Building](../Using/Package-Building.md)** - Create distributable packages
- **[Startup Methods](../Using/Startup-Methods.md)** - Understanding launch scenarios

59
docs/Home.md Normal file
View File

@@ -0,0 +1,59 @@
# Electron.NET Wiki Home
Welcome to the **Electron.NET Core** documentation! This wiki covers everything you need to know about building cross-platform desktop applications with ASP.NET Core and Electron.NET.
## 🚀 What is Electron.NET Core?
Electron.NET Core is a complete modernization of Electron.NET that eliminates the CLI tool dependency and integrates deeply with Visual Studio's MSBuild system. It transforms the development experience by providing:
- **Native Visual Studio Integration** - No more CLI tools or JSON configuration files
- **Console Application Support** - Build Electron apps with simple console applications, not just ASP.NET
- **Cross-Platform Development** - Build and debug Linux applications from Windows via WSL
- **Enhanced Debugging** - ASP.NET-first debugging with Hot Reload support
- **Flexible Architecture** - Choose any Electron version and target multiple platforms
## 📚 Documentation Sections
### [Core Documentation](Core/What's-New.md)
- **[What's New?](Core/What's-New.md)** - Complete overview of ElectronNET.Core features and improvements
- **[Migration Guide](Core/Migration-Guide.md)** - Step-by-step migration from previous versions
- **[Advanced Migration Topics](Core/Advanced-Migration-Topics.md)** - Technical details for complex scenarios
### [Getting Started](GettingStarted/ASP.Net.md)
- **[ASP.NET Applications](GettingStarted/ASP.Net.md)** - Build Electron apps with ASP.NET Core
- **[Console Applications](GettingStarted/Console-App.md)** - Use console apps for file system or remote content
- **[Startup Methods](GettingStarted/Startup-Methods.md)** - Understanding different launch scenarios
- **[Debugging](GettingStarted/Debugging.md)** - Debug Electron apps effectively in Visual Studio
- **[Package Building](GettingStarted/Package-Building.md)** - Create distributable packages
### [Release Information](RelInfo/Package-Description.md)
- **[Package Description](RelInfo/Package-Description.md)** - Understanding the three NuGet packages
- **[Changelog](../Changelog.md)** - Complete list of changes and improvements
## 🛠 System Requirements
See [System Requirements](GettingStarted/System-Requirements.md).
## 💡 Key Benefits
**No CLI Tools Required** - Everything works through Visual Studio
**Console App Support** - Use any HTML/JS source, not just ASP.NET
**True Cross-Platform** - Build Linux apps from Windows
**Modern Debugging** - Hot Reload and ASP.NET-first debugging
**Flexible Packaging** - Choose any Electron version
**MSBuild Integration** - Leverages .NET's build system
## 🚦 Getting Started
New to ElectronNET.Core? Start here:
1. **[ASP.NET Setup](GettingStarted/ASP.Net.md)** - Traditional web application approach
2. **[Console App Setup](GettingStarted/Console-App.md)** - Lightweight console application approach
3. **[Migration Guide](Core/Migration-Guide.md)** - Moving from previous versions
## 🤝 Contributing
Found an issue or want to improve the documentation? Contributions are welcome!
The wiki is auto-generated from the `/docs` folder in the [GitHub repository](https://github.com/ElectronNET/Electron.NET).

View File

@@ -0,0 +1,116 @@
# Package Description
ElectronNET.Core consists of three specialized NuGet packages designed for different development scenarios and project architectures.
## 📦 Package Overview
### ElectronNET.Core (Main Package)
**Primary package for Electron.NET applications**
- **Build system integration** - MSBuild targets and tasks for Electron
- **Project system extensions** - Visual Studio designer integration
- **Runtime orchestration** - Process lifecycle management
- **Automatic configuration** - Generates electron-builder.json and package.json
- **Includes ElectronNET.Core.Api** as a dependency
**When to use:**
- Main application projects (startup projects)
- Projects that need full Electron.NET functionality
- Applications requiring build-time Electron configuration
### ElectronNET.Core.Api (API Package)
**Pure API definitions without build integration**
- **Electron API wrappers** - Complete Electron API surface
- **Type definitions** - Full TypeScript-style IntelliSense
- **No build dependencies** - Clean API-only package
- **Multi-platform support** - Windows, macOS, Linux
**When to use:**
- Class library projects that interact with Electron APIs
- Projects that only need API access without build integration
- Multi-project solutions where only the startup project needs build integration
### ElectronNET.Core.AspNet (ASP.NET Integration)
**ASP.NET-specific runtime components**
- **ASP.NET middleware** - UseElectron() extension methods
- **WebHost integration** - Seamless ASP.NET + Electron hosting
- **Hot Reload support** - Enhanced debugging experience
- **Web-specific optimizations** - ASP.NET tailored performance
**When to use:**
- ASP.NET Core projects building Electron applications
- Applications requiring web server functionality
- Projects using MVC, Razor Pages, or Blazor
## 🏗 Architecture Benefits
### Separation of Concerns
- **Build logic separate from API** - Clean dependency management
- **Optional ASP.NET integration** - Use only what you need
- **Multi-project friendly** - Share APIs across projects without build conflicts
### Project Scenarios
**Single Project (ASP.NET):**
```xml
<ItemGroup>
<PackageReference Include="ElectronNET.Core" Version="1.0.0" />
<PackageReference Include="ElectronNET.Core.AspNet" Version="1.0.0" />
</ItemGroup>
```
**Single Project (Console):**
```xml
<ItemGroup>
<PackageReference Include="ElectronNET.Core" Version="1.0.0" />
</ItemGroup>
```
**Multi-Project Solution (ASP.NET):**
```xml
<!-- Startup project -->
<ItemGroup>
<PackageReference Include="ElectronNET.Core" Version="1.0.0" />
<PackageReference Include="ElectronNET.Core.AspNet" Version="1.0.0" />
</ItemGroup>
<!-- Class library projects -->
<ItemGroup>
<PackageReference Include="ElectronNET.Core.Api" Version="1.0.0" />
</ItemGroup>
```
**Multi-Project Solution (Console):**
```xml
<!-- Startup project -->
<ItemGroup>
<PackageReference Include="ElectronNET.Core" Version="1.0.0" />
</ItemGroup>
<!-- Class library projects -->
<ItemGroup>
<PackageReference Include="ElectronNET.Core.Api" Version="1.0.0" />
</ItemGroup>
```
## 🔗 Dependency Chain
```
ElectronNET.Core.AspNet → ElectronNET.Core.Api
ElectronNET.Core → ElectronNET.Core.Api
```
- **ElectronNET.Core.AspNet** depends on ElectronNET.Core.Api
- **ElectronNET.Core** depends on ElectronNET.Core.Api
- **ElectronNET.Core.Api** has no dependencies
## 💡 Recommendations
**Start with ElectronNET.Core** for new projects
**Add ElectronNET.Core.AspNet** only for ASP.NET applications
**Use ElectronNET.Core.Api** for class libraries and API-only scenarios
**Multi-project solutions** benefit from the modular architecture

View File

@@ -0,0 +1,94 @@
# Project Configuration
## 🔧 Visual Studio App Designer
Electron.NET provides close integration via the Visual Studio Project System and MSBuild. After adding the ElectronNET.Core package, you will see this in the project configuration page after double-click on the 'Properties' folder or right-click on the project and choosing 'Properties':
![App Designer1](../images/app_designer1.png)
![App Designer2](../images/app_designer2.png)
## Project File Settings
The same settings can be configured manually by editing the MSBuild properties in your `.csproj` file.
These are the current default values when you don't make any changes:
```xml
<PropertyGroup Label="ElectronNetCommon">
<ElectronVersion>30.4.0</ElectronVersion>
<ElectronBuilderVersion>26.0</ElectronBuilderVersion>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<ElectronSingleInstance>true</ElectronSingleInstance>
<ElectronSplashScreen></ElectronSplashScreen>
<ElectronIcon></ElectronIcon>
<ElectronPackageId>$(MSBuildProjectName.Replace(".", "-").ToLower())</ElectronPackageId>
<ElectronBuilderJson>electron-builder.json</ElectronBuilderJson>
<Title>$(MSBuildProjectName)</Title>
</PropertyGroup>
```
### Relation to package.json
ElectronNET.Core does not work with an `electron-manifest.json` file anymore.
Since electron builder still expects a `package.json` file to exist, ElectronNET.Core is creating this under the hood automatically during build. For reference, here's the package.json template file that is being used, so you can see how the MSBuild properties are being mapped to `package.json` data:
```json
{
"name": "$(ElectronPackageId)",
"productName": "$(ElectronTitle)",
"build": {
"appId": "$(ElectronPackageId)",
"linux": {
"desktop": {
"entry": { "Name": "$(Title)" }
},
"executableName": "$(ElectronPackageId)"
},
"deb": {
"desktop": {
"entry": { "Name": "$(Title)" }
}
}
},
"description": "$(Description)",
"version": "$(Version)",
"main": "main.js",
"author": {
"name": "$(Company)"
},
"license": "$(License)",
"executable": "$(TargetName)",
"singleInstance": "$(ElectronSingleInstance)",
"homepage": "$(ProjectUrl)",
"splashscreen": {
"imageFile": "$(ElectronSplashScreen)"
}
}
```
### Node.js Integration
Electron.NET requires Node.js integration to be enabled for IPC to function. If you are not using the IPC functionality you can disable Node.js integration like so:
```csharp
WebPreferences wp = new WebPreferences();
wp.NodeIntegration = false;
BrowserWindowOptions browserWindowOptions = new BrowserWindowOptions
{
WebPreferences = wp
};
```
## 🚀 Next Steps
- **[Startup Methods](Startup-Methods.md)** - Understanding launch scenarios
- **[Debugging](../Using/Debugging.md)** - Learn about ASP.NET debugging features
- **[Package Building](Package-Building.md)** - Create distributable packages

74
docs/Using/Custom_main.md Normal file
View File

@@ -0,0 +1,74 @@
# Using custom_main.js
This guide explains how to include and use a `custom_main.js` file in your Electron.NET application for advanced Electron/Node.js customization.
## Why use custom_main.js?
- Register custom protocol handlers (e.g., `myapp://`) — protocols must be registered before the app is fully initialized
- Integrate Node.js modules (e.g., telemetry, OS APIs)
- Control startup logic (abort, environment checks)
- Set up IPC messaging or preload scripts
## Step-by-Step Process
### 1. Create the custom_main.js file
Place your custom logic in `electron/custom_main.js`:
```javascript
module.exports.onStartup = function(host) {
// Example: Register a global shortcut for opening dev tools
const { app, globalShortcut, BrowserWindow } = require('electron');
app.on('ready', () => {
const ret = globalShortcut.register('Control+Shift+I', () => {
BrowserWindow.getAllWindows().forEach(win => win.webContents.openDevTools());
console.log('Ctrl+Shift+I is pressed: DevTools opened!');
});
});
app.on('will-quit', () => {
globalShortcut.unregisterAll();
});
return true;
};
```
### 2. Configure your .csproj to copy custom_main.js to output
Add this to your `.csproj` file:
```xml
<ItemGroup>
<None Update="electron\custom_main.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>.electron\custom_main.js</TargetPath>
</None>
</ItemGroup>
```
### 3. Build and run your app
Use the standard build/run commands:
```powershell
dotnet build
dotnet run
```
Electron.NET will automatically load and execute your `custom_main.js` before initializing the .NET backend.
## Advanced Usage
Use environment variables to control features:
```javascript
const env = process.env.ASPNETCORE_ENVIRONMENT || 'Production';
if (env === 'Development') { /* enable dev features */ }
```
## Notes
- `custom_main.js` must use CommonJS syntax (`module.exports.onStartup = ...`).
- Place the file in your source directory and copy it to `.electron` using `.csproj`.
- Electron.NET will abort startup if `onStartup` returns `false`.
### Complete example is available here [ElectronNetSampleApp](https://github.com/niteshsinghal85/ElectronNetSampleApp)

242
docs/Using/Debugging.md Normal file
View File

@@ -0,0 +1,242 @@
# Debugging
ElectronNET.Core transforms the debugging experience by providing native Visual Studio integration with multiple debugging modes. No more complex setup or manual process attachment—debugging now works as expected for .NET developers.
## 🎯 Debugging Modes
ElectronNET.Core supports three main debugging approaches, all configured through Visual Studio's launch profiles:
### 1. ASP.NET-First Debugging (Recommended)
Debug your .NET code directly with full Hot Reload support:
```json
{
"profiles": {
"ASP.Net (unpackaged)": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:8001/"
}
}
}
```
**Benefits:**
- ✅ Full C# debugging with breakpoints
- ✅ Hot Reload for ASP.NET code
- ✅ Edit-and-continue functionality
- ✅ Native Visual Studio debugging experience
### 2. Electron-First Debugging
Debug the Electron process when you need to inspect native Electron APIs:
```json
{
"profiles": {
"Electron (unpackaged)": {
"commandName": "Executable",
"executablePath": "node",
"commandLineArgs": "node_modules/electron/cli.js main.js -unpackedelectron",
"workingDirectory": "$(TargetDir).electron",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
```
**Benefits:**
- ✅ Debug Electron main process
- ✅ Inspect native Electron APIs
- ✅ Node.js debugging capabilities
### 3. Cross-Platform WSL Debugging
Debug Linux builds directly from Windows Visual Studio:
```json
{
"profiles": {
"WSL": {
"commandName": "WSL2",
"launchUrl": "http://localhost:8001/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "http://localhost:8001/"
},
"distributionName": ""
}
}
}
```
**Benefits:**
- ✅ Debug Linux applications from Windows
- ✅ Test Linux-specific behavior
- ✅ Validate cross-platform compatibility
## 🔧 Setup Instructions
### 1. Configure Launch Settings
Add the debugging profiles to `Properties/launchSettings.json`:
```json
{
"profiles": {
"ASP.Net (unpackaged)": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:8001/"
},
"Electron (unpackaged)": {
"commandName": "Executable",
"executablePath": "node",
"commandLineArgs": "node_modules/electron/cli.js main.js -unpackedelectron",
"workingDirectory": "$(TargetDir).electron",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WSL": {
"commandName": "WSL2",
"launchUrl": "http://localhost:8001/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "http://localhost:8001/"
},
"distributionName": ""
}
}
}
```
### 2. Switch Runtime Identifiers
When switching between Windows and WSL debugging:
1. **Right-click your project** in Solution Explorer
2. Select **Properties**
3. Adjust the Runtime Identifier
Without Visual Studio:
1. **Edit** the .csproj file
2. **Update the RuntimeIdentifier**:
```xml
<!-- For Windows debugging -->
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<!-- For WSL/Linux debugging -->
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
```
### 3. Enable WSL Debugging
For WSL debugging, ensure:
- **WSL2 is installed** and configured
- **Linux distribution** is set in the launch profile
- **Project targets Linux RID** for WSL debugging
## 🚀 Debugging Workflow
### ASP.NET-First Debugging (Default)
1. **Select "ASP.Net (unpackaged)"** profile in Visual Studio
2. **Press F5** to start debugging
3. **Set breakpoints** in your C# code
4. **Use Hot Reload** to edit ASP.NET code during runtime
5. **Stop debugging** when finished
### Electron Process Debugging
1. **Select "Electron (unpackaged)"** profile
2. **Press F5** to start debugging
3. **Attach to Electron process** if needed
4. **Debug Node.js and Electron APIs**
### Cross-Platform Debugging
1. **Set RuntimeIdentifier** to `linux-x64`
2. **Select "WSL"** profile
3. **Press F5** to debug in WSL
4. **Test Linux-specific behavior**
## 🔍 Debugging Tips
### Hot Reload
- **Works with ASP.NET-first debugging**
- **Edit Razor views, controllers, and pages**
- **See changes instantly** without restart
- **Preserves application state**
### Breakpoint Debugging
```csharp
// Set breakpoints here
public async Task<IActionResult> Index()
{
var data = await GetData(); // ← Breakpoint
return View(data);
}
```
### Process Management
- **ASP.NET-first mode** automatically manages Electron process lifecycle
- **Proper cleanup** on debugging session end
- **No manual process killing** required
## 🛠 Troubleshooting
### Common Issues
**"Electron process not found"**
- Ensure Node.js 22.x is installed
- Check that packages are restored (`dotnet restore`)
- Verify RuntimeIdentifier matches your target platform
**"WSL debugging fails"**
- Install and configure WSL2
- Ensure Linux distribution is properly set up
- Check that project targets correct RID
**"Hot Reload not working"**
- Use ASP.NET-first debugging profile
- Ensure ASPNETCORE_ENVIRONMENT=Development
- Check for compilation errors
## 🎨 Visual Debugging
*Placeholder for image showing Visual Studio debugging interface with Electron.NET*
The debugging interface provides familiar Visual Studio tools:
- **Locals and Watch windows** for variable inspection
- **Call Stack** for method call tracing
- **Immediate Window** for runtime evaluation
- **Hot Reload** indicator for edit-and-continue
## 🚀 Next Steps
- **[Startup Methods](Startup-Methods.md)** - Understanding different launch scenarios
- **[Package Building](Package-Building.md)** - Debug packaged applications
- **[Migration Guide](../Core/Migration-Guide.md)** - Moving from old debugging workflows
## 💡 Benefits
**Native Visual Studio Experience** - No complex setup or manual attachment
**Hot Reload Support** - Edit ASP.NET code during debugging
**Cross-Platform Debugging** - Debug Linux apps from Windows
**Multiple Debugging Modes** - Choose the right approach for your needs
**Process Lifecycle Management** - Automatic cleanup and proper termination

View File

@@ -0,0 +1,237 @@
# Package Building
ElectronNET.Core integrates with Visual Studio's publishing system to create distributable Electron packages using electron-builder. The process leverages .NET's build system while automatically generating the necessary Electron configuration files.
## 🎯 Publishing Overview
The publishing process differs slightly between ASP.NET and console applications:
- **ASP.NET Apps** - Use folder publishing with SelfContained=true
- **Console Apps** - Use folder publishing with SelfContained=false
## 🚀 Publishing Process
### Step 1: Create Publish Profiles
Add publish profiles to `Properties/PublishProfiles/`:
#### ASP.NET Application Profile (Windows)
**win-x64.pubxml:**
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<DeleteExistingFiles>true</DeleteExistingFiles>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>
```
#### ASP.NET Application Profile (Linux)
**linux-x64.pubxml:**
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<DeleteExistingFiles>true</DeleteExistingFiles>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>
```
#### ASP.NET Application Profile (macOS Apple Silicon ARM64)
**osx-arm64.pubxml:**
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<DeleteExistingFiles>true</DeleteExistingFiles>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>osx-arm64</RuntimeIdentifier>
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>
```
#### ASP.NET Application Profile (macOS Intel x64)
**osx-x64.pubxml:**
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<DeleteExistingFiles>true</DeleteExistingFiles>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>osx-x64</RuntimeIdentifier>
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>
```
#### Console Application Profile (Windows)
**win-x64.pubxml:**
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
<PublishReadyToRun>false</PublishReadyToRun>
</PropertyGroup>
</Project>
```
#### Console Application Profile (Linux)
**linux-x64.pubxml:**
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
</PropertyGroup>
</Project>
```
#### Console Application Profile (macOS Apple Silicon ARM64)
**osx-arm64.pubxml:**
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>osx-arm64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
</PropertyGroup>
</Project>
```
#### Console Application Profile (macOS Intel x64)
**osx-x64.pubxml:**
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>osx-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
</PropertyGroup>
</Project>
```
### Step 2: Configure Electron Builder
ElectronNET.Core automatically adds a default `electron-builder.json` file under `Properties\electron-builder.json`.
Please see here for details of the available configuration options: https://www.electron.build/.
### Step 3: Publish from Visual Studio
1. **Right-click your project** in Solution Explorer
2. **Select "Publish"**
4. **Select your publish profile** (Windows/Linux)
5. **Click "Publish"**
The publish process will:
- Build your .NET application
- Copy all files as needed
- Install npm dependencies
- Run electron-builder
> [!NOTE]
> When running publish for a Linux configuration on Windows, Electron.NET will automatically use WSL for the platform-specific steps.
**After publishing**, the final results will be in
`publish\Release\netx.0\xxx-xxx\`
## MacOS
> [!NOTE]
> macOS builds can't be created on Windows machines because they require symlinks that aren't supported on Windows (per [this Electron issue](https://github.com/electron-userland/electron-packager/issues/71)). macOS builds can be produced on either Linux or macOS machines.
## 🚀 Next Steps
- **[Startup Methods](Startup-Methods.md)** - Understanding different launch modes for packaged apps
- **[Debugging](Debugging.md)** - Debug packaged applications
- **[Migration Guide](../Core/Migration-Guide.md)** - Update existing projects for new publishing
## 💡 Benefits
**Native VS Integration** - Use familiar publish workflows
**Cross-Platform Building** - Build Linux packages from Windows
**Automatic Configuration** - No manual electron-builder setup
**Multiple Package Types** - NSIS, AppImage, DMG, etc.
**CI/CD Ready** - Easy integration with build pipelines

View File

@@ -0,0 +1,246 @@
# Startup Methods
ElectronNET.Core supports multiple startup methods to handle different development and deployment scenarios. The framework automatically detects the appropriate mode based on command-line flags and environment.
## 🎯 Startup Scenarios
The framework supports **8 different launch scenarios** covering every combination of:
- **Packaged vs Unpackaged** deployment
- **Console vs ASP.NET** application types
- **Dotnet-first vs Electron-first** initialization
## 🚀 Command-Line Flags
### Unpackaged Debugging Modes
#### **`-unpackedelectron`** - Electron-first debugging
```bash
# Launch Electron first, which then starts .NET
node node_modules/electron/cli.js main.js -unpackedelectron
```
#### **`-unpackeddotnet`** - .NET-first debugging
```bash
# Launch .NET first, which then starts Electron
dotnet run -unpackeddotnet
```
### Packaged Deployment Modes
#### **`-dotnetpacked`** - .NET-first packaged execution
```bash
# Run packaged app with .NET starting first
MyApp.exe -dotnetpacked
```
#### **No flags** - Electron-first packaged execution (default)
```bash
# Run packaged app with Electron starting first
MyApp.exe
```
## 📋 Startup Method Details
### 1. Unpackaged + Electron-First (Development)
- **Use Case**: Debug Electron main process and Node.js code
- **Command**: `-unpackedelectron` flag
- **Process Flow**:
1. Electron starts first
2. Electron launches .NET process
3. .NET connects back to Electron
4. Application runs with Electron in control
### 2. Unpackaged + .NET-First (Development)
- **Use Case**: Debug ASP.NET/C# code with Hot Reload
- **Command**: `-unpackeddotnet` flag
- **Process Flow**:
1. .NET application starts first
2. .NET launches Electron process
3. Electron connects back to .NET
4. Application runs with .NET in control
### 3. Packaged + .NET-First (Production)
- **Use Case**: Deployed application with .NET controlling lifecycle
- **Command**: `-dotnetpacked` flag
- **Process Flow**:
1. .NET executable starts first
2. .NET launches Electron from packaged files
3. Electron loads from app.asar or extracted files
4. .NET maintains process control
### 4. Packaged + Electron-First (Production)
- **Use Case**: Traditional Electron app behavior
- **Command**: No special flags
- **Process Flow**:
1. Electron executable starts first
2. Electron launches .NET from packaged files
3. .NET runs from Electron's process context
4. Electron maintains UI control
## 🔧 Configuration Examples
### ASP.NET Application Startup
```csharp
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Configure for different startup modes
builder.WebHost.UseElectron(args, async () =>
{
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions { Show = false });
await browserWindow.WebContents.LoadURLAsync("http://localhost:8001");
browserWindow.OnReadyToShow += () => browserWindow.Show();
});
var app = builder.Build();
app.Run();
```
### Console Application Startup
```csharp
// Program.cs
public static async Task Main(string[] args)
{
var runtimeController = ElectronNetRuntime.RuntimeController;
await runtimeController.Start();
await runtimeController.WaitReadyTask;
await InitializeApplication();
await runtimeController.WaitStoppedTask;
}
```
## 🎨 Visual Process Flow
![Startup Modes](../images/startup_modes.png)
The image above illustrates how each combination of deployment type, application type, and initialization order affects the process lifecycle.
## 🚀 Development Workflows
### Debugging Workflow
**ASP.NET-First Debugging** (Recommended)
```json
// launchSettings.json
{
"ASP.Net (unpackaged)": {
"commandName": "Project",
"commandLineArgs": "-unpackeddotnet"
}
}
```
**Electron-First Debugging**
```json
// launchSettings.json
{
"Electron (unpackaged)": {
"commandName": "Executable",
"executablePath": "node",
"commandLineArgs": "node_modules/electron/cli.js main.js -unpackedelectron"
}
}
```
### Production Deployment
**Dotnet-First Deployment**
```bash
# Build and package
dotnet publish -c Release -r win-x64
cd publish\Release\net8.0\win-x64
npm install
npx electron-builder
# Run with dotnet-first
MyApp.exe -dotnetpacked
```
**Electron-First Deployment** (Default)
```bash
# Run packaged application (no special flags needed)
MyApp.exe
```
## 🔍 Process Lifecycle Management
### Automatic Cleanup
ElectronNET.Core automatically manages process lifecycle:
- **Graceful shutdown** when main window is closed
- **Proper cleanup** of child processes
- **Error handling** for process failures
- **Cross-platform compatibility** for process management
### Manual Control
Access runtime controller for advanced scenarios:
```csharp
var runtime = ElectronNetRuntime.RuntimeController;
// Wait for Electron to be ready
await runtime.WaitReadyTask;
// Stop Electron runtime
await runtime.Stop();
await runtime.WaitStoppedTask;
```
## 🛠 Troubleshooting
### Common Startup Issues
**"Electron process not found"**
- Ensure Node.js 22.x is installed
- Check that .NET build succeeded
- Verify RuntimeIdentifier is set correctly
**"Port conflicts"**
- Use different ports for different startup modes
- Check that no other instances are running
- Verify firewall settings
**"Process won't terminate"**
- Use dotnet-first mode for better cleanup
- Check for unhandled exceptions
- Verify all windows are properly closed
## 💡 Best Practices
### Choose the Right Mode
- **Development**: Use .NET-first for C# debugging, Electron-first for Node.js debugging
- **Production**: Use .NET-first for better process control, Electron-first for traditional behavior
- **Cross-platform**: Use .NET-first for consistent behavior across platforms
### Environment Configuration
```xml
<!-- .csproj -->
<PropertyGroup>
<ElectronNETCoreEnvironment>Production</ElectronNETCoreEnvironment>
</PropertyGroup>
```
## 🚀 Next Steps
- **[Debugging](Debugging.md)** - Debug different startup modes
- **[Package Building](Package-Building.md)** - Package for different deployment scenarios
- **[Migration Guide](../Core/Migration-Guide.md)** - Update existing apps for new startup methods
## 🎯 Summary
The flexible startup system ensures ElectronNET.Core works optimally in every scenario while providing the control and debugging experience .NET developers expect. Choose the appropriate mode based on your development workflow and deployment requirements.

2
docs/_Footer.md Normal file
View File

@@ -0,0 +1,2 @@
Want to contribute to this documentation? Please fork and create a PR! The Wiki is autogenerated from the /docs content in the repository.

52
docs/_Sidebar.md Normal file
View File

@@ -0,0 +1,52 @@
<!-- First line gets deleted -->
# Wiki
- [Home](Home.md)
- [About this Project](About.md)
# Electron.NET Core
- [What's new?](Core/What's-New.md)
- [Migration Guide](Core/Migration-Guide.md)
- [Migration Checks](Core/Migration-Checks.md)
- [Advanced Migration](Core/Advanced-Migration-Topics.md)
# Getting Started
- [System Requirements](GettingStarted/System-Requirements.md)
- [With ASP.Net](GettingStarted/ASP.Net.md)
- [With a Console App](GettingStarted/Console-App.md)
# Using Electron.NET
- [Configuration](Using/Configuration.md)
- [Startup-Methods](Using/Startup-Methods.md)
- [Debugging](Using/Debugging.md)
- [Package Building](Using/Package-Building.md)
- [Adding a `custom_main.js`](Using/Custom_main.md)
# API Reference
- [API Overview](API/Overview.md)
- [Electron.App](API/App.md)
- [Electron.Dialog](API/Dialog.md)
- [Electron.Menu](API/Menu.md)
- [Electron.WindowManager](API/WindowManager.md)
- [Electron.Shell](API/Shell.md)
- [Electron.Screen](API/Screen.md)
- [Electron.Notification](API/Notification.md)
- [Electron.Tray](API/Tray.md)
- [Electron.Clipboard](API/Clipboard.md)
- [Electron.Dock](API/Dock.md)
- [Electron.HostHook](API/HostHook.md)
- [Electron.IpcMain](API/IpcMain.md)
- [Electron.GlobalShortcut](API/GlobalShortcut.md)
- [Electron.AutoUpdater](API/AutoUpdater.md)
- [Electron.NativeTheme](API/NativeTheme.md)
- [Electron.PowerMonitor](API/PowerMonitor.md)
# Release Information
- [Package Description](RelInfo/Package-Description.md)
- [Changelog](RelInfo/Changelog.md)

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

7857
docs/md-styles.css Normal file

File diff suppressed because it is too large Load Diff

7
global.json Normal file
View File

@@ -0,0 +1,7 @@
{
"sdk": {
"version": "10.0.100",
"rollForward": "feature",
"allowPrerelease": false
}
}

View File

@@ -3,6 +3,7 @@ using Nuke.Common;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.GitHub;
using Nuke.Common.Tools.NuGet;
@@ -15,9 +16,9 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
// ReSharper disable ArrangeThisQualifier
class Build : NukeBuild
{
@@ -27,25 +28,20 @@ class Build : NukeBuild
/// - Microsoft VisualStudio https://nuke.build/visualstudio
/// - Microsoft VSCode https://nuke.build/vscode
public static int Main () => Execute<Build>(x => x.RunUnitTests);
public static int Main() => Execute<Build>(x => x.RunUnitTests);
[Nuke.Common.Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Nuke.Common.Parameter("ReleaseNotesFilePath - To determine the SemanticVersion")]
[Nuke.Common.Parameter("ReleaseNotesFilePath - To determine the lates changelog version")]
readonly AbsolutePath ReleaseNotesFilePath = RootDirectory / "Changelog.md";
[Nuke.Common.Parameter("common.props file path - to determine the configured version")]
readonly AbsolutePath CommonPropsFilePath = RootDirectory / "src" / "common.props";
[Solution]
readonly Solution Solution;
string TargetProjectName => "ElectronNET";
string ApiTargetLibName => $"{TargetProjectName}.API";
string CliTargetLibName => $"{TargetProjectName}.CLI";
string DemoTargetLibName => $"{TargetProjectName}.WebApp";
AbsolutePath SourceDirectory => RootDirectory / "src";
AbsolutePath ResultDirectory => RootDirectory / "artifacts";
@@ -60,16 +56,7 @@ class Build : NukeBuild
string Version { get; set; }
AbsolutePath[] Projects
{
get
{
var api = SourceDirectory / ApiTargetLibName / $"{ApiTargetLibName}.csproj";
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
var projects = new[] { api, cli };
return projects;
}
}
string VersionPostFix { get; set; }
protected override void OnBuildInitialized()
{
@@ -82,9 +69,19 @@ class Build : NukeBuild
LatestReleaseNotes = ChangeLog.First();
LatestReleaseNotes.NotNull("LatestVersion could not be read!");
Log.Debug("Using LastestVersion from ChangeLog: {LatestVersion}", LatestReleaseNotes.Version);
var propsParser = new CommonPropsParser();
var propsVersion = propsParser.Parse(CommonPropsFilePath);
propsVersion.NotNull("Version from common.props could not be read!");
Assert.True(propsVersion == LatestReleaseNotes.Version,
$"The version in common.props ({propsVersion}) does not " +
$"equal the latest version in the changelog ({LatestReleaseNotes.Version})");
Log.Debug("Using version: {LatestVersion}", propsVersion);
SemVersion = LatestReleaseNotes.SemVersion;
Version = LatestReleaseNotes.Version.ToString();
Version = propsVersion.ToString();
if (GitHubActions != null)
{
@@ -94,145 +91,60 @@ class Build : NukeBuild
if (ScheduledTargets.Contains(Default))
{
Version = $"{Version}-ci.{buildNumber}";
VersionPostFix = $"-ci.{buildNumber}";
}
else if (ScheduledTargets.Contains(PrePublish))
{
Version = $"{Version}-alpha.{buildNumber}";
VersionPostFix = $"-pre.{buildNumber}";
}
}
else if (ScheduledTargets.Contains(PrePublish))
{
VersionPostFix = $"-pre";
}
Log.Information("Building version: {Version}", Version);
Log.Information("Building version {Version} with postfix {VersionPostFix}", Version, VersionPostFix);
}
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory);
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(dir => dir.DeleteDirectory());
});
Target Restore => _ => _
.Executes(() =>
{
Projects.ForEach(project =>
{
DotNetRestore(s => s
.SetProjectFile(project));
});
DotNetRestore(s => s.SetProjectFile(Solution));
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() =>
{
Projects.ForEach(project =>
{
DotNetBuild(s => s
.SetProjectFile(project)
.SetVersion(Version)
.SetConfiguration(Configuration)
.EnableNoRestore());
});
DotNetBuild(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.SetProperty("GeneratePackageOnBuild", "True")
.SetProperty("VersionPostFix", VersionPostFix ?? string.Empty));
});
Target RunUnitTests => _ => _
.DependsOn(Compile)
.Executes(() =>
{
Projects.ForEach(project =>
{
DotNetTest(s => s
.SetProjectFile(project)
.SetConfiguration(Configuration)
.EnableNoRestore()
.EnableNoBuild());
});
});
var TestProject = SourceDirectory / "ElectronNET.IntegrationTests" / "ElectronNET.IntegrationTests.csproj";
Target CreatePackages => _ => _
.DependsOn(Compile)
.Executes(() =>
{
Projects.ForEach(project =>
{
DotNetPack(s => s
.SetProject(project)
.SetVersion(Version)
.SetConfiguration(Configuration)
.SetOutputDirectory(ResultDirectory)
.SetIncludeSymbols(true)
.SetSymbolPackageFormat("snupkg")
.EnableNoRestore()
);
});
});
Target CompileSample => _ => _
.DependsOn(Compile)
.Executes(() =>
{
var sample = SourceDirectory / DemoTargetLibName / $"{DemoTargetLibName}.csproj";
DotNetBuild(s => s.SetProjectFile(sample).SetConfiguration(Configuration));
});
Target ElectronizeGenericTargetSample => _ => _
.DependsOn(CompileSample)
.Executes(() =>
{
var sample = SourceDirectory / DemoTargetLibName;
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
var args = "build /target custom win7-x86;win /dotnet-configuration Debug /electron-arch ia32 /electron-params \"--publish never\"";
DotNet($"run --project {cli} -- {args}", sample);
});
Target ElectronizeWindowsTargetSample => _ => _
.DependsOn(CompileSample)
.Executes(() =>
{
var sample = SourceDirectory / DemoTargetLibName;
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
var args = "build /target win /electron-params \"--publish never\"";
DotNet($"run --project {cli} -- {args}", sample);
});
Target ElectronizeCustomWin7TargetSample => _ => _
.DependsOn(CompileSample)
.Executes(() =>
{
var sample = SourceDirectory / DemoTargetLibName;
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
var args = "build /target custom win7-x86;win /electron-params \"--publish never\"";
DotNet($"run --project {cli} -- {args}", sample);
});
Target ElectronizeMacOsTargetSample => _ => _
.DependsOn(CompileSample)
.Executes(() =>
{
var sample = SourceDirectory / DemoTargetLibName;
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
var args = "build /target osx /electron-params \"--publish never\"";
DotNet($"run --project {cli} -- {args}", sample);
});
Target ElectronizeLinuxTargetSample => _ => _
.DependsOn(CompileSample)
.Executes(() =>
{
var sample = SourceDirectory / DemoTargetLibName;
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
var args = "build /target linux /electron-params \"--publish never\"";
DotNet($"run --project {cli} -- {args}", sample);
DotNetTest(s => s
.SetProjectFile(TestProject)
.SetConfiguration(Configuration)
.When(_ => GitHubActions.Instance is not null, x => x.SetLoggers("GitHubActions"))
);
});
Target PublishPackages => _ => _
.DependsOn(CreatePackages)
.DependsOn(Compile)
.DependsOn(RunUnitTests)
.Executes(() =>
{
@@ -244,7 +156,7 @@ class Build : NukeBuild
throw new BuildAbortedException("Could not resolve the NuGet API key.");
}
foreach (var nupkg in GlobFiles(ResultDirectory, "*.nupkg"))
foreach (var nupkg in ResultDirectory.GlobFiles("*.nupkg"))
{
DotNetNuGetPush(s => s
.SetTargetPath(nupkg)
@@ -280,9 +192,9 @@ class Build : NukeBuild
new InMemoryCredentialStore(credentials));
GitHubTasks.GitHubClient.Repository.Release
.Create("ElectronNET", "Electron.NET", new NewRelease(Version)
.Create("ElectronNET", "Electron.NET", new NewRelease(Version + VersionPostFix)
{
Name = Version,
Name = "ElectronNET.Core " + Version + VersionPostFix,
Body = String.Join(Environment.NewLine, LatestReleaseNotes.Notes),
Prerelease = true,
TargetCommitish = "develop",
@@ -318,7 +230,7 @@ class Build : NukeBuild
GitHubTasks.GitHubClient.Repository.Release
.Create("ElectronNET", "Electron.NET", new NewRelease(Version)
{
Name = Version,
Name = "ElectronNET.Core " + Version,
Body = String.Join(Environment.NewLine, LatestReleaseNotes.Notes),
Prerelease = false,
TargetCommitish = "main",
@@ -327,7 +239,7 @@ class Build : NukeBuild
Target Package => _ => _
.DependsOn(RunUnitTests)
.DependsOn(CreatePackages);
.DependsOn(Compile);
Target Default => _ => _
.DependsOn(Package);

33
nuke/CommonPropsParser.cs Normal file
View File

@@ -0,0 +1,33 @@
using System;
using System.Linq;
using System.Xml.Linq;
/// <summary>
/// Parses a version from an MSBuild .props file (XML).
/// </summary>
public sealed class CommonPropsParser
{
/// <summary>
/// Initializes a new instance of the <see cref="ReleaseNotesParser"/> class.
/// </summary>
public CommonPropsParser()
{
}
public Version Parse(string propsPath)
{
var doc = XDocument.Load(propsPath);
var versionElement = doc
.Descendants()
.FirstOrDefault(e => e.Name.LocalName == "Version");
if (Version.TryParse(versionElement?.Value.Trim(), out var version))
{
version = new Version(version.Major, version.Minor, version.Build);
return version;
}
return null;
}
}

View File

@@ -85,7 +85,7 @@ public sealed class ReleaseNotesParser
// Parse content.
var notes = new List<string>();
while (true)
{
// Sanity checks.

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace></RootNamespace>
<NoWarn>CS0649;CS0169</NoWarn>
<NukeRootDirectory>..</NukeRootDirectory>
@@ -11,11 +11,13 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Nuke.Common" Version="6.2.1" />
<PackageReference Include="Microsoft.Build" Version="18.0.2" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="18.0.2" />
<PackageReference Include="Nuke.Common" Version="10.1.0" />
</ItemGroup>
<ItemGroup>
<PackageDownload Include="NuGet.CommandLine" Version="[6.3.1]" />
<PackageDownload Include="NuGet.CommandLine" Version="[6.12.2]" />
</ItemGroup>
</Project>

4
src/.editorconfig Normal file
View File

@@ -0,0 +1,4 @@
[*.cs]
# CA1416: Validate platform compatibility
dotnet_diagnostic.CA1416.severity = error

View File

@@ -0,0 +1,382 @@
// ReSharper disable InconsistentNaming
namespace ElectronNET.API
{
using Common;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
public abstract class ApiBase
{
protected enum SocketTaskEventNameTypes
{
DashesLowerFirst,
NoDashUpperFirst
}
protected enum SocketTaskMessageNameTypes
{
DashesLowerFirst,
NoDashUpperFirst
}
protected enum SocketEventNameTypes
{
DashedLower,
CamelCase,
}
private static readonly TimeSpan InvocationTimeout = 1000.ms();
private readonly string objectName;
private readonly ConcurrentDictionary<string, Invocator> invocators;
private readonly ConcurrentDictionary<string, string> invocationEventNames = new();
private readonly ConcurrentDictionary<string, string> invocationMessageNames = new();
private readonly ConcurrentDictionary<string, string> methodMessageNames = new();
private static readonly ConcurrentDictionary<string, EventContainer> eventContainers = new();
private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, Invocator>> AllInvocators = new();
private readonly object objLock = new object();
public virtual int Id
{
get => -1;
// ReSharper disable once ValueParameterNotUsed
protected set
{
}
}
protected abstract SocketTaskEventNameTypes SocketTaskEventNameType { get; }
protected virtual SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.NoDashUpperFirst;
protected virtual SocketEventNameTypes SocketEventNameType => SocketEventNameTypes.DashedLower;
protected ApiBase()
{
this.objectName = this.GetType().Name.LowerFirst();
this.invocators = AllInvocators.GetOrAdd(this.objectName, _ => new ConcurrentDictionary<string, Invocator>());
}
protected void CallMethod0([CallerMemberName] string callerName = null)
{
var messageName = this.methodMessageNames.GetOrAdd(callerName, s => this.objectName + s);
if (this.Id >= 0)
{
BridgeConnector.Socket.Emit(messageName, this.Id);
}
else
{
BridgeConnector.Socket.Emit(messageName);
}
}
protected void CallMethod1(object val1, [CallerMemberName] string callerName = null)
{
var messageName = this.methodMessageNames.GetOrAdd(callerName, s => this.objectName + s);
if (this.Id >= 0)
{
BridgeConnector.Socket.Emit(messageName, this.Id, val1);
}
else
{
BridgeConnector.Socket.Emit(messageName, val1);
}
}
protected void CallMethod2(object val1, object val2, [CallerMemberName] string callerName = null)
{
var messageName = this.methodMessageNames.GetOrAdd(callerName, s => this.objectName + s);
if (this.Id >= 0)
{
BridgeConnector.Socket.Emit(messageName, this.Id, val1, val2);
}
else
{
BridgeConnector.Socket.Emit(messageName, val1, val2);
}
}
protected void CallMethod3(object val1, object val2, object val3, [CallerMemberName] string callerName = null)
{
var messageName = this.methodMessageNames.GetOrAdd(callerName, s => this.objectName + s);
if (this.Id >= 0)
{
BridgeConnector.Socket.Emit(messageName, this.Id, val1, val2, val3);
}
else
{
BridgeConnector.Socket.Emit(messageName, val1, val2, val3);
}
}
protected Task<T> InvokeAsync<T>(object arg = null, [CallerMemberName] string callerName = null)
{
return this.InvokeAsyncWithTimeout<T>(InvocationTimeout, arg, callerName);
}
protected Task<T> InvokeAsyncWithTimeout<T>(TimeSpan invocationTimeout, object arg = null, [CallerMemberName] string callerName = null)
{
Debug.Assert(callerName != null, nameof(callerName) + " != null");
lock (this.objLock)
{
return this.invocators.GetOrAdd(callerName, _ =>
{
var getter = new Invocator<T>(this, callerName, invocationTimeout, arg);
getter.Task<T>().ContinueWith(_ =>
{
lock (this.objLock)
{
return this.invocators.TryRemove(callerName, out var _);
}
});
return getter;
}).Task<T>();
}
}
protected void AddEvent(Action value, int? id = null, [CallerMemberName] string callerName = null)
{
Debug.Assert(callerName != null, nameof(callerName) + " != null");
var eventName = this.EventName(callerName);
var eventKey = this.EventKey(eventName, id);
lock (this.objLock)
{
var container = eventContainers.GetOrAdd(eventKey, _ =>
{
var container = new EventContainer();
BridgeConnector.Socket.On(eventKey, container.OnEventAction);
BridgeConnector.Socket.Emit($"register-{eventName}", id);
return container;
});
container.Register(value);
}
}
protected void RemoveEvent(Action value, int? id = null, [CallerMemberName] string callerName = null)
{
Debug.Assert(callerName != null, nameof(callerName) + " != null");
var eventName = this.EventName(callerName);
var eventKey = this.EventKey(eventName, id);
lock (this.objLock)
{
if (eventContainers.TryGetValue(eventKey, out var container) && !container.Unregister(value))
{
BridgeConnector.Socket.Off(eventKey);
eventContainers.TryRemove(eventKey, out _);
}
}
}
protected void AddEvent<T>(Action<T> value, int? id = null, [CallerMemberName] string callerName = null)
{
Debug.Assert(callerName != null, nameof(callerName) + " != null");
var eventName = this.EventName(callerName);
var eventKey = this.EventKey(eventName, id);
lock (this.objLock)
{
var container = eventContainers.GetOrAdd(eventKey, _ =>
{
var container = new EventContainer();
BridgeConnector.Socket.On<T>(eventKey, container.OnEventActionT);
BridgeConnector.Socket.Emit($"register-{eventName}", id);
return container;
});
container.Register(value);
}
}
protected void RemoveEvent<T>(Action<T> value, int? id = null, [CallerMemberName] string callerName = null)
{
Debug.Assert(callerName != null, nameof(callerName) + " != null");
var eventName = this.EventName(callerName);
var eventKey = this.EventKey(eventName, id);
lock (this.objLock)
{
if (eventContainers.TryGetValue(eventKey, out var container) && !container.Unregister(value))
{
BridgeConnector.Socket.Off(eventKey);
eventContainers.TryRemove(eventKey, out _);
}
}
}
private string EventName(string callerName)
{
switch (this.SocketEventNameType)
{
case SocketEventNameTypes.DashedLower:
return $"{this.objectName}-{callerName.ToDashedEventName()}";
case SocketEventNameTypes.CamelCase:
return $"{this.objectName}-{callerName.ToCamelCaseEventName()}";
default:
throw new ArgumentOutOfRangeException();
}
}
private string EventKey(string eventName, int? id)
{
return string.Format(CultureInfo.InvariantCulture, "{0}{1:D}", eventName, id);
}
internal abstract class Invocator
{
public abstract Task<T> Task<T>();
}
internal class Invocator<T> : Invocator
{
private readonly Task<T> tcsTask;
private TaskCompletionSource<T> tcs;
public Invocator(ApiBase apiBase, string callerName, TimeSpan timeout, object arg = null)
{
this.tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
this.tcsTask = this.tcs.Task;
string eventName;
string messageName;
switch (apiBase.SocketTaskEventNameType)
{
case SocketTaskEventNameTypes.DashesLowerFirst:
eventName = apiBase.invocationEventNames.GetOrAdd(callerName, s => $"{apiBase.objectName}-{s.StripAsync().LowerFirst()}-completed");
break;
case SocketTaskEventNameTypes.NoDashUpperFirst:
eventName = apiBase.invocationEventNames.GetOrAdd(callerName, s => $"{apiBase.objectName}{s.StripAsync()}Completed");
break;
default:
throw new ArgumentOutOfRangeException();
}
switch (apiBase.SocketTaskMessageNameType)
{
case SocketTaskMessageNameTypes.DashesLowerFirst:
messageName = apiBase.invocationMessageNames.GetOrAdd(callerName, s => $"{apiBase.objectName}-{s.StripAsync().LowerFirst()}");
break;
case SocketTaskMessageNameTypes.NoDashUpperFirst:
messageName = apiBase.invocationMessageNames.GetOrAdd(callerName, s => apiBase.objectName + s.StripAsync());
break;
default:
throw new ArgumentOutOfRangeException();
}
BridgeConnector.Socket.Once<T>(eventName, (result) =>
{
lock (this)
{
try
{
var value = result;
this.tcs?.SetResult(value);
}
catch (Exception ex)
{
this.tcs?.TrySetException(ex);
}
finally
{
this.tcs = null;
}
}
});
if (arg != null)
{
_ = apiBase.Id >= 0 ? BridgeConnector.Socket.Emit(messageName, apiBase.Id, arg) : BridgeConnector.Socket.Emit(messageName, arg);
}
else
{
_ = apiBase.Id >= 0 ? BridgeConnector.Socket.Emit(messageName, apiBase.Id) : BridgeConnector.Socket.Emit(messageName);
}
System.Threading.Tasks.Task.Delay(timeout).ContinueWith(_ =>
{
if (this.tcs != null)
{
lock (this)
{
if (this.tcs != null)
{
var ex = new TimeoutException(
$"No response after {(long)timeout.TotalMilliseconds}ms trying to retrieve value {apiBase.objectName}.{callerName}()"
);
this.tcs.TrySetException(ex);
this.tcs = null;
}
}
}
});
}
public override Task<T1> Task<T1>()
{
return this.tcsTask as Task<T1>;
}
}
[SuppressMessage("ReSharper", "InconsistentlySynchronizedField")]
private class EventContainer
{
private Action eventAction;
private Delegate eventActionT;
private Action<T> GetEventActionT<T>()
{
return (Action<T>)this.eventActionT;
}
private void SetEventActionT<T>(Action<T> actionT)
{
this.eventActionT = actionT;
}
public void OnEventAction() => this.eventAction?.Invoke();
public void OnEventActionT<T>(T p) => this.GetEventActionT<T>()?.Invoke(p);
public void Register(Action receiver)
{
this.eventAction += receiver;
}
public void Register<T>(Action<T> receiver)
{
var actionT = this.GetEventActionT<T>();
actionT += receiver;
this.SetEventActionT(actionT);
}
public bool Unregister(Action receiver)
{
this.eventAction -= receiver;
return this.eventAction != null;
}
public bool Unregister<T>(Action<T> receiver)
{
var actionT = this.GetEventActionT<T>();
actionT -= receiver;
this.SetEventActionT(actionT);
return actionT != null;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,378 @@
using ElectronNET.API.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
// ReSharper disable InconsistentNaming
namespace ElectronNET.API
{
/// <summary>
/// Enable apps to automatically update themselves. Based on electron-updater.
/// </summary>
public sealed class AutoUpdater : ApiBase
{
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
protected override SocketEventNameTypes SocketEventNameType => SocketEventNameTypes.DashedLower;
/// <summary>
/// Whether to automatically download an update when it is found. (Default is true)
/// </summary>
public bool AutoDownload
{
get
{
return Task.Run(() => this.InvokeAsync<bool>()).Result;
}
set
{
BridgeConnector.Socket.Emit("autoUpdater-autoDownload-set", value);
}
}
/// <summary>
/// Whether to automatically install a downloaded update on app quit (if `QuitAndInstall` was not called before).
///
/// Applicable only on Windows and Linux.
/// </summary>
public bool AutoInstallOnAppQuit
{
get
{
return Task.Run(() => this.InvokeAsync<bool>()).Result;
}
set
{
BridgeConnector.Socket.Emit("autoUpdater-autoInstallOnAppQuit-set", value);
}
}
/// <summary>
/// *GitHub provider only.* Whether to allow update to pre-release versions.
/// Defaults to "true" if application version contains prerelease components (e.g. "0.12.1-alpha.1", here "alpha" is a prerelease component), otherwise "false".
///
/// If "true", downgrade will be allowed("allowDowngrade" will be set to "true").
/// </summary>
public bool AllowPrerelease
{
get
{
return Task.Run(() => this.InvokeAsync<bool>()).Result;
}
set
{
BridgeConnector.Socket.Emit("autoUpdater-allowPrerelease-set", value);
}
}
/// <summary>
/// *GitHub provider only.*
/// Get all release notes (from current version to latest), not just the latest (Default is false).
/// </summary>
public bool FullChangelog
{
get
{
return Task.Run(() => this.InvokeAsync<bool>()).Result;
}
set
{
BridgeConnector.Socket.Emit("autoUpdater-fullChangelog-set", value);
}
}
/// <summary>
/// Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).
/// Taken in account only if channel differs (pre-release version component in terms of semantic versioning).
/// Default is false.
/// </summary>
public bool AllowDowngrade
{
get
{
return Task.Run(() => this.InvokeAsync<bool>()).Result;
}
set
{
BridgeConnector.Socket.Emit("autoUpdater-allowDowngrade-set", value);
}
}
/// <summary>
/// For test only.
/// </summary>
public string UpdateConfigPath
{
get
{
return Task.Run(() => this.InvokeAsync<string>()).Result;
}
}
/// <summary>
/// The current application version
/// </summary>
public Task<SemVer> CurrentVersionAsync
{
get
{
return Task.Run(() => this.InvokeAsync<SemVer>());
}
}
/// <summary>
/// Get the update channel. Not applicable for GitHub.
/// Doesnt return channel from the update configuration, only if was previously set.
/// </summary>
[Obsolete("Use the asynchronous version ChannelAsync instead")]
public string Channel
{
get
{
return ChannelAsync.Result;
}
}
/// <summary>
/// Get the update channel. Not applicable for GitHub.
/// Doesnt return channel from the update configuration, only if was previously set.
/// </summary>
public Task<string> ChannelAsync
{
get
{
return Task.Run(() => this.InvokeAsync<string>());
}
}
/// <summary>
/// Set the update channel. Not applicable for GitHub.
/// </summary>
public string SetChannel
{
set
{
BridgeConnector.Socket.Emit("autoUpdater-channel-set", value);
}
}
/// <summary>
/// The request headers.
/// </summary>
public Task<Dictionary<string, string>> RequestHeadersAsync
{
get
{
return Task.Run(() => this.InvokeAsync<Dictionary<string, string>>());
}
}
/// <summary>
/// The request headers.
/// </summary>
public Dictionary<string, string> RequestHeaders
{
set
{
BridgeConnector.Socket.Emit("autoUpdater-requestHeaders-set", value);
}
}
/// <summary>
/// Emitted when there is an error while updating.
/// </summary>
public event Action<string> OnError
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when checking if an update has started.
/// </summary>
public event Action OnCheckingForUpdate
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when there is an available update.
/// The update is downloaded automatically if AutoDownload is true.
/// </summary>
public event Action<UpdateInfo> OnUpdateAvailable
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted when there is no available update.
/// </summary>
public event Action<UpdateInfo> OnUpdateNotAvailable
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted on download progress.
/// </summary>
public event Action<ProgressInfo> OnDownloadProgress
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
/// <summary>
/// Emitted on download complete.
/// </summary>
public event Action<UpdateInfo> OnUpdateDownloaded
{
add => AddEvent(value, GetHashCode());
remove => RemoveEvent(value, GetHashCode());
}
private static AutoUpdater _autoUpdater;
private static object _syncRoot = new object();
internal AutoUpdater()
{
}
internal static AutoUpdater Instance
{
get
{
if (_autoUpdater == null)
{
lock (_syncRoot)
{
if (_autoUpdater == null)
{
_autoUpdater = new AutoUpdater();
}
}
}
return _autoUpdater;
}
}
/// <summary>
/// Asks the server whether there is an update.
/// </summary>
/// <returns></returns>
public Task<UpdateCheckResult> CheckForUpdatesAsync()
{
var taskCompletionSource = new TaskCompletionSource<UpdateCheckResult>();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.Once<UpdateCheckResult>("autoUpdater-checkForUpdates-completed" + guid, (result) =>
{
try
{
BridgeConnector.Socket.Off("autoUpdater-checkForUpdatesError" + guid);
taskCompletionSource.SetResult(result);
}
catch (Exception ex)
{
taskCompletionSource.SetException(ex);
}
});
BridgeConnector.Socket.Once<string>("autoUpdater-checkForUpdatesError" + guid, (result) =>
{
BridgeConnector.Socket.Off("autoUpdater-checkForUpdates-completed" + guid);
string message = "An error occurred in CheckForUpdatesAsync";
if (!string.IsNullOrEmpty(result)) message = result;
taskCompletionSource.SetException(new Exception(message));
});
BridgeConnector.Socket.Emit("autoUpdater-checkForUpdates", guid);
return taskCompletionSource.Task;
}
/// <summary>
/// Asks the server whether there is an update.
///
/// This will immediately download an update, then install when the app quits.
/// </summary>
/// <returns></returns>
public Task<UpdateCheckResult> CheckForUpdatesAndNotifyAsync()
{
var taskCompletionSource = new TaskCompletionSource<UpdateCheckResult>();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.Once<UpdateCheckResult>("autoUpdater-checkForUpdatesAndNotify-completed" + guid, (result) =>
{
try
{
BridgeConnector.Socket.Off("autoUpdater-checkForUpdatesAndNotifyError" + guid);
taskCompletionSource.SetResult(result);
}
catch (Exception ex)
{
taskCompletionSource.SetException(ex);
}
});
BridgeConnector.Socket.Once<string>("autoUpdater-checkForUpdatesAndNotifyError" + guid, (result) =>
{
BridgeConnector.Socket.Off("autoUpdater-checkForUpdatesAndNotify-completed" + guid);
string message = "An error occurred in CheckForUpdatesAndNotifyAsync";
if (!string.IsNullOrEmpty(result)) message = result;
taskCompletionSource.SetException(new Exception(message));
});
BridgeConnector.Socket.Emit("autoUpdater-checkForUpdatesAndNotify", guid);
return taskCompletionSource.Task;
}
/// <summary>
/// Restarts the app and installs the update after it has been downloaded.
/// It should only be called after `update-downloaded` has been emitted.
///
/// Note: QuitAndInstall() will close all application windows first and only emit `before-quit` event on `app` after that.
/// This is different from the normal quit event sequence.
/// </summary>
/// <param name="isSilent">*windows-only* Runs the installer in silent mode. Defaults to `false`.</param>
/// <param name="isForceRunAfter">Run the app after finish even on silent install. Not applicable for macOS. Ignored if `isSilent` is set to `false`.</param>
public void QuitAndInstall(bool isSilent = false, bool isForceRunAfter = false)
{
BridgeConnector.Socket.Emit("autoUpdater-quitAndInstall", isSilent, isForceRunAfter);
}
/// <summary>
/// Start downloading update manually. You can use this method if "AutoDownload" option is set to "false".
/// </summary>
/// <returns>Path to downloaded file.</returns>
public Task<string> DownloadUpdateAsync()
{
var tcs = new TaskCompletionSource<string>();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.Once<string>("autoUpdater-downloadUpdate-completed" + guid, tcs.SetResult);
BridgeConnector.Socket.Emit("autoUpdater-downloadUpdate", guid);
return tcs.Task;
}
/// <summary>
/// Feed URL.
/// </summary>
/// <returns>Feed URL.</returns>
public Task<string> GetFeedURLAsync()
{
var tcs = new TaskCompletionSource<string>();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.Once<string>("autoUpdater-getFeedURL-completed" + guid, tcs.SetResult);
BridgeConnector.Socket.Emit("autoUpdater-getFeedURL", guid);
return tcs.Task;
}
}
}

View File

@@ -1,25 +1,22 @@
using ElectronNET.API.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using ElectronNET.API.Entities;
using System.Threading.Tasks;
namespace ElectronNET.API
{
/// <summary>
/// A BrowserView can be used to embed additional web content into a BrowserWindow.
/// It is like a child window, except that it is positioned relative to its owning window.
/// A BrowserView can be used to embed additional web content into a BrowserWindow.
/// It is like a child window, except that it is positioned relative to its owning window.
/// It is meant to be an alternative to the webview tag.
/// </summary>
public class BrowserView
public class BrowserView : ApiBase
{
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
/// <summary>
/// Gets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
public int Id { get; internal set; }
public override int Id { get; protected set; }
/// <summary>
/// Render and control web pages.
@@ -28,38 +25,24 @@ namespace ElectronNET.API
/// <summary>
/// Resizes and moves the view to the supplied bounds relative to the window.
///
/// (experimental)
/// </summary>
public Rectangle Bounds
{
get
{
return Task.Run<Rectangle>(() =>
{
var taskCompletionSource = new TaskCompletionSource<Rectangle>();
BridgeConnector.Socket.On("browserView-getBounds-reply", (result) =>
{
BridgeConnector.Socket.Off("browserView-getBounds-reply");
taskCompletionSource.SetResult((Rectangle)result);
});
BridgeConnector.Socket.Emit("browserView-getBounds", Id);
return taskCompletionSource.Task;
}).Result;
return Task.Run(() => this.InvokeAsync<Rectangle>()).Result;
}
set
{
BridgeConnector.Socket.Emit("browserView-setBounds", Id, JObject.FromObject(value, _jsonSerializer));
BridgeConnector.Socket.Emit("browserView-bounds-set", Id, value);
}
}
/// <summary>
/// BrowserView
/// </summary>
internal BrowserView(int id)
internal BrowserView(int id)
{
Id = id;
@@ -74,12 +57,11 @@ namespace ElectronNET.API
/// <param name="options"></param>
public void SetAutoResize(AutoResizeOptions options)
{
BridgeConnector.Socket.Emit("browserView-setAutoResize", Id, JObject.FromObject(options, _jsonSerializer));
BridgeConnector.Socket.Emit("browserView-setAutoResize", Id, options);
}
/// <summary>
/// Color in #aarrggbb or #argb form. The alpha channel is optional.
///
/// (experimental)
/// </summary>
/// <param name="color">Color in #aarrggbb or #argb form. The alpha channel is optional.</param>
@@ -87,11 +69,5 @@ namespace ElectronNET.API
{
BridgeConnector.Socket.Emit("browserView-setBackgroundColor", Id, color);
}
private JsonSerializer _jsonSerializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +1,27 @@
using ElectronNET.API.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using ElectronNET.API.Entities;
using ElectronNET.API.Serialization;
using System.Runtime.Versioning;
using System.Text.Json;
using System.Threading.Tasks;
// ReSharper disable InconsistentNaming
namespace ElectronNET.API
{
/// <summary>
/// Perform copy and paste operations on the system clipboard.
/// </summary>
public sealed class Clipboard
public sealed class Clipboard : ApiBase
{
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
private static Clipboard _clipboard;
private static object _syncRoot = new object();
internal Clipboard() { }
internal Clipboard()
{
}
internal static Clipboard Instance
{
@@ -40,21 +47,7 @@ namespace ElectronNET.API
/// </summary>
/// <param name="type"></param>
/// <returns>The content in the clipboard as plain text.</returns>
public Task<string> ReadTextAsync(string type = "")
{
var taskCompletionSource = new TaskCompletionSource<string>();
BridgeConnector.Socket.On("clipboard-readText-Completed", (text) =>
{
BridgeConnector.Socket.Off("clipboard-readText-Completed");
taskCompletionSource.SetResult(text.ToString());
});
BridgeConnector.Socket.Emit("clipboard-readText", type);
return taskCompletionSource.Task;
}
public Task<string> ReadTextAsync(string type = "") => this.InvokeAsync<string>(type);
/// <summary>
/// Writes the text into the clipboard as plain text.
@@ -71,21 +64,7 @@ namespace ElectronNET.API
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Task<string> ReadHTMLAsync(string type = "")
{
var taskCompletionSource = new TaskCompletionSource<string>();
BridgeConnector.Socket.On("clipboard-readHTML-Completed", (text) =>
{
BridgeConnector.Socket.Off("clipboard-readHTML-Completed");
taskCompletionSource.SetResult(text.ToString());
});
BridgeConnector.Socket.Emit("clipboard-readHTML", type);
return taskCompletionSource.Task;
}
public Task<string> ReadHTMLAsync(string type = "") => this.InvokeAsync<string>(type);
/// <summary>
/// Writes markup to the clipboard.
@@ -102,21 +81,7 @@ namespace ElectronNET.API
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Task<string> ReadRTFAsync(string type = "")
{
var taskCompletionSource = new TaskCompletionSource<string>();
BridgeConnector.Socket.On("clipboard-readRTF-Completed", (text) =>
{
BridgeConnector.Socket.Off("clipboard-readRTF-Completed");
taskCompletionSource.SetResult(text.ToString());
});
BridgeConnector.Socket.Emit("clipboard-readRTF", type);
return taskCompletionSource.Task;
}
public Task<string> ReadRTFAsync(string type = "") => this.InvokeAsync<string>(type);
/// <summary>
/// Writes the text into the clipboard in RTF.
@@ -125,41 +90,31 @@ namespace ElectronNET.API
/// <param name="type"></param>
public void WriteRTF(string text, string type = "")
{
BridgeConnector.Socket.Emit("clipboard-writeHTML", text, type);
BridgeConnector.Socket.Emit("clipboard-writeRTF", text, type);
}
/// <summary>
/// Returns an Object containing title and url keys representing
/// the bookmark in the clipboard. The title and url values will
/// Returns an Object containing title and url keys representing
/// the bookmark in the clipboard. The title and url values will
/// be empty strings when the bookmark is unavailable.
/// </summary>
/// <returns></returns>
public Task<ReadBookmark> ReadBookmarkAsync()
{
var taskCompletionSource = new TaskCompletionSource<ReadBookmark>();
BridgeConnector.Socket.On("clipboard-readBookmark-Completed", (bookmark) =>
{
BridgeConnector.Socket.Off("clipboard-readBookmark-Completed");
taskCompletionSource.SetResult(((JObject)bookmark).ToObject<ReadBookmark>());
});
BridgeConnector.Socket.Emit("clipboard-readBookmark");
return taskCompletionSource.Task;
}
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public Task<ReadBookmark> ReadBookmarkAsync() => this.InvokeAsync<ReadBookmark>();
/// <summary>
/// Writes the title and url into the clipboard as a bookmark.
///
/// Note: Most apps on Windows dont support pasting bookmarks
/// into them so you can use clipboard.write to write both a
/// into them so you can use clipboard.write to write both a
/// bookmark and fallback text to the clipboard.
/// </summary>
/// <param name="title"></param>
/// <param name="url"></param>
/// <param name="type"></param>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public void WriteBookmark(string title, string url, string type = "")
{
BridgeConnector.Socket.Emit("clipboard-writeBookmark", title, url, type);
@@ -171,27 +126,15 @@ namespace ElectronNET.API
/// find pasteboard whenever the application is activated.
/// </summary>
/// <returns></returns>
public Task<string> ReadFindTextAsync()
{
var taskCompletionSource = new TaskCompletionSource<string>();
BridgeConnector.Socket.On("clipboard-readFindText-Completed", (text) =>
{
BridgeConnector.Socket.Off("clipboard-readFindText-Completed");
taskCompletionSource.SetResult(text.ToString());
});
BridgeConnector.Socket.Emit("clipboard-readFindText");
return taskCompletionSource.Task;
}
[SupportedOSPlatform("macOS")]
public Task<string> ReadFindTextAsync() => this.InvokeAsync<string>();
/// <summary>
/// macOS: Writes the text into the find pasteboard as plain text. This method uses
/// macOS: Writes the text into the find pasteboard as plain text. This method uses
/// synchronous IPC when called from the renderer process.
/// </summary>
/// <param name="text"></param>
[SupportedOSPlatform("macOS")]
public void WriteFindText(string text)
{
BridgeConnector.Socket.Emit("clipboard-writeFindText", text);
@@ -211,21 +154,7 @@ namespace ElectronNET.API
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Task<string[]> AvailableFormatsAsync(string type = "")
{
var taskCompletionSource = new TaskCompletionSource<string[]>();
BridgeConnector.Socket.On("clipboard-availableFormats-Completed", (formats) =>
{
BridgeConnector.Socket.Off("clipboard-availableFormats-Completed");
taskCompletionSource.SetResult(((JArray)formats).ToObject<string[]>());
});
BridgeConnector.Socket.Emit("clipboard-availableFormats", type);
return taskCompletionSource.Task;
}
public Task<string[]> AvailableFormatsAsync(string type = "") => this.InvokeAsync<string[]>(type);
/// <summary>
/// Writes data to the clipboard.
@@ -234,7 +163,7 @@ namespace ElectronNET.API
/// <param name="type"></param>
public void Write(Data data, string type = "")
{
BridgeConnector.Socket.Emit("clipboard-write", JObject.FromObject(data, _jsonSerializer), type);
BridgeConnector.Socket.Emit("clipboard-write", data, type);
}
/// <summary>
@@ -242,25 +171,8 @@ namespace ElectronNET.API
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Task<NativeImage> ReadImageAsync(string type = "")
{
var taskCompletionSource = new TaskCompletionSource<NativeImage>();
public Task<NativeImage> ReadImageAsync(string type = "") => this.InvokeAsync<NativeImage>(type);
BridgeConnector.Socket.On("clipboard-readImage-Completed", (image) =>
{
BridgeConnector.Socket.Off("clipboard-readImage-Completed");
var nativeImage = ((JObject)image).ToObject<NativeImage>();
taskCompletionSource.SetResult(nativeImage);
});
BridgeConnector.Socket.Emit("clipboard-readImage", type);
return taskCompletionSource.Task;
}
/// <summary>
/// Writes an image to the clipboard.
/// </summary>
@@ -268,14 +180,7 @@ namespace ElectronNET.API
/// <param name="type"></param>
public void WriteImage(NativeImage image, string type = "")
{
BridgeConnector.Socket.Emit("clipboard-writeImage", JsonConvert.SerializeObject(image), type);
BridgeConnector.Socket.Emit("clipboard-writeImage", JsonSerializer.Serialize(image, ElectronJson.Options), type);
}
private JsonSerializer _jsonSerializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
}
}

View File

@@ -8,7 +8,9 @@ namespace ElectronNET.API
/// </summary>
public sealed class CommandLine
{
internal CommandLine() { }
internal CommandLine()
{
}
internal static CommandLine Instance
{
@@ -66,22 +68,17 @@ namespace ElectronNET.API
/// <param name="switchName">A command-line switch</param>
/// <param name="cancellationToken"></param>
/// <returns>Whether the command-line switch is present.</returns>
public async Task<bool> HasSwitchAsync(string switchName, CancellationToken cancellationToken = default(CancellationToken))
public async Task<bool> HasSwitchAsync(string switchName, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
BridgeConnector.Socket.On("appCommandLineHasSwitchCompleted", (result) =>
{
BridgeConnector.Socket.Off("appCommandLineHasSwitchCompleted");
taskCompletionSource.SetResult((bool)result);
});
BridgeConnector.Socket.Once<bool>("appCommandLineHasSwitchCompleted", tcs.SetResult);
BridgeConnector.Socket.Emit("appCommandLineHasSwitch", switchName);
return await taskCompletionSource.Task.ConfigureAwait(false);
return await tcs.Task.ConfigureAwait(false);
}
}
@@ -94,23 +91,18 @@ namespace ElectronNET.API
/// <remarks>
/// Note: When the switch is not present or has no value, it returns empty string.
/// </remarks>
public async Task<string> GetSwitchValueAsync(string switchName, CancellationToken cancellationToken = default(CancellationToken))
public async Task<string> GetSwitchValueAsync(string switchName, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<string>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
var tcs = new TaskCompletionSource<string>();
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
BridgeConnector.Socket.On("appCommandLineGetSwitchValueCompleted", (result) =>
{
BridgeConnector.Socket.Off("appCommandLineGetSwitchValueCompleted");
taskCompletionSource.SetResult((string)result);
});
BridgeConnector.Socket.Once<string>("appCommandLineGetSwitchValueCompleted", tcs.SetResult);
BridgeConnector.Socket.Emit("appCommandLineGetSwitchValue", switchName);
return await taskCompletionSource.Task.ConfigureAwait(false);
return await tcs.Task.ConfigureAwait(false);
}
}
}
}
}

View File

@@ -1,9 +1,8 @@
using System;
using System.Threading.Tasks;
using ElectronNET.API.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using ElectronNET.API.Serialization;
using System;
using System.Text.Json;
using System.Threading.Tasks;
namespace ElectronNET.API
{
@@ -34,16 +33,21 @@ namespace ElectronNET.API
{
if (_changed == null)
{
BridgeConnector.Socket.On("webContents-session-cookies-changed" + Id, (args) =>
BridgeConnector.Socket.On<JsonElement>("webContents-session-cookies-changed" + Id, (args) =>
{
Cookie cookie = ((JArray)args)[0].ToObject<Cookie>();
CookieChangedCause cause = ((JArray)args)[1].ToObject<CookieChangedCause>();
bool removed = ((JArray)args)[2].ToObject<bool>();
var e = args.EnumerateArray().GetEnumerator();
e.MoveNext();
var cookie = e.Current.Deserialize<Cookie>(ElectronJson.Options);
e.MoveNext();
var cause = e.Current.Deserialize<CookieChangedCause>(ElectronJson.Options);
e.MoveNext();
var removed = e.Current.GetBoolean();
_changed(cookie, cause, removed);
});
BridgeConnector.Socket.Emit("register-webContents-session-cookies-changed", Id);
}
_changed += value;
}
remove
@@ -51,12 +55,16 @@ namespace ElectronNET.API
_changed -= value;
if (_changed == null)
{
BridgeConnector.Socket.Off("webContents-session-cookies-changed" + Id);
}
}
}
private event Action<Cookie, CookieChangedCause, bool> _changed;
/// <summary>
/// Sends a request to get all cookies matching filter, and resolves a callack with the response.
/// </summary>
@@ -65,20 +73,13 @@ namespace ElectronNET.API
/// <returns>A task which resolves an array of cookie objects.</returns>
public Task<Cookie[]> GetAsync(CookieFilter filter)
{
var taskCompletionSource = new TaskCompletionSource<Cookie[]>();
string guid = Guid.NewGuid().ToString();
var tcs = new TaskCompletionSource<Cookie[]>();
var guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.On("webContents-session-cookies-get-completed" + guid, (cookies) =>
{
Cookie[] result = ((JArray)cookies).ToObject<Cookie[]>();
BridgeConnector.Socket.Once<Cookie[]>("webContents-session-cookies-get-completed" + guid, tcs.SetResult);
BridgeConnector.Socket.Emit("webContents-session-cookies-get", Id, filter, guid);
BridgeConnector.Socket.Off("webContents-session-cookies-get-completed" + guid);
taskCompletionSource.SetResult(result);
});
BridgeConnector.Socket.Emit("webContents-session-cookies-get", Id, JObject.FromObject(filter, _jsonSerializer), guid);
return taskCompletionSource.Task;
return tcs.Task;
}
/// <summary>
@@ -88,18 +89,13 @@ namespace ElectronNET.API
/// <returns></returns>
public Task SetAsync(CookieDetails details)
{
var taskCompletionSource = new TaskCompletionSource<object>();
string guid = Guid.NewGuid().ToString();
var tcs = new TaskCompletionSource<object>();
var guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.On("webContents-session-cookies-set-completed" + guid, () =>
{
BridgeConnector.Socket.Off("webContents-session-cookies-set-completed" + guid);
taskCompletionSource.SetResult(null);
});
BridgeConnector.Socket.Once<object>("webContents-session-cookies-set-completed" + guid, tcs.SetResult);
BridgeConnector.Socket.Emit("webContents-session-cookies-set", Id, details, guid);
BridgeConnector.Socket.Emit("webContents-session-cookies-set", Id, JObject.FromObject(details, _jsonSerializer), guid);
return taskCompletionSource.Task;
return tcs.Task;
}
/// <summary>
@@ -110,18 +106,13 @@ namespace ElectronNET.API
/// <returns>A task which resolves when the cookie has been removed</returns>
public Task RemoveAsync(string url, string name)
{
var taskCompletionSource = new TaskCompletionSource<object>();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.On("webContents-session-cookies-remove-completed" + guid, () =>
{
BridgeConnector.Socket.Off("webContents-session-cookies-remove-completed" + guid);
taskCompletionSource.SetResult(null);
});
var tcs = new TaskCompletionSource<object>();
var guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.Once<object>("webContents-session-cookies-remove-completed" + guid, tcs.SetResult);
BridgeConnector.Socket.Emit("webContents-session-cookies-remove", Id, url, name, guid);
return taskCompletionSource.Task;
return tcs.Task;
}
/// <summary>
@@ -130,25 +121,13 @@ namespace ElectronNET.API
/// <returns>A task which resolves when the cookie store has been flushed</returns>
public Task FlushStoreAsync()
{
var taskCompletionSource = new TaskCompletionSource<object>();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.On("webContents-session-cookies-flushStore-completed" + guid, () =>
{
BridgeConnector.Socket.Off("webContents-session-cookies-flushStore-completed" + guid);
taskCompletionSource.SetResult(null);
});
var tcs = new TaskCompletionSource<object>();
var guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.Once<object>("webContents-session-cookies-flushStore-completed" + guid, tcs.SetResult);
BridgeConnector.Socket.Emit("webContents-session-cookies-flushStore", Id, guid);
return taskCompletionSource.Task;
return tcs.Task;
}
private JsonSerializer _jsonSerializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
}
}

View File

@@ -1,9 +1,7 @@
using ElectronNET.API.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using ElectronNET.API.Entities;
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Text.Json;
using System.Threading.Tasks;
namespace ElectronNET.API
@@ -16,7 +14,9 @@ namespace ElectronNET.API
private static Dialog _dialog;
private static object _syncRoot = new object();
internal Dialog() { }
internal Dialog()
{
}
internal static Dialog Instance
{
@@ -26,7 +26,7 @@ namespace ElectronNET.API
{
lock (_syncRoot)
{
if(_dialog == null)
if (_dialog == null)
{
_dialog = new Dialog();
}
@@ -38,8 +38,8 @@ namespace ElectronNET.API
}
/// <summary>
/// Note: On Windows and Linux an open dialog can not be both a file selector
/// and a directory selector, so if you set properties to ['openFile', 'openDirectory']
/// Note: On Windows and Linux an open dialog can not be both a file selector
/// and a directory selector, so if you set properties to ['openFile', 'openDirectory']
/// on these platforms, a directory selector will be shown.
/// </summary>
/// <param name="browserWindow">The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.</param>
@@ -47,23 +47,16 @@ namespace ElectronNET.API
/// <returns>An array of file paths chosen by the user</returns>
public Task<string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options)
{
var taskCompletionSource = new TaskCompletionSource<string[]>();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.On("showOpenDialogComplete" + guid, (filePaths) =>
{
BridgeConnector.Socket.Off("showOpenDialogComplete" + guid);
var result = ((JArray)filePaths).ToObject<string[]>();
taskCompletionSource.SetResult(result);
});
var tcs = new TaskCompletionSource<string[]>();
var guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.Once<string[]>("showOpenDialogComplete" + guid, tcs.SetResult);
BridgeConnector.Socket.Emit("showOpenDialog",
JObject.FromObject(browserWindow, _jsonSerializer),
JObject.FromObject(options, _jsonSerializer), guid);
browserWindow,
options,
guid);
return taskCompletionSource.Task;
return tcs.Task;
}
/// <summary>
@@ -74,22 +67,16 @@ namespace ElectronNET.API
/// <returns>Returns String, the path of the file chosen by the user, if a callback is provided it returns an empty string.</returns>
public Task<string> ShowSaveDialogAsync(BrowserWindow browserWindow, SaveDialogOptions options)
{
var taskCompletionSource = new TaskCompletionSource<string>();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.On("showSaveDialogComplete" + guid, (filename) =>
{
BridgeConnector.Socket.Off("showSaveDialogComplete" + guid);
taskCompletionSource.SetResult(filename.ToString());
});
var tcs = new TaskCompletionSource<string>();
var guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.Once<string>("showSaveDialogComplete" + guid, tcs.SetResult);
BridgeConnector.Socket.Emit("showSaveDialog",
JObject.FromObject(browserWindow, _jsonSerializer),
JObject.FromObject(options, _jsonSerializer),
guid);
browserWindow,
options,
guid);
return taskCompletionSource.Task;
return tcs.Task;
}
/// <summary>
@@ -103,7 +90,7 @@ namespace ElectronNET.API
/// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns>
public async Task<MessageBoxResult> ShowMessageBoxAsync(string message)
{
return await ShowMessageBoxAsync(null, new MessageBoxOptions(message));
return await this.ShowMessageBoxAsync(null, new MessageBoxOptions(message)).ConfigureAwait(false);
}
/// <summary>
@@ -117,7 +104,7 @@ namespace ElectronNET.API
/// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns>
public async Task<MessageBoxResult> ShowMessageBoxAsync(MessageBoxOptions messageBoxOptions)
{
return await ShowMessageBoxAsync(null, messageBoxOptions);
return await this.ShowMessageBoxAsync(null, messageBoxOptions).ConfigureAwait(false);
}
/// <summary>
@@ -130,7 +117,7 @@ namespace ElectronNET.API
/// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns>
public async Task<MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, string message)
{
return await ShowMessageBoxAsync(browserWindow, new MessageBoxOptions(message));
return await this.ShowMessageBoxAsync(browserWindow, new MessageBoxOptions(message)).ConfigureAwait(false);
}
/// <summary>
@@ -143,43 +130,47 @@ namespace ElectronNET.API
/// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns>
public Task<MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, MessageBoxOptions messageBoxOptions)
{
var taskCompletionSource = new TaskCompletionSource<MessageBoxResult>();
var tcs = new TaskCompletionSource<MessageBoxResult>();
var guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.On("showMessageBoxComplete" + guid, (args) =>
BridgeConnector.Socket.Once<JsonElement>("showMessageBoxComplete" + guid, (args) =>
{
BridgeConnector.Socket.Off("showMessageBoxComplete" + guid);
// args is [response:int, checkboxChecked:boolean]
var arr = args.EnumerateArray();
var e = arr.GetEnumerator();
e.MoveNext();
var response = e.Current.GetInt32();
e.MoveNext();
var checkbox = e.Current.GetBoolean();
var result = ((JArray)args);
taskCompletionSource.SetResult(new MessageBoxResult
tcs.SetResult(new MessageBoxResult
{
Response = (int)result.First,
CheckboxChecked = (bool)result.Last
Response = response,
CheckboxChecked = checkbox
});
});
if (browserWindow == null)
{
BridgeConnector.Socket.Emit("showMessageBox", JObject.FromObject(messageBoxOptions, _jsonSerializer), guid);
} else
BridgeConnector.Socket.Emit("showMessageBox", messageBoxOptions, guid);
}
else
{
BridgeConnector.Socket.Emit("showMessageBox",
JObject.FromObject(browserWindow, _jsonSerializer),
JObject.FromObject(messageBoxOptions, _jsonSerializer),
BridgeConnector.Socket.Emit("showMessageBox",
browserWindow,
messageBoxOptions,
guid);
}
return taskCompletionSource.Task;
return tcs.Task;
}
/// <summary>
/// Displays a modal dialog that shows an error message.
///
/// This API can be called safely before the ready event the app module emits,
/// it is usually used to report errors in early stage of startup.If called
/// before the app readyevent on Linux, the message will be emitted to stderr,
/// This API can be called safely before the ready event the app module emits,
/// it is usually used to report errors in early stage of startup.If called
/// before the app readyevent on Linux, the message will be emitted to stderr,
/// and no GUI dialog will appear.
/// </summary>
/// <param name="title">The title to display in the error box.</param>
@@ -191,11 +182,13 @@ namespace ElectronNET.API
/// <summary>
/// On macOS, this displays a modal dialog that shows a message and certificate information,
/// and gives the user the option of trusting/importing the certificate. If you provide a
/// and gives the user the option of trusting/importing the certificate. If you provide a
/// browserWindow argument the dialog will be attached to the parent window, making it modal.
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public Task ShowCertificateTrustDialogAsync(CertificateTrustDialogOptions options)
{
return ShowCertificateTrustDialogAsync(null, options);
@@ -203,36 +196,26 @@ namespace ElectronNET.API
/// <summary>
/// On macOS, this displays a modal dialog that shows a message and certificate information,
/// and gives the user the option of trusting/importing the certificate. If you provide a
/// and gives the user the option of trusting/importing the certificate. If you provide a
/// browserWindow argument the dialog will be attached to the parent window, making it modal.
/// </summary>
/// <param name="browserWindow"></param>
/// <param name="options"></param>
/// <returns></returns>
[SupportedOSPlatform("macOS")]
[SupportedOSPlatform("Windows")]
public Task ShowCertificateTrustDialogAsync(BrowserWindow browserWindow, CertificateTrustDialogOptions options)
{
var taskCompletionSource = new TaskCompletionSource<object>();
var tcs = new TaskCompletionSource();
string guid = Guid.NewGuid().ToString();
BridgeConnector.Socket.On("showCertificateTrustDialogComplete" + guid, () =>
{
BridgeConnector.Socket.Off("showCertificateTrustDialogComplete" + guid);
taskCompletionSource.SetResult(null);
});
BridgeConnector.Socket.Once("showCertificateTrustDialogComplete" + guid, () => tcs.SetResult());
BridgeConnector.Socket.Emit("showCertificateTrustDialog",
JObject.FromObject(browserWindow, _jsonSerializer),
JObject.FromObject(options, _jsonSerializer),
browserWindow,
options,
guid);
return taskCompletionSource.Task;
return tcs.Task;
}
private JsonSerializer _jsonSerializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
}
}
}

View File

@@ -1,17 +1,16 @@
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using ElectronNET.API.Entities;
using ElectronNET.API.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace ElectronNET.API
{
/// <summary>
/// Control your app in the macOS dock.
/// </summary>
[SupportedOSPlatform("macOS")]
public sealed class Dock
{
private static Dock _dock;
@@ -54,18 +53,13 @@ namespace ElectronNET.API
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<int>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
var tcs = new TaskCompletionSource<int>();
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
BridgeConnector.Socket.On("dock-bounce-completed", (id) =>
{
BridgeConnector.Socket.Off("dock-bounce-completed");
taskCompletionSource.SetResult((int) id);
});
BridgeConnector.Socket.Once<int>("dock-bounce-completed", tcs.SetResult);
BridgeConnector.Socket.Emit("dock-bounce", type);
BridgeConnector.Socket.Emit("dock-bounce", type.GetDescription());
return await taskCompletionSource.Task
return await tcs.Task
.ConfigureAwait(false);
}
}
@@ -106,18 +100,13 @@ namespace ElectronNET.API
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<string>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
var tcs = new TaskCompletionSource<string>();
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
BridgeConnector.Socket.On("dock-getBadge-completed", (text) =>
{
BridgeConnector.Socket.Off("dock-getBadge-completed");
taskCompletionSource.SetResult((string) text);
});
BridgeConnector.Socket.Once<string>("dock-getBadge-completed", tcs.SetResult);
BridgeConnector.Socket.Emit("dock-getBadge");
return await taskCompletionSource.Task
return await tcs.Task
.ConfigureAwait(false);
}
}
@@ -148,18 +137,13 @@ namespace ElectronNET.API
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
BridgeConnector.Socket.On("dock-isVisible-completed", (isVisible) =>
{
BridgeConnector.Socket.Off("dock-isVisible-completed");
taskCompletionSource.SetResult((bool) isVisible);
});
BridgeConnector.Socket.Once<bool>("dock-isVisible-completed", tcs.SetResult);
BridgeConnector.Socket.Emit("dock-isVisible");
return await taskCompletionSource.Task
return await tcs.Task
.ConfigureAwait(false);
}
}
@@ -170,7 +154,14 @@ namespace ElectronNET.API
/// <value>
/// The menu items.
/// </value>
public IReadOnlyCollection<MenuItem> MenuItems { get { return _items.AsReadOnly(); } }
public IReadOnlyCollection<MenuItem> MenuItems
{
get
{
return _items.AsReadOnly();
}
}
private List<MenuItem> _items = new List<MenuItem>();
/// <summary>
@@ -179,15 +170,15 @@ namespace ElectronNET.API
public void SetMenu(MenuItem[] menuItems)
{
menuItems.AddMenuItemsId();
BridgeConnector.Socket.Emit("dock-setMenu", JArray.FromObject(menuItems, _jsonSerializer));
BridgeConnector.Socket.Emit("dock-setMenu", new[] { menuItems });
_items.AddRange(menuItems);
BridgeConnector.Socket.Off("dockMenuItemClicked");
BridgeConnector.Socket.On("dockMenuItemClicked", (id) => {
MenuItem menuItem = _items.GetMenuItem(id.ToString());
BridgeConnector.Socket.On<string>("dockMenuItemClicked", (id) =>
{
MenuItem menuItem = _items.GetMenuItem(id);
menuItem?.Click();
});
}
/// <summary>
@@ -198,18 +189,13 @@ namespace ElectronNET.API
{
cancellationToken.ThrowIfCancellationRequested();
var taskCompletionSource = new TaskCompletionSource<Menu>();
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
var tcs = new TaskCompletionSource<Menu>();
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
BridgeConnector.Socket.On("dock-getMenu-completed", (menu) =>
{
BridgeConnector.Socket.Off("dock-getMenu-completed");
taskCompletionSource.SetResult(((JObject)menu).ToObject<Menu>());
});
BridgeConnector.Socket.Once<Menu>("dock-getMenu-completed", tcs.SetResult);
BridgeConnector.Socket.Emit("dock-getMenu");
return await taskCompletionSource.Task
return await tcs.Task
.ConfigureAwait(false);
}
}
@@ -222,11 +208,5 @@ namespace ElectronNET.API
{
BridgeConnector.Socket.Emit("dock-setIcon", image);
}
private JsonSerializer _jsonSerializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
}
}

View File

@@ -0,0 +1,199 @@
namespace ElectronNET.API
{
/// <summary>
/// The Electron.NET API
/// </summary>
public static class Electron
{
/// <summary>
/// Communicate asynchronously from the main process to renderer processes.
/// </summary>
public static IpcMain IpcMain
{
get
{
return IpcMain.Instance;
}
}
/// <summary>
/// Control your application's event lifecycle.
/// </summary>
public static App App
{
get
{
return App.Instance;
}
}
/// <summary>
/// Enable apps to automatically update themselves. Based on electron-updater.
/// </summary>
public static AutoUpdater AutoUpdater
{
get
{
return AutoUpdater.Instance;
}
}
/// <summary>
/// Control your windows.
/// </summary>
public static WindowManager WindowManager
{
get
{
return WindowManager.Instance;
}
}
/// <summary>
/// Create native application menus and context menus.
/// </summary>
public static Menu Menu
{
get
{
return Menu.Instance;
}
}
/// <summary>
/// Display native system dialogs for opening and saving files, alerting, etc.
/// </summary>
public static Dialog Dialog
{
get
{
return Dialog.Instance;
}
}
/// <summary>
/// Create OS desktop notifications
/// </summary>
public static Notification Notification
{
get
{
return Notification.Instance;
}
}
/// <summary>
/// Add icons and context menus to the systems notification area.
/// </summary>
public static Tray Tray
{
get
{
return Tray.Instance;
}
}
/// <summary>
/// Detect keyboard events when the application does not have keyboard focus.
/// </summary>
public static GlobalShortcut GlobalShortcut
{
get
{
return GlobalShortcut.Instance;
}
}
/// <summary>
/// Manage files and URLs using their default applications.
/// </summary>
public static Shell Shell
{
get
{
return Shell.Instance;
}
}
/// <summary>
/// Retrieve information about screen size, displays, cursor position, etc.
/// </summary>
public static Screen Screen
{
get
{
return Screen.Instance;
}
}
/// <summary>
/// Perform copy and paste operations on the system clipboard.
/// </summary>
public static Clipboard Clipboard
{
get
{
return Clipboard.Instance;
}
}
/// <summary>
/// Allows you to execute native JavaScript/TypeScript code from the host process.
///
/// It is only possible if the Electron.NET CLI has previously added an
/// ElectronHostHook directory:
/// <c>electronize add HostHook</c>
/// </summary>
public static HostHook HostHook
{
get
{
return HostHook.Instance;
}
}
/// <summary>
/// Allows you to execute native Lock and Unlock process.
/// </summary>
public static PowerMonitor PowerMonitor
{
get
{
return PowerMonitor.Instance;
}
}
/// <summary>
/// Read and respond to changes in Chromium's native color theme.
/// </summary>
public static NativeTheme NativeTheme
{
get
{
return NativeTheme.Instance;
}
}
/// <summary>
/// Control your app in the macOS dock.
/// </summary>
public static Dock Dock
{
get
{
return Dock.Instance;
}
}
/// <summary>
/// Electeon extensions to the Nodejs process object.
/// </summary>
public static Process Process
{
get
{
return Process.Instance;
}
}
}
}

View File

@@ -1,8 +1,11 @@
namespace ElectronNET.API.Entities
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// About panel options.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class AboutPanelOptions
{
/// <summary>
@@ -21,28 +24,35 @@
public string Copyright { get; set; }
/// <summary>
/// The app's build version number.
/// The app's build version number (macOS).
/// </summary>
[SupportedOSPlatform("macos")]
public string Version { get; set; }
/// <summary>
/// Credit information.
/// Credit information (macOS, Windows).
/// </summary>
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("windows")]
public string Credits { get; set; }
/// <summary>
/// List of app authors.
/// List of app authors (Linux).
/// </summary>
[SupportedOSPlatform("linux")]
public string[] Authors { get; set; }
/// <summary>
/// The app's website.
/// The app's website (Linux).
/// </summary>
[SupportedOSPlatform("linux")]
public string Website { get; set; }
/// <summary>
/// Path to the app's icon. On Linux, will be shown as 64x64 pixels while retaining aspect ratio.
/// Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio. On Windows, a 48x48 PNG will result in the best visual quality.
/// </summary>
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("windows")]
public string IconPath { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
using System.Text.Json.Serialization;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class AddRepresentationOptions
{
/// <summary>
/// Gets or sets the width in pixels. Defaults to 0. Required if a bitmap buffer is specified as <see cref="Buffer"/>.
/// </summary>
public int? Width { get; set; }
/// <summary>
/// Gets or sets the height in pixels. Defaults to 0. Required if a bitmap buffer is specified as <see cref="Buffer"/>.
/// </summary>
public int? Height { get; set; }
/// <summary>
/// Gets or sets the image scale factor. Defaults to 1.0.
/// </summary>
public float ScaleFactor { get; set; } = 1.0f;
/// <summary>
/// Gets or sets the buffer containing the raw image data.
/// </summary>
public byte[] Buffer { get; set; }
/// <summary>
/// Gets or sets the data URL containing a base 64 encoded PNG or JPEG image.
/// </summary>
public string DataUrl { get; set; }
}
}

View File

@@ -1,32 +1,36 @@
namespace ElectronNET.API.Entities
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
[SupportedOSPlatform("windows")]
public class AppDetailsOptions
{
/// <summary>
/// Windows App User Model ID. It has to be set, otherwise the other options will have no effect.
/// Window's App User Model ID. It has to be set, otherwise the other options will have no effect.
/// </summary>
public string AppId { get; set; }
/// <summary>
/// Windows Relaunch Icon.
/// Window's relaunch icon resource path.
/// </summary>
public string AppIconPath { get; set; }
/// <summary>
/// Index of the icon in appIconPath. Ignored when appIconPath is not set. Default is 0.
/// Index of the icon in <see cref="AppIconPath"/>. Ignored when <see cref="AppIconPath"/> is not set. Default is 0.
/// </summary>
public int AppIconIndex { get; set; }
/// <summary>
/// Windows Relaunch Command.
/// Window's relaunch command.
/// </summary>
public string RelaunchCommand { get; set; }
/// <summary>
/// Windows Relaunch Display Name.
/// Window's relaunch display name.
/// </summary>
public string RelaunchDisplayName { get; set; }
}

View File

@@ -5,6 +5,7 @@ namespace ElectronNET.API.Entities
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class AutoResizeOptions
{
/// <summary>
@@ -35,4 +36,4 @@ namespace ElectronNET.API.Entities
[DefaultValue(false)]
public bool Vertical { get; set; } = false;
}
}
}

View File

@@ -3,11 +3,12 @@
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class BitmapOptions
{
/// <summary>
/// Gets or sets the scale factor
/// The image scale factor. Defaults to 1.0.
/// </summary>
public float ScaleFactor { get; set; } = 1.0f;
}
}
}

View File

@@ -3,6 +3,7 @@
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class Blob : IPostData
{
/// <summary>

View File

@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ElectronNET.API.Entities
namespace ElectronNET.API.Entities
{
/// <summary>
///
@@ -32,4 +28,4 @@ namespace ElectronNET.API.Entities
/// </summary>
public bool IsAdminRightsRequired { get; set; }
}
}
}

View File

@@ -3,23 +3,26 @@
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class BrowserViewConstructorOptions
{
/// <summary>
/// See BrowserWindow.
/// Gets or sets the web preferences for the view (see WebPreferences).
/// </summary>
public WebPreferences WebPreferences { get; set; }
/// <summary>
/// A proxy to set on creation in the format host:port.
/// Gets or sets a proxy to use on creation in the format host:port.
/// The proxy can be alternatively set using the BrowserView.WebContents.SetProxyAsync function.
/// </summary>
/// <remarks>This is custom shortcut. Not part of the Electron API.</remarks>
public string Proxy { get; set; }
/// <summary>
/// The credentials of the Proxy in the format username:password.
/// Gets or sets the credentials of the proxy in the format username:password.
/// These will only be used if the Proxy field is also set.
/// </summary>
/// <remarks>This is custom shortcut. Not part of the Electron API.</remarks>
public string ProxyCredentials { get; set; }
}
}
}

View File

@@ -1,6 +1,7 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using ElectronNET.Converter;
using System.ComponentModel;
using System.Text.Json.Serialization;
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
@@ -23,13 +24,13 @@ namespace ElectronNET.API.Entities
/// ( if y is used) Window's left offset from screen. Default is to center the
/// window.
/// </summary>
public int X { get; set; } = -1;
public int? X { get; set; }
/// <summary>
/// ( if x is used) Window's top offset from screen. Default is to center the
/// window.
/// </summary>
public int Y { get; set; } = -1;
public int? Y { get; set; }
/// <summary>
/// The width and height would be used as web page's size, which means the actual
@@ -72,24 +73,32 @@ namespace ElectronNET.API.Entities
/// <summary>
/// Whether window is movable. This is not implemented on Linux. Default is true.
/// </summary>
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("windows")]
[DefaultValue(true)]
public bool Movable { get; set; } = true;
/// <summary>
/// Whether window is minimizable. This is not implemented on Linux. Default is true.
/// </summary>
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("windows")]
[DefaultValue(true)]
public bool Minimizable { get; set; } = true;
/// <summary>
/// Whether window is maximizable. This is not implemented on Linux. Default is true.
/// </summary>
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("windows")]
[DefaultValue(true)]
public bool Maximizable { get; set; } = true;
/// <summary>
/// Whether window is closable. This is not implemented on Linux. Default is true.
/// </summary>
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("windows")]
[DefaultValue(true)]
public bool Closable { get; set; } = true;
@@ -115,16 +124,24 @@ namespace ElectronNET.API.Entities
/// <summary>
/// Whether the window can be put into fullscreen mode. On macOS, also whether the
/// maximize/zoom button should toggle full screen mode or maximize window.Default
/// is true.
/// maximize/zoom button should toggle full screen mode or maximize window. Default
/// is true (Electron default).
/// </summary>
public bool Fullscreenable { get; set; }
[DefaultValue(true)]
public bool Fullscreenable { get; set; } = true; // FIX: previously defaulted to false in C#
/// <summary>
/// Whether to show the window in taskbar. Default is false.
/// </summary>
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("windows")]
public bool SkipTaskbar { get; set; }
/// <summary>
/// Determines if Blazor is used. Will disable "module" and "process" globals. Default is false.
/// </summary>
public bool IsRunningBlazor { get; set; }
/// <summary>
/// The kiosk mode. Default is false.
/// </summary>
@@ -136,8 +153,7 @@ namespace ElectronNET.API.Entities
public string Title { get; set; } = "Electron.NET";
/// <summary>
/// The window icon. On Windows it is recommended to use ICO icons to get best
/// visual effects, you can also leave it undefined so the executable's icon will be used.
/// The window icon. Can be a NativeImage or a string path. On Windows it is recommended to use ICO icons; when undefined, the executable's icon will be used.
/// </summary>
public string Icon { get; set; }
@@ -148,7 +164,7 @@ namespace ElectronNET.API.Entities
public bool Show { get; set; } = true;
/// <summary>
/// Specify false to create a . Default is true.
/// Specify false to create a frameless window. Default is true.
/// </summary>
[DefaultValue(true)]
public bool Frame { get; set; } = true;
@@ -163,6 +179,7 @@ namespace ElectronNET.API.Entities
/// Whether the web view accepts a single mouse-down event that simultaneously
/// activates the window.Default is false.
/// </summary>
[SupportedOSPlatform("macos")]
public bool AcceptFirstMouse { get; set; }
/// <summary>
@@ -173,33 +190,40 @@ namespace ElectronNET.API.Entities
/// <summary>
/// Auto hide the menu bar unless the Alt key is pressed. Default is false.
/// </summary>
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
public bool AutoHideMenuBar { get; set; }
/// <summary>
/// Enable the window to be resized larger than screen. Default is false.
/// </summary>
[SupportedOSPlatform("macos")]
public bool EnableLargerThanScreen { get; set; }
/// <summary>
/// Window's background color as Hexadecimal value, like #66CD00 or #FFF or
/// #80FFFFFF (alpha is supported). Default is #FFF (white).
/// The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if transparent is set to true. Default is #FFF (white).
/// </summary>
public string BackgroundColor { get; set; }
/// <summary>
/// Whether window should have a shadow. This is only implemented on macOS. Default
/// is true.
/// Initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). Only implemented on Windows and macOS.
/// </summary>
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("macos")]
public double? Opacity { get; set; }
/// <summary>
/// Whether window should have a shadow. Default is true.
/// </summary>
public bool HasShadow { get; set; }
/// <summary>
/// Forces using dark theme for the window, only works on some GTK+3 desktop
/// environments.Default is false.
/// Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default is false.
/// </summary>
public bool DarkTheme { get; set; }
/// <summary>
/// Makes the window . Default is false.
/// Makes the window transparent. Default is false.
/// </summary>
public bool Transparent { get; set; }
@@ -212,13 +236,30 @@ namespace ElectronNET.API.Entities
/// The style of window title bar. Default is default. Possible values are:
/// 'default' | 'hidden' | 'hiddenInset' | 'customButtonsOnHover'
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public TitleBarStyle TitleBarStyle { get; set; }
/// <summary>
/// Shows the title in the tile bar in full screen mode on macOS for all
/// titleBarStyle options.Default is false.
/// Set a custom position for the traffic light buttons in frameless windows (macOS).
/// </summary>
[SupportedOSPlatform("macos")]
public Point TrafficLightPosition { get; set; }
/// <summary>
/// Configures the window's title bar overlay when using a frameless window.
/// Can be either:
/// - false: No title bar overlay.
/// - true: Enables the default title bar overlay.
/// - An object defining custom overlay options (such as height, color, etc.).
///
/// Default is false.
/// </summary>
[JsonConverter(typeof(TitleBarOverlayConverter))]
public TitleBarOverlay TitleBarOverlay { get; set; }
/// <summary>
/// Shows the title in the title bar in full screen mode on macOS for all titleBarStyle options. Default is false.
/// </summary>
/// <remarks>Not documented by MCP base-window-options / browser-window-options.</remarks>
public bool FullscreenWindowTitle { get; set; }
/// <summary>
@@ -226,15 +267,27 @@ namespace ElectronNET.API.Entities
/// window frame.Setting it to false will remove window shadow and window
/// animations. Default is true.
/// </summary>
[SupportedOSPlatform("windows")]
[DefaultValue(true)]
public bool ThickFrame { get; set; } = true;
/// <summary>
/// Add a type of vibrancy effect to the window, only on macOS. Can be
/// appearance-based, light, dark, titlebar, selection, menu, popover, sidebar,
/// medium-light or ultra-dark.
/// Whether frameless window should have rounded corners. Default is true. Setting this
/// property to false will prevent the window from being fullscreenable on macOS. On
/// Windows versions older than Windows 11 Build 22000 this property has no effect, and
/// frameless windows will not have rounded corners.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("windows")]
[DefaultValue(true)]
public bool RoundedCorners { get; set; } = true;
/// <summary>
/// Add a type of vibrancy effect to the window, only on macOS. Can be
/// appearance-based, titlebar, selection, menu, popover, sidebar, header, sheet,
/// window, hud, fullscreen-ui, tooltip, content, under-window, or under-page.
/// </summary>
[SupportedOSPlatform("macos")]
public Vibrancy Vibrancy { get; set; }
/// <summary>
@@ -244,6 +297,7 @@ namespace ElectronNET.API.Entities
/// it to zoom to the width of the screen.This will also affect the behavior when
/// calling maximize() directly.Default is false.
/// </summary>
[SupportedOSPlatform("macos")]
public bool ZoomToPageWidth { get; set; }
/// <summary>
@@ -252,6 +306,7 @@ namespace ElectronNET.API.Entities
/// adds a native new tab button to your window's tab bar and allows your app and
/// window to receive the new-window-for-tab event.
/// </summary>
[SupportedOSPlatform("macos")]
public string TabbingIdentifier { get; set; }
/// <summary>
@@ -263,12 +318,39 @@ namespace ElectronNET.API.Entities
/// A proxy to set on creation in the format host:port.
/// The proxy can be alternatively set using the BrowserWindow.WebContents.SetProxyAsync function.
/// </summary>
/// <remarks>Not documented by MCP base-window-options / browser-window-options.</remarks>
public string Proxy { get; set; }
/// <summary>
/// The credentials of the Proxy in the format username:password.
/// These will only be used if the Proxy field is also set.
/// </summary>
/// <remarks>Not documented by MCP base-window-options / browser-window-options.</remarks>
public string ProxyCredentials { get; set; }
/// <summary>
/// Gets or sets whether to use pre-Lion fullscreen on macOS. Default is false.
/// </summary>
[SupportedOSPlatform("macos")]
public bool SimpleFullscreen { get; set; }
/// <summary>
/// Gets or sets whether the window should be hidden when the user toggles into mission control (macOS).
/// </summary>
[SupportedOSPlatform("macos")]
public bool HiddenInMissionControl { get; set; }
/// <summary>
/// Gets or sets how the material appearance should reflect window activity state on macOS. Must be used with the vibrancy property.
/// Possible values: 'followWindow' (default), 'active', 'inactive'.
/// </summary>
[SupportedOSPlatform("macos")]
public string VisualEffectState { get; set; }
/// <summary>
/// Gets or sets the system-drawn background material on Windows. Can be 'auto', 'none', 'mica', 'acrylic' or 'tabbed'.
/// </summary>
[SupportedOSPlatform("windows")]
public string BackgroundMaterial { get; set; }
}
}
}

View File

@@ -0,0 +1,25 @@
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class CPUUsage
{
/// <summary>
/// Percentage of CPU used since the last call to getCPUUsage. First call returns 0.
/// </summary>
public double PercentCPUUsage { get; set; }
/// <summary>
/// Total seconds of CPU time used since process startup, if available.
/// </summary>
public double? CumulativeCPUUsage { get; set; }
/// <summary>
/// The number of average idle CPU wakeups per second since the last call to
/// getCPUUsage. First call returns 0. Will always return 0 on Windows.
/// </summary>
public double IdleWakeupsPerSecond { get; set; }
}
}

View File

@@ -3,6 +3,7 @@
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class Certificate
{
/// <summary>

View File

@@ -3,6 +3,7 @@
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class CertificatePrincipal
{
/// <summary>

View File

@@ -3,6 +3,7 @@
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class CertificateTrustDialogOptions
{
/// <summary>

View File

@@ -1,12 +1,9 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ElectronNET.API.Entities
namespace ElectronNET.API.Entities
{
/// <summary>
/// Provide metadata about the current loaded Chrome extension
/// </summary>
/// <yremarks>Project-specific: no matching Electron structure found in MCP docs (electronjs).</yremarks>
public class ChromeExtensionInfo
{
/// <summary>
@@ -30,4 +27,4 @@ namespace ElectronNET.API.Entities
/// </summary>
public string Version { get; set; }
}
}
}

View File

@@ -0,0 +1,28 @@
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class ClearStorageDataOptions
{
/// <summary>
/// Should follow window.location.origins representation scheme://host:port.
/// </summary>
public string Origin { get; set; }
/// <summary>
/// The types of storages to clear. Can contain: cookies, filesystem, indexdb,
/// localstorage, shadercache, websql, serviceworkers, cachestorage.
/// If not specified, all storage types are cleared.
/// </summary>
public string[] Storages { get; set; }
/// <summary>
/// The types of quotas to clear. Can contain: temporary. If not specified,
/// all quotas are cleared. The <c>quotas</c> option is deprecated;
/// "temporary" is the only remaining supported quota type.
/// </summary>
public string[] Quotas { get; set; }
}
}

View File

@@ -0,0 +1,59 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// Cookie structure as used by Electron session.cookies APIs.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class Cookie
{
/// <summary>
/// Gets or sets the name of the cookie.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the value of the cookie.
/// </summary>
public string Value { get; set; }
/// <summary>
/// Gets or sets the domain of the cookie; this will be normalized with a preceding dot so that it's also valid for subdomains.
/// </summary>
public string Domain { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the cookie is a host-only cookie; this will only be true if no domain was passed.
/// </summary>
public bool? HostOnly { get; set; }
/// <summary>
/// Gets or sets the path of the cookie.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the cookie is marked as secure.
/// </summary>
public bool? Secure { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the cookie is marked as HTTP only.
/// </summary>
public bool? HttpOnly { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the cookie is a session cookie or a persistent cookie with an expiration date.
/// </summary>
public bool? Session { get; set; }
/// <summary>
/// Gets or sets the expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies.
/// </summary>
public double? ExpirationDate { get; set; }
/// <summary>
/// Gets or sets the SameSite policy applied to this cookie. Can be "unspecified", "no_restriction", "lax" or "strict".
/// </summary>
public string SameSite { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
namespace ElectronNET.API.Entities
{
using System.Text.Json.Serialization;
/// <summary>
/// The cause of the cookie change (per Electron Cookies 'changed' event).
/// </summary>
public enum CookieChangedCause
{
/// <summary>
/// The cookie was changed directly by a consumer's action.
/// </summary>
@explicit,
/// <summary>
/// The cookie was automatically removed due to an insert operation that overwrote it.
/// </summary>
overwrite,
/// <summary>
/// The cookie was automatically removed as it expired.
/// </summary>
expired,
/// <summary>
/// The cookie was automatically evicted during garbage collection.
/// </summary>
evicted,
/// <summary>
/// The cookie was overwritten with an already-expired expiration date.
/// </summary>
[JsonPropertyName("expired_overwrite")]
expiredOverwrite
}
}

View File

@@ -0,0 +1,63 @@
using System.ComponentModel;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class CookieDetails
{
/// <summary>
/// Gets or sets the URL to associate the cookie with. The operation will be rejected if the URL is invalid.
/// </summary>
public string Url { get; set; }
/// <summary>
/// Gets or sets the name of the cookie. Empty by default if omitted.
/// </summary>
[DefaultValue("")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the value of the cookie. Empty by default if omitted.
/// </summary>
[DefaultValue("")]
public string Value { get; set; }
/// <summary>
/// Gets or sets the domain of the cookie; this will be normalized with a preceding dot so that it's also valid for subdomains. Empty by default if omitted.
/// </summary>
[DefaultValue("")]
public string Domain { get; set; }
/// <summary>
/// Gets or sets the path of the cookie. Empty by default if omitted.
/// </summary>
[DefaultValue("")]
public string Path { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the cookie should be marked as secure. Defaults to false unless the SameSite policy is set to <c>no_restriction</c> (SameSite=None).
/// </summary>
[DefaultValue(false)]
public bool Secure { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the cookie should be marked as HTTP only. Defaults to false.
/// </summary>
[DefaultValue(false)]
public bool HttpOnly { get; set; }
/// <summary>
/// Gets or sets the expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie and will not be retained between sessions.
/// </summary>
[DefaultValue(0)]
public double ExpirationDate { get; set; }
/// <summary>
/// Gets or sets the SameSite policy to apply to this cookie. Can be "unspecified", "no_restriction", "lax" or "strict". Default is "lax".
/// </summary>
public string SameSite { get; set; }
}
}

View File

@@ -1,16 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace ElectronNET.API.Entities
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
public class CookieFilter
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class CookieFilter
{
/// <summary>
/// (optional) - Retrieves cookies which are associated with url.Empty implies retrieving cookies of all URLs.
/// (optional) - Retrieves cookies which are associated with url. Empty implies retrieving cookies of all URLs.
/// </summary>
public string Url { get; set; }
@@ -32,12 +29,16 @@ namespace ElectronNET.API.Entities
/// <summary>
/// (optional) - Filters cookies by their Secure property.
/// </summary>
public bool Secure { get; set; }
public bool? Secure { get; set; }
/// <summary>
/// (optional) - Filters out session or persistent cookies.
/// </summary>
public bool Session { get; set; }
public bool? Session { get; set; }
/// <summary>
/// (optional) - Filters cookies by httpOnly.
/// </summary>
public bool? HttpOnly { get; set; }
}
}
}

View File

@@ -3,21 +3,22 @@
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class CreateFromBitmapOptions
{
/// <summary>
/// Gets or sets the width
/// Gets or sets the width in pixels. Required for nativeImage.createFromBitmap(buffer, options).
/// </summary>
public int? Width { get; set; }
/// <summary>
/// Gets or sets the height
/// Gets or sets the height in pixels. Required for nativeImage.createFromBitmap(buffer, options).
/// </summary>
public int? Height { get; set; }
/// <summary>
/// Gets or sets the scalefactor
/// Gets or sets the image scale factor. Optional, defaults to 1.0.
/// </summary>
public float ScaleFactor { get; set; } = 1.0f;
}
}
}

View File

@@ -3,20 +3,21 @@ namespace ElectronNET.API.Entities
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class CreateFromBufferOptions
{
/// <summary>
/// Gets or sets the width
/// Gets or sets the width. Required for bitmap buffers passed to nativeImage.createFromBuffer.
/// </summary>
public int? Width { get; set; }
/// <summary>
/// Gets or sets the height
/// Gets or sets the height. Required for bitmap buffers passed to nativeImage.createFromBuffer.
/// </summary>
public int? Height { get; set; }
/// <summary>
/// Gets or sets the scalefactor
/// The image scale factor. Optional, defaults to 1.0.
/// </summary>
public float ScaleFactor { get; set; } = 1.0f;
}

View File

@@ -3,6 +3,7 @@
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class CreateInterruptedDownloadOptions
{
/// <summary>
@@ -16,7 +17,7 @@
public string[] UrlChain { get; set; }
/// <summary>
///
/// (optional) - MIME type of the download.
/// </summary>
public string MimeType { get; set; }
@@ -41,9 +42,10 @@
public string ETag { get; set; }
/// <summary>
/// Time when download was started in number of seconds since UNIX epoch.
/// (optional) - Time when download was started in number of seconds since UNIX epoch.
/// Electron documents this as a Number (Double).
/// </summary>
public int StartTime { get; set; }
public double? StartTime { get; set; }
/// <summary>
///
@@ -64,4 +66,4 @@
ETag = eTag;
}
}
}
}

View File

@@ -21,6 +21,12 @@
/// </value>
public string Html { get; set; }
/// <summary>
/// Gets or sets the image.
/// Maps to clipboard.write({ image: NativeImage }).
/// </summary>
public NativeImage Image { get; set; }
/// <summary>
/// Gets or sets the RTF.

Some files were not shown because too many files have changed in this diff Show More