mirror of
https://github.com/ElectronNET/Electron.NET.git
synced 2026-07-09 10:17:49 +00:00
Compare commits
8 Commits
0.1.0
...
legacy/bui
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2910833e61 | ||
|
|
42e816e85c | ||
|
|
03c08503cc | ||
|
|
555f0378b4 | ||
|
|
79580327bd | ||
|
|
f6d17406cd | ||
|
|
9e79665690 | ||
|
|
9f98b5ca85 |
BIN
.github/WikiLinks.exe
vendored
BIN
.github/WikiLinks.exe
vendored
Binary file not shown.
46
.github/workflows/ci.yml
vendored
46
.github/workflows/ci.yml
vendored
@@ -7,38 +7,34 @@ env:
|
||||
NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
|
||||
|
||||
jobs:
|
||||
# linux:
|
||||
# runs-on: ubuntu-latest
|
||||
# timeout-minutes: 10
|
||||
|
||||
# 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.sh
|
||||
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 10
|
||||
linux:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Setup dotnet
|
||||
uses: actions/setup-dotnet@v4
|
||||
uses: actions/setup-dotnet@v1
|
||||
with:
|
||||
dotnet-version: |
|
||||
6.0.x
|
||||
8.0.x
|
||||
10.0.x
|
||||
7.0.x
|
||||
|
||||
- name: Build
|
||||
run: ./build.sh
|
||||
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
|
||||
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: |
|
||||
|
||||
59
.github/workflows/publish-wiki.yml
vendored
59
.github/workflows/publish-wiki.yml
vendored
@@ -1,59 +0,0 @@
|
||||
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'
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -266,4 +266,3 @@ __pycache__/
|
||||
|
||||
# Nuke build tool
|
||||
.nuke/temp
|
||||
/publish.cmd
|
||||
|
||||
@@ -1,54 +1,19 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"title": "Build Schema",
|
||||
"$ref": "#/definitions/build",
|
||||
"definitions": {
|
||||
"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": {
|
||||
"build": {
|
||||
"type": "object",
|
||||
"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"
|
||||
@@ -58,8 +23,25 @@
|
||||
"description": "Shows the help text for this build assembly"
|
||||
},
|
||||
"Host": {
|
||||
"type": "string",
|
||||
"description": "Host for execution. Default is 'automatic'",
|
||||
"$ref": "#/definitions/Host"
|
||||
"enum": [
|
||||
"AppVeyor",
|
||||
"AzurePipelines",
|
||||
"Bamboo",
|
||||
"Bitbucket",
|
||||
"Bitrise",
|
||||
"GitHubActions",
|
||||
"GitLab",
|
||||
"Jenkins",
|
||||
"Rider",
|
||||
"SpaceAutomation",
|
||||
"TeamCity",
|
||||
"Terminal",
|
||||
"TravisCI",
|
||||
"VisualStudio",
|
||||
"VSCode"
|
||||
]
|
||||
},
|
||||
"NoLogo": {
|
||||
"type": "boolean",
|
||||
@@ -80,6 +62,10 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ReleaseNotesFilePath": {
|
||||
"type": "string",
|
||||
"description": "ReleaseNotesFilePath - To determine the SemanticVersion"
|
||||
},
|
||||
"Root": {
|
||||
"type": "string",
|
||||
"description": "Root directory during build execution"
|
||||
@@ -88,50 +74,71 @@
|
||||
"type": "array",
|
||||
"description": "List of targets to be skipped. Empty list skips all dependencies",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExecutableTarget"
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Clean",
|
||||
"Compile",
|
||||
"CompileSample",
|
||||
"CreatePackages",
|
||||
"Default",
|
||||
"ElectronizeCustomWin7TargetSample",
|
||||
"ElectronizeGenericTargetSample",
|
||||
"ElectronizeLinuxTargetSample",
|
||||
"ElectronizeMacOsTargetSample",
|
||||
"ElectronizeWindowsTargetSample",
|
||||
"Package",
|
||||
"PrePublish",
|
||||
"Publish",
|
||||
"PublishPackages",
|
||||
"PublishPreRelease",
|
||||
"PublishRelease",
|
||||
"Restore",
|
||||
"RunUnitTests"
|
||||
]
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
"$ref": "#/definitions/ExecutableTarget"
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Clean",
|
||||
"Compile",
|
||||
"CompileSample",
|
||||
"CreatePackages",
|
||||
"Default",
|
||||
"ElectronizeCustomWin7TargetSample",
|
||||
"ElectronizeGenericTargetSample",
|
||||
"ElectronizeLinuxTargetSample",
|
||||
"ElectronizeMacOsTargetSample",
|
||||
"ElectronizeWindowsTargetSample",
|
||||
"Package",
|
||||
"PrePublish",
|
||||
"Publish",
|
||||
"PublishPackages",
|
||||
"PublishPreRelease",
|
||||
"PublishRelease",
|
||||
"Restore",
|
||||
"RunUnitTests"
|
||||
]
|
||||
}
|
||||
},
|
||||
"Verbosity": {
|
||||
"type": "string",
|
||||
"description": "Logging verbosity during build execution. Default is 'Normal'",
|
||||
"$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"
|
||||
"Minimal",
|
||||
"Normal",
|
||||
"Quiet",
|
||||
"Verbose"
|
||||
]
|
||||
},
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"$schema": "./build.schema.json",
|
||||
"Solution": "src/ElectronNET.Lean.sln"
|
||||
"Solution": "src/ElectronNET.sln"
|
||||
}
|
||||
4
.vscode/launch.json
vendored
4
.vscode/launch.json
vendored
@@ -10,9 +10,9 @@
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceRoot}/src/ElectronNET.CLI/bin/Debug/net8.0/dotnet-electronize.dll",
|
||||
"program": "${workspaceRoot}/ElectronNET.CLI/bin/Debug/netcoreapp2.0/dotnet-electronize.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceRoot}/src/ElectronNET.CLI",
|
||||
"cwd": "${workspaceRoot}/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
2
.vscode/tasks.json
vendored
@@ -7,7 +7,7 @@
|
||||
"label": "build",
|
||||
"type": "shell",
|
||||
"command": "dotnet",
|
||||
"args": ["build", "${workspaceRoot}/src/ElectronNET.CLI/ElectronNET.CLI.csproj"],
|
||||
"args": ["build", "${workspaceRoot}/ElectronNET.CLI/ElectronNET.CLI.csproj"],
|
||||
"problemMatcher": "$msCompile",
|
||||
"group": {
|
||||
"_id": "build",
|
||||
|
||||
424
Changelog.md
424
Changelog.md
@@ -1,85 +1,377 @@
|
||||
# 0.1.0
|
||||
# 23.6.2
|
||||
|
||||
## ElectronNET.Core
|
||||
## ElectronNET.API
|
||||
|
||||
- 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
|
||||
* Fixed escaping of URL (#735) @cosmo0
|
||||
* Changed `ZoomFactor` type from `int` to `double` (#754) @Yuvix25
|
||||
|
||||
# 0.0.18
|
||||
## ElectronNET.CLI
|
||||
|
||||
## ElectronNET.Core
|
||||
* (none)
|
||||
|
||||
### Highlights
|
||||
## Infrastructure
|
||||
|
||||
- **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
|
||||
* Changed build system to NUKE #757 @FlorianRappl
|
||||
* Updated target framework for host project #753 @r-pankevicius
|
||||
|
||||
### Build System & Project Structure
|
||||
# 23.6.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: Upgrade to .NET 6 support
|
||||
|
||||
- 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)
|
||||
## ElectronNET.API
|
||||
|
||||
### Debugging & Runtime
|
||||
* 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)
|
||||
|
||||
- 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
|
||||
# 13.5.1
|
||||
|
||||
### Technical Improvements
|
||||
ElectronNET.CLI:
|
||||
|
||||
- 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
|
||||
* 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)
|
||||
|
||||
### Package & Distribution
|
||||
# 11.5.1
|
||||
|
||||
- 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
|
||||
ElectronNET.CLI:
|
||||
|
||||
### Migration & Compatibility
|
||||
* 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)
|
||||
|
||||
- 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
|
||||
ElectronNET.API:
|
||||
|
||||
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.
|
||||
* 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)
|
||||
|
||||
`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)
|
||||
|
||||
# 9.31.2
|
||||
|
||||
* Electron-Builder fixed for Windows builds.
|
||||
|
||||
# 9.31.1
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* 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
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017-2025 Gregor Biswanger, Robert Mühsig, Florian Rappl
|
||||
Copyright (c) 2017-2023 Gregor Biswanger, Robert Mühsig
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<config>
|
||||
<add key="repositoryPath" value="artifacts" />
|
||||
</config>
|
||||
<packageSources>
|
||||
<packageSources>
|
||||
<clear />
|
||||
<add key="LocalDev" value="artifacts" />
|
||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||
</packageSources>
|
||||
</packageSources>
|
||||
</configuration>
|
||||
344
README.md
344
README.md
@@ -2,144 +2,215 @@
|
||||
|
||||
[](https://donorbox.org/electron-net) [](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [](https://github.com/ElectronNET/Electron.NET/actions/workflows/ci.yml)
|
||||
|
||||
# Electron.NET Core is here!
|
||||
Build cross platform desktop apps with .NET 6 and Blazor, ASP.NET Core (Razor Pages, MVC).
|
||||
|
||||
## A Complete Transformation
|
||||
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.
|
||||
|
||||
`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.
|
||||
The CLI extensions hosts our toolset to build and start Electron.NET applications.
|
||||
|
||||
Read more: [**What's New in `ElectronNET.Core`**](https://github.com/ElectronNET/Electron.NET/wiki/What's-New)
|
||||
## Wait - you host a .NET Core app inside Electron? Why?
|
||||
|
||||
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 ran by the Electron side is still the primary way, there's more flexibility now: both, dotnet 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 got with a lightweight console app instead.
|
||||
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.
|
||||
|
||||
## 📦 NuGet
|
||||
|
||||
* ElectronNET.Core: [](https://www.nuget.org/packages/ElectronNET.Core.API/)
|
||||
* ElectronNET.Core.API: [](https://www.nuget.org/packages/ElectronNET.Core.API/)
|
||||
* ElectronNET.Core.AspNet: [](https://www.nuget.org/packages/ElectronNET.Core.AspNet/)
|
||||
[ ElectronNET.API ](https://www.nuget.org/packages/ElectronNET.API/) | [ ElectronNET.CLI](https://www.nuget.org/packages/ElectronNET.CLI/)
|
||||
|
||||
## 🛠 Requirements to Run
|
||||
|
||||
You should have installed:
|
||||
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).
|
||||
|
||||
* .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).
|
||||
Also you should have installed:
|
||||
|
||||
## 👩🏫 Usage with ASP.NET
|
||||
* npm [contained in nodejs (at least Version 16.17.1)](https://nodejs.org)
|
||||
|
||||
- Create a new ASP.NET Core project
|
||||
- Install the following two NuGet packages:
|
||||
## 💬 Community
|
||||
|
||||
[](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.
|
||||
|
||||
```ps1
|
||||
dotnet add package ElectronNET.Core
|
||||
|
||||
dotnet add package ElectronNET.Core.AspNet
|
||||
PM> Install-Package ElectronNET.API
|
||||
```
|
||||
|
||||
### Classic ASP.NET Core
|
||||
## Setup Using Minimal-API
|
||||
|
||||
#### Enable Electron.NET on Startup
|
||||
You start Electron.NET up with an `UseElectron` WebHostBuilder-Extension and open the Electron Window:
|
||||
|
||||
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
|
||||
### Program.cs
|
||||
|
||||
```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();
|
||||
}
|
||||
```
|
||||
|
||||
### Minimal API Example
|
||||
|
||||
For a minimal API you can use:
|
||||
|
||||
```csharp
|
||||
using ElectronNET;
|
||||
using ElectronNET.API;
|
||||
using ElectronNET.API.Entities;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.WebHost.UseElectron(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();
|
||||
});
|
||||
// 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();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Error");
|
||||
}
|
||||
...
|
||||
|
||||
app.UseStaticFiles();
|
||||
app.UseRouting();
|
||||
app.UseAuthorization();
|
||||
app.MapRazorPages();
|
||||
app.Run();
|
||||
await app.StartAsync();
|
||||
|
||||
// Open the Electron-Window here
|
||||
await Electron.WindowManager.CreateWindowAsync();
|
||||
|
||||
app.WaitForShutdown();
|
||||
```
|
||||
|
||||
## 🚀 Starting and Debugging the Application
|
||||
## Setup using Normal-API
|
||||
|
||||
Just press `F5` in Visual Studio or use dotnet for debugging.
|
||||
### 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)
|
||||
{
|
||||
//...
|
||||
|
||||
Electron.WindowManager.CreateWindowAsync();
|
||||
}
|
||||
```
|
||||
|
||||
## 🚀 Starting the Application
|
||||
|
||||
To start the application make sure you have installed the "[ElectronNET.CLI](https://www.nuget.org/packages/ElectronNET.CLI/)" packages as global tool:
|
||||
|
||||
```sh
|
||||
dotnet tool install ElectronNET.CLI -g
|
||||
```
|
||||
|
||||
At the first time, you need an Electron.NET project initialization. Type the following command in your ASP.NET Core folder:
|
||||
|
||||
```sh
|
||||
electronize init
|
||||
```
|
||||
|
||||
* Now a electronnet.manifest.json should appear in your ASP.NET Core project
|
||||
* Now run the following:
|
||||
|
||||
```sh
|
||||
electronize start
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
## 📔 Usage of the Electron API
|
||||
|
||||
A complete documentation is available on the Wiki.
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
> [!NOTE]
|
||||
> The video hasn't been updated for the changes in ElectronNET.Core, so it is partially outdated.
|
||||
## ⛏ 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)).
|
||||
|
||||
Consequently, 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
|
||||
```
|
||||
|
||||
## 👨💻 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.
|
||||
|
||||
## 🙋♀️🙋♂ 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).
|
||||
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!
|
||||
@@ -155,7 +226,106 @@ Any support appreciated! 🍻
|
||||
|
||||
## 🎉 License
|
||||
|
||||
MIT-licensed. See [LICENSE](https://github.com/ElectronNET/Electron.NET/blob/main/LICENSE) for details.
|
||||
MIT-licensed. See [LICENSE](./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();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,23 +0,0 @@
|
||||
<?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
489
docs/API/App.md
@@ -1,489 +0,0 @@
|
||||
# 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
|
||||
@@ -1,243 +0,0 @@
|
||||
# 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
|
||||
@@ -1,231 +0,0 @@
|
||||
# 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
|
||||
@@ -1,160 +0,0 @@
|
||||
# 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
209
docs/API/Dock.md
@@ -1,209 +0,0 @@
|
||||
# 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
|
||||
@@ -1,189 +0,0 @@
|
||||
# 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
|
||||
@@ -1,152 +0,0 @@
|
||||
# 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
|
||||
@@ -1,167 +0,0 @@
|
||||
# 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
210
docs/API/Menu.md
@@ -1,210 +0,0 @@
|
||||
# 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
|
||||
@@ -1,189 +0,0 @@
|
||||
# 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
|
||||
@@ -1,164 +0,0 @@
|
||||
# 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
|
||||
@@ -1,62 +0,0 @@
|
||||
# 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
|
||||
@@ -1,188 +0,0 @@
|
||||
# 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
|
||||
@@ -1,174 +0,0 @@
|
||||
# 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
|
||||
@@ -1,175 +0,0 @@
|
||||
# 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
232
docs/API/Tray.md
@@ -1,232 +0,0 @@
|
||||
# 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
|
||||
@@ -1,292 +0,0 @@
|
||||
# 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
|
||||
@@ -1,208 +0,0 @@
|
||||
# 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
|
||||
@@ -1,51 +0,0 @@
|
||||
|
||||
|
||||
# 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
|
||||
|
||||
[](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!
|
||||
|
||||
[](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)
|
||||
|
||||
* **[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. 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.
|
||||
|
||||
* **[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.
|
||||
@@ -1,90 +0,0 @@
|
||||
# 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
|
||||
@@ -1,170 +0,0 @@
|
||||
# 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` 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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🎯 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.
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,25 +0,0 @@
|
||||
<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>
|
||||
@@ -1,129 +0,0 @@
|
||||
|
||||
# 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
|
||||
@@ -1,166 +0,0 @@
|
||||
|
||||
|
||||
# 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.1.0" />
|
||||
</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
|
||||
@@ -1,53 +0,0 @@
|
||||
|
||||
## 🛠 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
59
docs/Home.md
@@ -1,59 +0,0 @@
|
||||
|
||||
|
||||
# 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).
|
||||
@@ -1,116 +0,0 @@
|
||||
# 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
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
|
||||
# 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':
|
||||
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
## 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>
|
||||
<PackageId>$(MSBuildProjectName.Replace(".", "-").ToLower())</PackageId>
|
||||
<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": "$(PackageId)",
|
||||
"productName": "$(ElectronTitle)",
|
||||
"build": {
|
||||
"appId": "$(PackageId)",
|
||||
"linux": {
|
||||
"desktop": {
|
||||
"entry": { "Name": "$(Title)" }
|
||||
},
|
||||
"executableName": "$(PackageId)"
|
||||
},
|
||||
"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
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
# 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
|
||||
@@ -1,145 +0,0 @@
|
||||
# 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>
|
||||
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
</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>
|
||||
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
</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>
|
||||
```
|
||||
|
||||
### 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
|
||||
@@ -1,246 +0,0 @@
|
||||
# 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
|
||||
|
||||
|
||||

|
||||
|
||||
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.
|
||||
@@ -1,2 +0,0 @@
|
||||
|
||||
Want to contribute to this documentation? Please fork and create a PR! The Wiki is autogenerated from the /docs content in the repository.
|
||||
@@ -1,50 +0,0 @@
|
||||
<!-- 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)
|
||||
- [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)
|
||||
|
||||
# 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.
|
Before Width: | Height: | Size: 29 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 23 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 26 KiB |
7857
docs/md-styles.css
7857
docs/md-styles.css
File diff suppressed because it is too large
Load Diff
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "10.0.100",
|
||||
"rollForward": "feature",
|
||||
"allowPrerelease": false
|
||||
}
|
||||
}
|
||||
180
nuke/Build.cs
180
nuke/Build.cs
@@ -3,7 +3,6 @@ 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;
|
||||
@@ -16,9 +15,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
|
||||
{
|
||||
@@ -28,20 +27,25 @@ 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 lates changelog version")]
|
||||
[Nuke.Common.Parameter("ReleaseNotesFilePath - To determine the SemanticVersion")]
|
||||
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";
|
||||
@@ -56,7 +60,16 @@ class Build : NukeBuild
|
||||
|
||||
string Version { get; set; }
|
||||
|
||||
string VersionPostFix { get; set; }
|
||||
AbsolutePath[] Projects
|
||||
{
|
||||
get
|
||||
{
|
||||
var api = SourceDirectory / ApiTargetLibName / $"{ApiTargetLibName}.csproj";
|
||||
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
|
||||
var projects = new[] { api, cli };
|
||||
return projects;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnBuildInitialized()
|
||||
{
|
||||
@@ -69,19 +82,9 @@ class Build : NukeBuild
|
||||
LatestReleaseNotes = ChangeLog.First();
|
||||
LatestReleaseNotes.NotNull("LatestVersion could not be read!");
|
||||
|
||||
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);
|
||||
Log.Debug("Using LastestVersion from ChangeLog: {LatestVersion}", LatestReleaseNotes.Version);
|
||||
SemVersion = LatestReleaseNotes.SemVersion;
|
||||
Version = propsVersion.ToString();
|
||||
Version = LatestReleaseNotes.Version.ToString();
|
||||
|
||||
if (GitHubActions != null)
|
||||
{
|
||||
@@ -91,60 +94,145 @@ class Build : NukeBuild
|
||||
|
||||
if (ScheduledTargets.Contains(Default))
|
||||
{
|
||||
VersionPostFix = $"-ci.{buildNumber}";
|
||||
Version = $"{Version}-ci.{buildNumber}";
|
||||
}
|
||||
else if (ScheduledTargets.Contains(PrePublish))
|
||||
{
|
||||
VersionPostFix = $"-pre.{buildNumber}";
|
||||
Version = $"{Version}-alpha.{buildNumber}";
|
||||
}
|
||||
}
|
||||
else if (ScheduledTargets.Contains(PrePublish))
|
||||
{
|
||||
VersionPostFix = $"-pre";
|
||||
}
|
||||
|
||||
Log.Information("Building version {Version} with postfix {VersionPostFix}", Version, VersionPostFix);
|
||||
Log.Information("Building version: {Version}", Version);
|
||||
}
|
||||
|
||||
Target Clean => _ => _
|
||||
.Before(Restore)
|
||||
.Executes(() =>
|
||||
{
|
||||
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(dir => dir.DeleteDirectory());
|
||||
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory);
|
||||
});
|
||||
|
||||
Target Restore => _ => _
|
||||
.Executes(() =>
|
||||
{
|
||||
DotNetRestore(s => s.SetProjectFile(Solution));
|
||||
Projects.ForEach(project =>
|
||||
{
|
||||
DotNetRestore(s => s
|
||||
.SetProjectFile(project));
|
||||
});
|
||||
});
|
||||
|
||||
Target Compile => _ => _
|
||||
.DependsOn(Restore)
|
||||
.Executes(() =>
|
||||
{
|
||||
DotNetBuild(s => s
|
||||
.SetProjectFile(Solution)
|
||||
.SetConfiguration(Configuration)
|
||||
.SetProperty("GeneratePackageOnBuild", "True")
|
||||
.SetProperty("VersionPostFix", VersionPostFix ?? string.Empty));
|
||||
Projects.ForEach(project =>
|
||||
{
|
||||
DotNetBuild(s => s
|
||||
.SetProjectFile(project)
|
||||
.SetVersion(Version)
|
||||
.SetConfiguration(Configuration)
|
||||
.EnableNoRestore());
|
||||
});
|
||||
});
|
||||
|
||||
Target RunUnitTests => _ => _
|
||||
.DependsOn(Compile)
|
||||
.Executes(() =>
|
||||
{
|
||||
var TestProject = SourceDirectory / "ElectronNET.IntegrationTests" / "ElectronNET.IntegrationTests.csproj";
|
||||
Projects.ForEach(project =>
|
||||
{
|
||||
DotNetTest(s => s
|
||||
.SetProjectFile(project)
|
||||
.SetConfiguration(Configuration)
|
||||
.EnableNoRestore()
|
||||
.EnableNoBuild());
|
||||
});
|
||||
});
|
||||
|
||||
DotNetTest(s => s
|
||||
.SetProjectFile(TestProject)
|
||||
.SetConfiguration(Configuration)
|
||||
.When(_ => GitHubActions.Instance is not null, x => x.SetLoggers("GitHubActions"))
|
||||
);
|
||||
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);
|
||||
});
|
||||
|
||||
Target PublishPackages => _ => _
|
||||
.DependsOn(Compile)
|
||||
.DependsOn(CreatePackages)
|
||||
.DependsOn(RunUnitTests)
|
||||
.Executes(() =>
|
||||
{
|
||||
@@ -156,7 +244,7 @@ class Build : NukeBuild
|
||||
throw new BuildAbortedException("Could not resolve the NuGet API key.");
|
||||
}
|
||||
|
||||
foreach (var nupkg in ResultDirectory.GlobFiles("*.nupkg"))
|
||||
foreach (var nupkg in GlobFiles(ResultDirectory, "*.nupkg"))
|
||||
{
|
||||
DotNetNuGetPush(s => s
|
||||
.SetTargetPath(nupkg)
|
||||
@@ -192,9 +280,9 @@ class Build : NukeBuild
|
||||
new InMemoryCredentialStore(credentials));
|
||||
|
||||
GitHubTasks.GitHubClient.Repository.Release
|
||||
.Create("ElectronNET", "Electron.NET", new NewRelease(Version + VersionPostFix)
|
||||
.Create("ElectronNET", "Electron.NET", new NewRelease(Version)
|
||||
{
|
||||
Name = "ElectronNET.Core " + Version + VersionPostFix,
|
||||
Name = Version,
|
||||
Body = String.Join(Environment.NewLine, LatestReleaseNotes.Notes),
|
||||
Prerelease = true,
|
||||
TargetCommitish = "develop",
|
||||
@@ -230,7 +318,7 @@ class Build : NukeBuild
|
||||
GitHubTasks.GitHubClient.Repository.Release
|
||||
.Create("ElectronNET", "Electron.NET", new NewRelease(Version)
|
||||
{
|
||||
Name = "ElectronNET.Core " + Version,
|
||||
Name = Version,
|
||||
Body = String.Join(Environment.NewLine, LatestReleaseNotes.Notes),
|
||||
Prerelease = false,
|
||||
TargetCommitish = "main",
|
||||
@@ -239,7 +327,7 @@ class Build : NukeBuild
|
||||
|
||||
Target Package => _ => _
|
||||
.DependsOn(RunUnitTests)
|
||||
.DependsOn(Compile);
|
||||
.DependsOn(CreatePackages);
|
||||
|
||||
Target Default => _ => _
|
||||
.DependsOn(Package);
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace></RootNamespace>
|
||||
<NoWarn>CS0649;CS0169</NoWarn>
|
||||
<NukeRootDirectory>..</NukeRootDirectory>
|
||||
@@ -11,11 +11,11 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Nuke.Common" Version="9.0.4" />
|
||||
<PackageReference Include="Nuke.Common" Version="6.2.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageDownload Include="NuGet.CommandLine" Version="[6.12.2]" />
|
||||
<PackageDownload Include="NuGet.CommandLine" Version="[6.3.1]" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
2
src/.editorconfig
Normal file
2
src/.editorconfig
Normal file
@@ -0,0 +1,2 @@
|
||||
[*.cs]
|
||||
dotnet_diagnostic.CA1416.severity=silent
|
||||
@@ -1,373 +0,0 @@
|
||||
// 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 const int PropertyTimeout = 1000;
|
||||
|
||||
private readonly string objectName;
|
||||
private readonly ConcurrentDictionary<string, PropertyGetter> propertyGetters;
|
||||
private readonly ConcurrentDictionary<string, string> propertyEventNames = new();
|
||||
private readonly ConcurrentDictionary<string, string> propertyMessageNames = new();
|
||||
private readonly ConcurrentDictionary<string, string> methodMessageNames = new();
|
||||
private static readonly ConcurrentDictionary<string, EventContainer> eventContainers = new();
|
||||
private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, PropertyGetter>> AllPropertyGetters = 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();
|
||||
propertyGetters = AllPropertyGetters.GetOrAdd(objectName, _ => new ConcurrentDictionary<string, PropertyGetter>());
|
||||
}
|
||||
|
||||
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> GetPropertyAsync<T>(object arg = null, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
Debug.Assert(callerName != null, nameof(callerName) + " != null");
|
||||
|
||||
lock (this.objLock)
|
||||
{
|
||||
return this.propertyGetters.GetOrAdd(callerName, _ =>
|
||||
{
|
||||
var getter = new PropertyGetter<T>(this, callerName, PropertyTimeout, arg);
|
||||
|
||||
getter.Task<T>().ContinueWith(_ =>
|
||||
{
|
||||
lock (this.objLock)
|
||||
{
|
||||
return this.propertyGetters.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 = EventName(callerName);
|
||||
|
||||
var eventKey = EventKey(eventName, id);
|
||||
|
||||
lock (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 = EventName(callerName);
|
||||
var eventKey = EventKey(eventName, id);
|
||||
|
||||
lock (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 = EventName(callerName);
|
||||
var eventKey = EventKey(eventName, id);
|
||||
|
||||
lock (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 = EventName(callerName);
|
||||
var eventKey = EventKey(eventName, id);
|
||||
|
||||
lock (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 (SocketEventNameType)
|
||||
{
|
||||
case SocketEventNameTypes.DashedLower:
|
||||
return $"{objectName}-{callerName.ToDashedEventName()}";
|
||||
case SocketEventNameTypes.CamelCase:
|
||||
return $"{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 PropertyGetter
|
||||
{
|
||||
public abstract Task<T> Task<T>();
|
||||
}
|
||||
|
||||
internal class PropertyGetter<T> : PropertyGetter
|
||||
{
|
||||
private readonly Task<T> tcsTask;
|
||||
private TaskCompletionSource<T> tcs;
|
||||
|
||||
public PropertyGetter(ApiBase apiBase, string callerName, int timeoutMs, 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.propertyEventNames.GetOrAdd(callerName, s => $"{apiBase.objectName}-{s.StripAsync().LowerFirst()}-completed");
|
||||
break;
|
||||
case SocketTaskEventNameTypes.NoDashUpperFirst:
|
||||
eventName = apiBase.propertyEventNames.GetOrAdd(callerName, s => $"{apiBase.objectName}{s.StripAsync()}Completed");
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
|
||||
switch (apiBase.SocketTaskMessageNameType)
|
||||
{
|
||||
case SocketTaskMessageNameTypes.DashesLowerFirst:
|
||||
messageName = apiBase.propertyMessageNames.GetOrAdd(callerName, s => $"{apiBase.objectName}-{s.StripAsync().LowerFirst()}");
|
||||
break;
|
||||
case SocketTaskMessageNameTypes.NoDashUpperFirst:
|
||||
messageName = apiBase.propertyMessageNames.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(PropertyTimeout).ContinueWith(_ =>
|
||||
{
|
||||
if (this.tcs != null)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (this.tcs != null)
|
||||
{
|
||||
var ex = new TimeoutException($"No response after {timeoutMs:D}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>)eventActionT;
|
||||
}
|
||||
|
||||
private void SetEventActionT<T>(Action<T> actionT)
|
||||
{
|
||||
eventActionT = actionT;
|
||||
}
|
||||
|
||||
public void OnEventAction() => eventAction?.Invoke();
|
||||
|
||||
public void OnEventActionT<T>(T p) => GetEventActionT<T>()?.Invoke(p);
|
||||
|
||||
public void Register(Action receiver)
|
||||
{
|
||||
eventAction += receiver;
|
||||
}
|
||||
|
||||
public void Register<T>(Action<T> receiver)
|
||||
{
|
||||
var actionT = GetEventActionT<T>();
|
||||
actionT += receiver;
|
||||
SetEventActionT(actionT);
|
||||
}
|
||||
|
||||
public bool Unregister(Action receiver)
|
||||
{
|
||||
eventAction -= receiver;
|
||||
return this.eventAction != null;
|
||||
}
|
||||
|
||||
public bool Unregister<T>(Action<T> receiver)
|
||||
{
|
||||
var actionT = GetEventActionT<T>();
|
||||
actionT -= receiver;
|
||||
SetEventActionT(actionT);
|
||||
|
||||
return actionT != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,382 +0,0 @@
|
||||
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(() => GetPropertyAsync<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(() => GetPropertyAsync<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(() => GetPropertyAsync<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(() => GetPropertyAsync<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(() => GetPropertyAsync<bool>()).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-allowDowngrade-set", value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For test only.
|
||||
/// </summary>
|
||||
public string UpdateConfigPath
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => GetPropertyAsync<string>()).Result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The current application version
|
||||
/// </summary>
|
||||
public Task<SemVer> CurrentVersionAsync
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => GetPropertyAsync<SemVer>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the update channel. Not applicable for GitHub.
|
||||
/// Doesn’t 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.
|
||||
/// Doesn’t return channel from the update configuration, only if was previously set.
|
||||
/// </summary>
|
||||
public Task<string> ChannelAsync
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => GetPropertyAsync<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(() => GetPropertyAsync<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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,65 +0,0 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Serialization;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Query and modify a session's cookies.
|
||||
/// </summary>
|
||||
public class Cookies
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the identifier.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The identifier.
|
||||
/// </value>
|
||||
public int Id { get; private set; }
|
||||
|
||||
internal Cookies(int id)
|
||||
{
|
||||
Id = id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when a cookie is changed because it was added, edited, removed, or expired.
|
||||
/// </summary>
|
||||
public event Action<Cookie, CookieChangedCause, bool> OnChanged
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_changed == null)
|
||||
{
|
||||
BridgeConnector.Socket.On<JsonElement>("webContents-session-cookies-changed" + Id, (args) =>
|
||||
{
|
||||
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
|
||||
{
|
||||
_changed -= value;
|
||||
|
||||
if (_changed == null)
|
||||
BridgeConnector.Socket.Off("webContents-session-cookies-changed" + Id);
|
||||
}
|
||||
}
|
||||
|
||||
private event Action<Cookie, CookieChangedCause, bool> _changed;
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
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 system’s 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
using ElectronNET.API.Serialization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
internal class NativeImageJsonConverter : JsonConverter<NativeImage>
|
||||
{
|
||||
public override void Write(Utf8JsonWriter writer, NativeImage value, JsonSerializerOptions options)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
writer.WriteNullValue();
|
||||
return;
|
||||
}
|
||||
|
||||
var scaledImages = value.GetAllScaledImages();
|
||||
JsonSerializer.Serialize(writer, scaledImages, ElectronJson.Options);
|
||||
}
|
||||
|
||||
public override NativeImage Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
var dict = JsonSerializer.Deserialize<Dictionary<float, string>>(ref reader, ElectronJson.Options);
|
||||
var newDictionary = new Dictionary<float, Image>();
|
||||
foreach (var item in dict)
|
||||
{
|
||||
var bytes = Convert.FromBase64String(item.Value);
|
||||
newDictionary.Add(item.Key, Image.FromStream(new MemoryStream(bytes)));
|
||||
}
|
||||
|
||||
return new NativeImage(newDictionary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
namespace ElectronNET.API.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 'OnDidFailLoad' event details.
|
||||
/// </summary>
|
||||
public class OnDidFailLoadInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// The full list of error codes and their meaning is available here
|
||||
/// https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h
|
||||
/// </summary>
|
||||
public int ErrorCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Validated URL.
|
||||
/// </summary>
|
||||
public string ValidatedUrl { get; set; }
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
namespace ElectronNET.API.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 'OnDidNavigate' event details.
|
||||
/// </summary>
|
||||
public class OnDidNavigateInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Navigated URL.
|
||||
/// </summary>
|
||||
public string Url { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// HTTP response code.
|
||||
/// </summary>
|
||||
public int HttpResponseCode { get; set; }
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
namespace ElectronNET.API.Entities;
|
||||
|
||||
public class PageSize
|
||||
{
|
||||
private readonly string _value;
|
||||
|
||||
public PageSize()
|
||||
{
|
||||
}
|
||||
|
||||
private PageSize(string value) : this() => _value = value;
|
||||
|
||||
public double Height { get; set; }
|
||||
|
||||
public double Width { get; set; }
|
||||
|
||||
public static implicit operator string(PageSize pageSize) => pageSize?._value;
|
||||
|
||||
public static implicit operator PageSize(string value) => new(value);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
/// An object listing the version strings specific to Electron
|
||||
/// </summary>
|
||||
/// <param name="Chrome">Value representing Chrome's version string</param>
|
||||
/// <param name="Electron">Value representing Electron's version string</param>
|
||||
/// <returns></returns>
|
||||
public record ProcessVersions(string Chrome, string Electron);
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
namespace ElectronNET.API.Entities;
|
||||
|
||||
public class TitleBarOverlay
|
||||
{
|
||||
private readonly bool? _value;
|
||||
|
||||
public TitleBarOverlay()
|
||||
{
|
||||
}
|
||||
|
||||
private TitleBarOverlay(bool value) : this() => _value = value;
|
||||
|
||||
public string Color { get; set; }
|
||||
|
||||
public double Height { get; set; }
|
||||
|
||||
public string SymbolColor { get; set; }
|
||||
|
||||
public static implicit operator bool?(TitleBarOverlay titleBarOverlay) => titleBarOverlay?._value;
|
||||
|
||||
public static implicit operator TitleBarOverlay(bool value) => new(value);
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
using System;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Monitor power state changes..
|
||||
/// </summary>
|
||||
public sealed class PowerMonitor: ApiBase
|
||||
{
|
||||
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
|
||||
protected override SocketEventNameTypes SocketEventNameType => SocketEventNameTypes.DashedLower;
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when the system is about to lock the screen.
|
||||
/// </summary>
|
||||
public event Action OnLockScreen
|
||||
{
|
||||
add => AddEvent(value);
|
||||
remove => RemoveEvent(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when the system is about to unlock the screen.
|
||||
/// </summary>
|
||||
public event Action OnUnLockScreen
|
||||
{
|
||||
add => AddEvent(value);
|
||||
remove => RemoveEvent(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when the system is suspending.
|
||||
/// </summary>
|
||||
public event Action OnSuspend
|
||||
{
|
||||
add => AddEvent(value);
|
||||
remove => RemoveEvent(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when system is resuming.
|
||||
/// </summary>
|
||||
public event Action OnResume
|
||||
{
|
||||
add => AddEvent(value);
|
||||
remove => RemoveEvent(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when the system changes to AC power.
|
||||
/// </summary>
|
||||
public event Action OnAC
|
||||
{
|
||||
add => AddEvent(value);
|
||||
remove => RemoveEvent(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when system changes to battery power.
|
||||
/// </summary>
|
||||
public event Action OnBattery
|
||||
{
|
||||
add => AddEvent(value);
|
||||
remove => RemoveEvent(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when the system is about to reboot or shut down. If the event handler
|
||||
/// invokes `e.preventDefault()`, Electron will attempt to delay system shutdown in
|
||||
/// order for the app to exit cleanly.If `e.preventDefault()` is called, the app
|
||||
/// should exit as soon as possible by calling something like `app.quit()`.
|
||||
/// </summary>
|
||||
public event Action OnShutdown
|
||||
{
|
||||
add => AddEvent(value);
|
||||
remove => RemoveEvent(value);
|
||||
}
|
||||
|
||||
private static PowerMonitor _powerMonitor;
|
||||
private static object _syncRoot = new object();
|
||||
|
||||
internal PowerMonitor()
|
||||
{
|
||||
}
|
||||
|
||||
internal static PowerMonitor Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_powerMonitor == null)
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
if (_powerMonitor == null)
|
||||
{
|
||||
_powerMonitor = new PowerMonitor();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _powerMonitor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Serialization;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Electron's process object is extended from the Node.js process object. It adds the
|
||||
/// events, properties, and methods.
|
||||
/// </summary>
|
||||
public sealed class Process: ApiBase
|
||||
{
|
||||
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
|
||||
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
|
||||
internal Process()
|
||||
{
|
||||
}
|
||||
|
||||
internal static Process Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_process == null)
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
if (_process == null)
|
||||
{
|
||||
_process = new Process();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _process;
|
||||
}
|
||||
}
|
||||
|
||||
private static Process _process;
|
||||
|
||||
private static readonly object _syncRoot = new();
|
||||
|
||||
/// <summary>
|
||||
/// The process.execPath property returns the absolute pathname of the executable that
|
||||
/// started the Node.js process. Symbolic links, if any, are resolved.
|
||||
/// </summary>
|
||||
public Task<string> ExecPathAsync => GetPropertyAsync<string>();
|
||||
|
||||
/// <summary>
|
||||
/// The process.argv property returns an array containing the command-line arguments passed
|
||||
/// when the Node.js process was launched. The first element will be process.execPath. See
|
||||
/// process.argv0 if access to the original value of argv[0] is needed. The second element
|
||||
/// will be the path to the JavaScript file being executed. The remaining elements will be
|
||||
/// any additional command-line arguments
|
||||
/// </summary>
|
||||
public Task<string[]> ArgvAsync => GetPropertyAsync<string[]>();
|
||||
|
||||
/// <summary>
|
||||
/// The process.execPath property returns the absolute pathname of the executable that
|
||||
/// started the Node.js process. Symbolic links, if any, are resolved.
|
||||
/// </summary>
|
||||
public Task<string> TypeAsync => GetPropertyAsync<string>();
|
||||
|
||||
/// <summary>
|
||||
/// The process.versions property returns an object listing the version strings of
|
||||
/// chrome and electron.
|
||||
/// </summary>
|
||||
public Task<ProcessVersions> VersionsAsync => GetPropertyAsync<ProcessVersions>();
|
||||
|
||||
/// <summary>
|
||||
/// A Boolean. When app is started by being passed as parameter to the default app, this
|
||||
/// property is true in the main process, otherwise it is false.
|
||||
/// </summary>
|
||||
public Task<bool> DefaultAppAsync => GetPropertyAsync<bool>();
|
||||
|
||||
/// <summary>
|
||||
/// A Boolean, true when the current renderer context is the "main" renderer frame. If you
|
||||
/// want the ID of the current frame you should use webFrame.routingId
|
||||
/// </summary>
|
||||
public Task<bool> IsMainFrameAsync => GetPropertyAsync<bool>();
|
||||
|
||||
/// <summary>
|
||||
/// A String representing the path to the resources directory.
|
||||
/// </summary>
|
||||
public Task<string> ResourcesPathAsync => GetPropertyAsync<string>();
|
||||
|
||||
/// <summary>
|
||||
/// The number of seconds the current Node.js process has been running. The return value
|
||||
/// includes fractions of a second. Use Math.floor() to get whole seconds.
|
||||
/// </summary>
|
||||
public Task<double> UpTimeAsync => GetPropertyAsync<double>();
|
||||
|
||||
/// <summary>
|
||||
/// The PID of the electron process
|
||||
/// </summary>
|
||||
public Task<int> PidAsync => GetPropertyAsync<int>();
|
||||
|
||||
/// <summary>
|
||||
/// The operating system CPU architecture for which the Node.js binary was compiled
|
||||
/// </summary>
|
||||
public Task<string> ArchAsync => GetPropertyAsync<string>();
|
||||
|
||||
/// <summary>
|
||||
/// A string identifying the operating system platform on which the Node.js process is running
|
||||
/// </summary>
|
||||
public Task<string> PlatformAsync => GetPropertyAsync<string>();
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using ElectronNET.API.Serialization;
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieve information about screen size, displays, cursor position, etc.
|
||||
/// </summary>
|
||||
public sealed class Screen: ApiBase
|
||||
{
|
||||
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
|
||||
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
|
||||
protected override SocketEventNameTypes SocketEventNameType => SocketEventNameTypes.DashedLower;
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when an new Display has been added.
|
||||
/// </summary>
|
||||
public event Action<Display> OnDisplayAdded
|
||||
{
|
||||
add => AddEvent(value, GetHashCode());
|
||||
remove => RemoveEvent(value, GetHashCode());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when oldDisplay has been removed.
|
||||
/// </summary>
|
||||
public event Action<Display> OnDisplayRemoved
|
||||
{
|
||||
add => AddEvent(value, GetHashCode());
|
||||
remove => RemoveEvent(value, GetHashCode());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public event Action<Display, string[]> OnDisplayMetricsChanged
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_onDisplayMetricsChanged == null)
|
||||
{
|
||||
BridgeConnector.Socket.On<JsonElement>("screen-display-metrics-changed" + GetHashCode(), (args) =>
|
||||
{
|
||||
var arr = args.EnumerateArray().ToArray();
|
||||
var display = arr[0].Deserialize(ElectronJsonContext.Default.Display);
|
||||
var metrics = arr[1].Deserialize<string[]>(ElectronJson.Options);
|
||||
|
||||
_onDisplayMetricsChanged(display, metrics);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-screen-display-metrics-changed", GetHashCode());
|
||||
}
|
||||
_onDisplayMetricsChanged += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_onDisplayMetricsChanged -= value;
|
||||
|
||||
if (_onDisplayMetricsChanged == null)
|
||||
{
|
||||
BridgeConnector.Socket.Off("screen-display-metrics-changed" + GetHashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private event Action<Display, string[]> _onDisplayMetricsChanged;
|
||||
|
||||
private static Screen _screen;
|
||||
private static object _syncRoot = new object();
|
||||
|
||||
internal Screen()
|
||||
{
|
||||
}
|
||||
|
||||
internal static Screen Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_screen == null)
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
if (_screen == null)
|
||||
{
|
||||
_screen = new Screen();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _screen;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The current absolute position of the mouse pointer.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Task<Point> GetCursorScreenPointAsync() => GetPropertyAsync<Point>();
|
||||
|
||||
/// <summary>
|
||||
/// macOS: The height of the menu bar in pixels.
|
||||
/// </summary>
|
||||
/// <returns>The height of the menu bar in pixels.</returns>
|
||||
public Task<Rectangle> GetMenuBarWorkAreaAsync() => GetPropertyAsync<Rectangle>();
|
||||
|
||||
/// <summary>
|
||||
/// The primary display.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Task<Display> GetPrimaryDisplayAsync() => GetPropertyAsync<Display>();
|
||||
|
||||
/// <summary>
|
||||
/// An array of displays that are currently available.
|
||||
/// </summary>
|
||||
/// <returns>An array of displays that are currently available.</returns>
|
||||
public Task<Display[]> GetAllDisplaysAsync() => GetPropertyAsync<Display[]>();
|
||||
|
||||
/// <summary>
|
||||
/// The display nearest the specified point.
|
||||
/// </summary>
|
||||
/// <returns>The display nearest the specified point.</returns>
|
||||
public Task<Display> GetDisplayNearestPointAsync(Point point) => GetPropertyAsync<Display>(point);
|
||||
|
||||
/// <summary>
|
||||
/// The display that most closely intersects the provided bounds.
|
||||
/// </summary>
|
||||
/// <param name="rectangle"></param>
|
||||
/// <returns>The display that most closely intersects the provided bounds.</returns>
|
||||
public Task<Display> GetDisplayMatchingAsync(Rectangle rectangle) => GetPropertyAsync<Display>(rectangle);
|
||||
}
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace ElectronNET.API;
|
||||
|
||||
/// <summary>
|
||||
/// Render and control web pages.
|
||||
/// </summary>
|
||||
public class WebContents: ApiBase
|
||||
{
|
||||
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
|
||||
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
|
||||
protected override SocketEventNameTypes SocketEventNameType => SocketEventNameTypes.CamelCase;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the identifier.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The identifier.
|
||||
/// </value>
|
||||
public override int Id { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Manage browser sessions, cookies, cache, proxy settings, etc.
|
||||
/// </summary>
|
||||
public Session Session { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when the renderer process crashes or is killed.
|
||||
/// </summary>
|
||||
public event Action<bool> OnCrashed
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when the navigation is done, i.e. the spinner of the tab has
|
||||
/// stopped spinning, and the onload event was dispatched.
|
||||
/// </summary>
|
||||
public event Action OnDidFinishLoad
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when any frame (including main) starts navigating.
|
||||
/// </summary>
|
||||
public event Action<string> OnDidStartNavigation
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when a main frame navigation is done.
|
||||
/// This event is not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.
|
||||
/// </summary>
|
||||
public event Action<OnDidNavigateInfo> OnDidNavigate
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when a server side redirect occurs during navigation. For example a 302 redirect.
|
||||
/// This event will be emitted after OnDidStartNavigation and always before the OnDidRedirectNavigation event for the same navigation.
|
||||
/// </summary>
|
||||
public event Action<string> OnWillRedirect
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted after a server side redirect occurs during navigation. For example a 302 redirect.
|
||||
/// </summary>
|
||||
public event Action<string> OnDidRedirectNavigation
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This event is like OnDidFinishLoad but emitted when the load failed.
|
||||
/// </summary>
|
||||
public event Action<OnDidFailLoadInfo> OnDidFailLoad
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when an input event is sent to the WebContents.
|
||||
/// </summary>
|
||||
public event Action<InputEvent> InputEvent
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when the document in the top-level frame is loaded.
|
||||
/// </summary>
|
||||
public event Action OnDomReady
|
||||
{
|
||||
add => AddEvent(value, Id);
|
||||
remove => RemoveEvent(value, Id);
|
||||
}
|
||||
|
||||
internal WebContents(int id)
|
||||
{
|
||||
Id = id;
|
||||
Session = new Session(id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the devtools.
|
||||
/// </summary>
|
||||
public void OpenDevTools()
|
||||
{
|
||||
BridgeConnector.Socket.Emit("webContentsOpenDevTools", Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the devtools.
|
||||
/// </summary>
|
||||
/// <param name="openDevToolsOptions"></param>
|
||||
public void OpenDevTools(OpenDevToolsOptions openDevToolsOptions)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("webContentsOpenDevTools", Id, openDevToolsOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get system printers.
|
||||
/// </summary>
|
||||
/// <returns>printers</returns>
|
||||
public Task<PrinterInfo[]> GetPrintersAsync() => GetPropertyAsync<PrinterInfo[]>();
|
||||
|
||||
/// <summary>
|
||||
/// Prints window's web page.
|
||||
/// </summary>
|
||||
/// <param name="options"></param>
|
||||
/// <returns>success</returns>
|
||||
public Task<bool> PrintAsync(PrintOptions options) => GetPropertyAsync<bool>(options);
|
||||
/// <summary>
|
||||
/// Prints window's web page.
|
||||
/// </summary>
|
||||
/// <returns>success</returns>
|
||||
public Task<bool> PrintAsync() => GetPropertyAsync<bool>(string.Empty);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns>success</returns>
|
||||
public Task<bool> PrintToPDFAsync(string path, PrintToPDFOptions options = null)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
|
||||
BridgeConnector.Socket.Once<bool>("webContents-printToPDF-completed", tcs.SetResult);
|
||||
|
||||
if (options == null)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("webContents-printToPDF", Id, "", path);
|
||||
}
|
||||
else
|
||||
{
|
||||
BridgeConnector.Socket.Emit("webContents-printToPDF", Id, options, path);
|
||||
}
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates script code in page.
|
||||
/// </summary>
|
||||
/// <param name="code">The code to execute.</param>
|
||||
/// <param name="userGesture">if set to <c>true</c> simulate a user gesture.</param>
|
||||
/// <returns>The result of the executed code.</returns>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Code execution will be suspended until web page stop loading.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public Task<T> ExecuteJavaScriptAsync<T>(string code, bool userGesture = false)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<T>();
|
||||
|
||||
BridgeConnector.Socket.Once<T>("webContents-executeJavaScript-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("webContents-executeJavaScript", Id, code, userGesture);
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is used to get the Url of the loaded page.
|
||||
/// It's usefull if a web-server redirects you and you need to know where it redirects. For instance, It's useful in case of Implicit Authorization.
|
||||
/// </summary>
|
||||
/// <returns>URL of the loaded page</returns>
|
||||
public Task<string> GetUrl()
|
||||
{
|
||||
var tcs = new TaskCompletionSource<string>();
|
||||
|
||||
BridgeConnector.Socket.Once<string>("webContents-getUrl" + Id, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("webContents-getUrl", Id);
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
public Task LoadURLAsync(string url)
|
||||
{
|
||||
return LoadURLAsync(url, new LoadURLOptions());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="options"></param>
|
||||
public Task LoadURLAsync(string url, LoadURLOptions options)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<object>();
|
||||
|
||||
BridgeConnector.Socket.Once("webContents-loadURL-complete" + Id, () =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("webContents-loadURL-error" + Id);
|
||||
tcs.SetResult(null);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Once<string>("webContents-loadURL-error" + Id, (error) =>
|
||||
{
|
||||
tcs.SetException(new InvalidOperationException(error));
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("webContents-loadURL", Id, url, options);
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts CSS into the web page.
|
||||
/// See: https://www.electronjs.org/docs/api/web-contents#contentsinsertcsscss-options
|
||||
/// Works for both BrowserWindows and BrowserViews.
|
||||
/// </summary>
|
||||
/// <param name="isBrowserWindow">Whether the webContents belong to a BrowserWindow or not (the other option is a BrowserView)</param>
|
||||
/// <param name="path">Absolute path to the CSS file location</param>
|
||||
public void InsertCSS(bool isBrowserWindow, string path)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("webContents-insertCSS", Id, isBrowserWindow, path);
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
using ElectronNET.API.Serialization;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
public class OnBeforeRequestDetails
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Url { get; set; }
|
||||
public string Method { get; set; }
|
||||
|
||||
public int? WebContentsId { get; set; }
|
||||
// Ensure all necessary properties are included as per Electron documentation
|
||||
}
|
||||
|
||||
public class WebRequestFilter
|
||||
{
|
||||
public string[] Urls { get; set; }
|
||||
}
|
||||
|
||||
public class WebRequest
|
||||
{
|
||||
public int Id { get; private set; }
|
||||
|
||||
internal WebRequest(int id)
|
||||
{
|
||||
Id = id;
|
||||
}
|
||||
|
||||
private event Action<OnBeforeRequestDetails, Action<object>> _onBeforeRequest;
|
||||
|
||||
public void OnBeforeRequest(WebRequestFilter filter, Action<OnBeforeRequestDetails, Action<object>> listener)
|
||||
{
|
||||
if (_onBeforeRequest == null)
|
||||
{
|
||||
BridgeConnector.Socket.On<JsonElement>($"webContents-session-webRequest-onBeforeRequest{Id}",
|
||||
(args) =>
|
||||
{
|
||||
//// var details0 = args[0].Deserialize<OnBeforeRequestDetails>(ElectronNET.ElectronJson.Options);
|
||||
var details = args.Deserialize<OnBeforeRequestDetails>(ElectronJson.Options);
|
||||
var callback = (Action<object>)((response) => { BridgeConnector.Socket.Emit($"webContents-session-webRequest-onBeforeRequest-response{Id}", response); });
|
||||
|
||||
_onBeforeRequest?.Invoke(details, callback);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-webContents-session-webRequest-onBeforeRequest", Id, filter);
|
||||
}
|
||||
|
||||
_onBeforeRequest += listener;
|
||||
}
|
||||
|
||||
public void RemoveListener(Action<OnBeforeRequestDetails, Action<object>> listener)
|
||||
{
|
||||
_onBeforeRequest -= listener;
|
||||
if (_onBeforeRequest == null)
|
||||
{
|
||||
BridgeConnector.Socket.Off($"webContents-session-webRequest-onBeforeRequest{Id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
## Class: WebRequest
|
||||
|
||||
> Intercept and modify the contents of a request at various stages of its lifetime.
|
||||
|
||||
Process: [Main](../glossary.md#main-process)<br />
|
||||
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
|
||||
|
||||
Instances of the `WebRequest` class are accessed by using the `webRequest`
|
||||
property of a `Session`.
|
||||
|
||||
The methods of `WebRequest` accept an optional `filter` and a `listener`. The
|
||||
`listener` will be called with `listener(details)` when the API's event has
|
||||
happened. The `details` object describes the request.
|
||||
|
||||
⚠️ Only the last attached `listener` will be used. Passing `null` as `listener` will unsubscribe from the event.
|
||||
|
||||
The `filter` object has a `urls` property which is an Array of URL
|
||||
patterns that will be used to filter out the requests that do not match the URL
|
||||
patterns. If the `filter` is omitted then all requests will be matched.
|
||||
|
||||
For certain events the `listener` is passed with a `callback`, which should be
|
||||
called with a `response` object when `listener` has done its work.
|
||||
|
||||
An example of adding `User-Agent` header for requests:
|
||||
|
||||
```js
|
||||
const { session } = require('electron')
|
||||
|
||||
// Modify the user agent for all requests to the following urls.
|
||||
const filter = {
|
||||
urls: ['https://*.github.com/*', '*://electron.github.io/*']
|
||||
}
|
||||
|
||||
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
|
||||
details.requestHeaders['User-Agent'] = 'MyAgent'
|
||||
callback({ requestHeaders: details.requestHeaders })
|
||||
})
|
||||
```
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The following methods are available on instances of `WebRequest`:
|
||||
|
||||
#### `webRequest.onBeforeRequest([filter, ]listener)`
|
||||
|
||||
* `filter` [WebRequestFilter](structures/web-request-filter.md) (optional)
|
||||
* `listener` Function | null
|
||||
* `details` Object
|
||||
* `id` Integer
|
||||
* `url` string
|
||||
* `method` string
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `referrer` string
|
||||
* `timestamp` Double
|
||||
* `uploadData` [UploadData[]](structures/upload-data.md)
|
||||
* `callback` Function
|
||||
* `response` Object
|
||||
* `cancel` boolean (optional)
|
||||
* `redirectURL` string (optional) - The original request is prevented from
|
||||
being sent or completed and is instead redirected to the given URL.
|
||||
|
||||
The `listener` will be called with `listener(details, callback)` when a request
|
||||
is about to occur.
|
||||
|
||||
The `uploadData` is an array of `UploadData` objects.
|
||||
|
||||
The `callback` has to be called with an `response` object.
|
||||
|
||||
Some examples of valid `urls`:
|
||||
|
||||
```js
|
||||
'http://foo:1234/'
|
||||
'http://foo.com/'
|
||||
'http://foo:1234/bar'
|
||||
'*://*/*'
|
||||
'*://example.com/*'
|
||||
'*://example.com/foo/*'
|
||||
'http://*.foo:1234/'
|
||||
'file://foo:1234/bar'
|
||||
'http://foo:*/'
|
||||
'*://www.foo.com/'
|
||||
```
|
||||
|
||||
#### `webRequest.onBeforeSendHeaders([filter, ]listener)`
|
||||
|
||||
* `filter` [WebRequestFilter](structures/web-request-filter.md) (optional)
|
||||
* `listener` Function | null
|
||||
* `details` Object
|
||||
* `id` Integer
|
||||
* `url` string
|
||||
* `method` string
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `referrer` string
|
||||
* `timestamp` Double
|
||||
* `uploadData` [UploadData[]](structures/upload-data.md) (optional)
|
||||
* `requestHeaders` Record<string, string>
|
||||
* `callback` Function
|
||||
* `beforeSendResponse` Object
|
||||
* `cancel` boolean (optional)
|
||||
* `requestHeaders` Record<string, string | string[]> (optional) - When provided, request will be made
|
||||
with these headers.
|
||||
|
||||
The `listener` will be called with `listener(details, callback)` before sending
|
||||
an HTTP request, once the request headers are available. This may occur after a
|
||||
TCP connection is made to the server, but before any http data is sent.
|
||||
|
||||
The `callback` has to be called with a `response` object.
|
||||
|
||||
#### `webRequest.onSendHeaders([filter, ]listener)`
|
||||
|
||||
* `filter` [WebRequestFilter](structures/web-request-filter.md) (optional)
|
||||
* `listener` Function | null
|
||||
* `details` Object
|
||||
* `id` Integer
|
||||
* `url` string
|
||||
* `method` string
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `referrer` string
|
||||
* `timestamp` Double
|
||||
* `requestHeaders` Record<string, string>
|
||||
|
||||
The `listener` will be called with `listener(details)` just before a request is
|
||||
going to be sent to the server, modifications of previous `onBeforeSendHeaders`
|
||||
response are visible by the time this listener is fired.
|
||||
|
||||
#### `webRequest.onHeadersReceived([filter, ]listener)`
|
||||
|
||||
* `filter` [WebRequestFilter](structures/web-request-filter.md) (optional)
|
||||
* `listener` Function | null
|
||||
* `details` Object
|
||||
* `id` Integer
|
||||
* `url` string
|
||||
* `method` string
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `referrer` string
|
||||
* `timestamp` Double
|
||||
* `statusLine` string
|
||||
* `statusCode` Integer
|
||||
* `responseHeaders` Record<string, string[]> (optional)
|
||||
* `callback` Function
|
||||
* `headersReceivedResponse` Object
|
||||
* `cancel` boolean (optional)
|
||||
* `responseHeaders` Record<string, string | string[]> (optional) - When provided, the server is assumed
|
||||
to have responded with these headers.
|
||||
* `statusLine` string (optional) - Should be provided when overriding
|
||||
`responseHeaders` to change header status otherwise original response
|
||||
header's status will be used.
|
||||
|
||||
The `listener` will be called with `listener(details, callback)` when HTTP
|
||||
response headers of a request have been received.
|
||||
|
||||
The `callback` has to be called with a `response` object.
|
||||
|
||||
#### `webRequest.onResponseStarted([filter, ]listener)`
|
||||
|
||||
* `filter` [WebRequestFilter](structures/web-request-filter.md) (optional)
|
||||
* `listener` Function | null
|
||||
* `details` Object
|
||||
* `id` Integer
|
||||
* `url` string
|
||||
* `method` string
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `referrer` string
|
||||
* `timestamp` Double
|
||||
* `responseHeaders` Record<string, string[]> (optional)
|
||||
* `fromCache` boolean - Indicates whether the response was fetched from disk
|
||||
cache.
|
||||
* `statusCode` Integer
|
||||
* `statusLine` string
|
||||
|
||||
The `listener` will be called with `listener(details)` when first byte of the
|
||||
response body is received. For HTTP requests, this means that the status line
|
||||
and response headers are available.
|
||||
|
||||
#### `webRequest.onBeforeRedirect([filter, ]listener)`
|
||||
|
||||
* `filter` [WebRequestFilter](structures/web-request-filter.md) (optional)
|
||||
* `listener` Function | null
|
||||
* `details` Object
|
||||
* `id` Integer
|
||||
* `url` string
|
||||
* `method` string
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `referrer` string
|
||||
* `timestamp` Double
|
||||
* `redirectURL` string
|
||||
* `statusCode` Integer
|
||||
* `statusLine` string
|
||||
* `ip` string (optional) - The server IP address that the request was
|
||||
actually sent to.
|
||||
* `fromCache` boolean
|
||||
* `responseHeaders` Record<string, string[]> (optional)
|
||||
|
||||
The `listener` will be called with `listener(details)` when a server initiated
|
||||
redirect is about to occur.
|
||||
|
||||
#### `webRequest.onCompleted([filter, ]listener)`
|
||||
|
||||
* `filter` [WebRequestFilter](structures/web-request-filter.md) (optional)
|
||||
* `listener` Function | null
|
||||
* `details` Object
|
||||
* `id` Integer
|
||||
* `url` string
|
||||
* `method` string
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `referrer` string
|
||||
* `timestamp` Double
|
||||
* `responseHeaders` Record<string, string[]> (optional)
|
||||
* `fromCache` boolean
|
||||
* `statusCode` Integer
|
||||
* `statusLine` string
|
||||
* `error` string
|
||||
|
||||
The `listener` will be called with `listener(details)` when a request is
|
||||
completed.
|
||||
|
||||
#### `webRequest.onErrorOccurred([filter, ]listener)`
|
||||
|
||||
* `filter` [WebRequestFilter](structures/web-request-filter.md) (optional)
|
||||
* `listener` Function | null
|
||||
* `details` Object
|
||||
* `id` Integer
|
||||
* `url` string
|
||||
* `method` string
|
||||
* `webContentsId` Integer (optional)
|
||||
* `webContents` WebContents (optional)
|
||||
* `frame` WebFrameMain (optional)
|
||||
* `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`.
|
||||
* `referrer` string
|
||||
* `timestamp` Double
|
||||
* `fromCache` boolean
|
||||
* `error` string - The error description.
|
||||
|
||||
The `listener` will be called with `listener(details)` when an error occurs.
|
||||
File diff suppressed because it is too large
Load Diff
639
src/ElectronNET.API/AutoUpdater.cs
Normal file
639
src/ElectronNET.API/AutoUpdater.cs
Normal file
@@ -0,0 +1,639 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Enable apps to automatically update themselves. Based on electron-updater.
|
||||
/// </summary>
|
||||
public sealed class AutoUpdater
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether to automatically download an update when it is found. (Default is true)
|
||||
/// </summary>
|
||||
public bool AutoDownload
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run<bool>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdater-autoDownload-get-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-autoDownload-get-reply");
|
||||
taskCompletionSource.SetResult((bool)result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-autoDownload-get").FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-autoDownload-set", value).FireAndForget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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<bool>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdater-autoInstallOnAppQuit-get-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-autoInstallOnAppQuit-get-reply");
|
||||
taskCompletionSource.SetResult((bool)result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-autoInstallOnAppQuit-get").FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-autoInstallOnAppQuit-set", value).FireAndForget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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<bool>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdater-allowPrerelease-get-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-allowPrerelease-get-reply");
|
||||
taskCompletionSource.SetResult((bool)result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-allowPrerelease-get").FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-allowPrerelease-set", value).FireAndForget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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<bool>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdater-fullChangelog-get-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-fullChangelog-get-reply");
|
||||
taskCompletionSource.SetResult((bool)result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-fullChangelog-get").FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-fullChangelog-set", value).FireAndForget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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<bool>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdater-allowDowngrade-get-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-allowDowngrade-get-reply");
|
||||
taskCompletionSource.SetResult((bool)result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-allowDowngrade-get").FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-allowDowngrade-set", value).FireAndForget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For test only.
|
||||
/// </summary>
|
||||
public string UpdateConfigPath
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run<string>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdater-updateConfigPath-get-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-updateConfigPath-get-reply");
|
||||
taskCompletionSource.SetResult(result.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-updateConfigPath-get").FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}).Result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The current application version
|
||||
/// </summary>
|
||||
public Task<SemVer> CurrentVersionAsync
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run<SemVer>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<SemVer>();
|
||||
BridgeConnector.Socket.On("autoUpdater-currentVersion-get-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-currentVersion-get-reply");
|
||||
SemVer version = ((JObject)result).ToObject<SemVer>();
|
||||
taskCompletionSource.SetResult(version);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-currentVersion-get").FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the update channel. Not applicable for GitHub.
|
||||
/// Doesn’t 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.
|
||||
/// Doesn’t return channel from the update configuration, only if was previously set.
|
||||
/// </summary>
|
||||
public Task<string> ChannelAsync
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run<string>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdater-channel-get-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-channel-get-reply");
|
||||
taskCompletionSource.SetResult(result.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-channel-get").FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// The request headers.
|
||||
/// </summary>
|
||||
public Task<Dictionary<string, string>> RequestHeadersAsync
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<Dictionary<string, string>>();
|
||||
BridgeConnector.Socket.On("autoUpdater-requestHeaders-get-reply", (headers) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-requestHeaders-get-reply");
|
||||
Dictionary<string, string> result = ((JObject)headers).ToObject<Dictionary<string, string>>();
|
||||
taskCompletionSource.SetResult(result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdater-requestHeaders-get").FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The request headers.
|
||||
/// </summary>
|
||||
public Dictionary<string, string> RequestHeaders
|
||||
{
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-requestHeaders-set", JObject.FromObject(value, _jsonSerializer)).FireAndForget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when there is an error while updating.
|
||||
/// </summary>
|
||||
public event Action<string> OnError
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_error == null)
|
||||
{
|
||||
BridgeConnector.Socket.On("autoUpdater-error" + GetHashCode(), (message) =>
|
||||
{
|
||||
_error(message.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-autoUpdater-error-event", GetHashCode()).FireAndForget();
|
||||
}
|
||||
_error += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_error -= value;
|
||||
|
||||
if (_error == null)
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-error" + GetHashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private event Action<string> _error;
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when checking if an update has started.
|
||||
/// </summary>
|
||||
public event Action OnCheckingForUpdate
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_checkingForUpdate == null)
|
||||
{
|
||||
BridgeConnector.Socket.On("autoUpdater-checking-for-update" + GetHashCode(), () =>
|
||||
{
|
||||
_checkingForUpdate();
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-autoUpdater-checking-for-update-event", GetHashCode()).FireAndForget();
|
||||
}
|
||||
_checkingForUpdate += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_checkingForUpdate -= value;
|
||||
|
||||
if (_checkingForUpdate == null)
|
||||
BridgeConnector.Socket.Off("autoUpdater-checking-for-update" + GetHashCode());
|
||||
}
|
||||
}
|
||||
|
||||
private event Action _checkingForUpdate;
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when there is an available update.
|
||||
/// The update is downloaded automatically if AutoDownload is true.
|
||||
/// </summary>
|
||||
public event Action<UpdateInfo> OnUpdateAvailable
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_updateAvailable == null)
|
||||
{
|
||||
BridgeConnector.Socket.On("autoUpdater-update-available" + GetHashCode(), (updateInfo) =>
|
||||
{
|
||||
_updateAvailable(JObject.Parse(updateInfo.ToString()).ToObject<UpdateInfo>());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-autoUpdater-update-available-event", GetHashCode()).FireAndForget();
|
||||
}
|
||||
_updateAvailable += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_updateAvailable -= value;
|
||||
|
||||
if (_updateAvailable == null)
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-update-available" + GetHashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private event Action<UpdateInfo> _updateAvailable;
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when there is no available update.
|
||||
/// </summary>
|
||||
public event Action<UpdateInfo> OnUpdateNotAvailable
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_updateNotAvailable == null)
|
||||
{
|
||||
BridgeConnector.Socket.On("autoUpdater-update-not-available" + GetHashCode(), (updateInfo) =>
|
||||
{
|
||||
_updateNotAvailable(JObject.Parse(updateInfo.ToString()).ToObject<UpdateInfo>());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-autoUpdater-update-not-available-event", GetHashCode()).FireAndForget();
|
||||
}
|
||||
_updateNotAvailable += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_updateNotAvailable -= value;
|
||||
|
||||
if (_updateNotAvailable == null)
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-update-not-available" + GetHashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private event Action<UpdateInfo> _updateNotAvailable;
|
||||
|
||||
/// <summary>
|
||||
/// Emitted on download progress.
|
||||
/// </summary>
|
||||
public event Action<ProgressInfo> OnDownloadProgress
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_downloadProgress == null)
|
||||
{
|
||||
BridgeConnector.Socket.On("autoUpdater-download-progress" + GetHashCode(), (progressInfo) =>
|
||||
{
|
||||
_downloadProgress(JObject.Parse(progressInfo.ToString()).ToObject<ProgressInfo>());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-autoUpdater-download-progress-event", GetHashCode()).FireAndForget();
|
||||
}
|
||||
_downloadProgress += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_downloadProgress -= value;
|
||||
|
||||
if (_downloadProgress == null)
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-download-progress" + GetHashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private event Action<ProgressInfo> _downloadProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Emitted on download complete.
|
||||
/// </summary>
|
||||
public event Action<UpdateInfo> OnUpdateDownloaded
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_updateDownloaded == null)
|
||||
{
|
||||
BridgeConnector.Socket.On("autoUpdater-update-downloaded" + GetHashCode(), (updateInfo) =>
|
||||
{
|
||||
_updateDownloaded(JObject.Parse(updateInfo.ToString()).ToObject<UpdateInfo>());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-autoUpdater-update-downloaded-event", GetHashCode()).FireAndForget();
|
||||
}
|
||||
_updateDownloaded += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_updateDownloaded -= value;
|
||||
|
||||
if (_updateDownloaded == null)
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdater-update-downloaded" + GetHashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private event Action<UpdateInfo> _updateDownloaded;
|
||||
|
||||
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.On("autoUpdaterCheckForUpdatesComplete" + guid, (updateCheckResult) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesComplete" + guid);
|
||||
BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesError" + guid);
|
||||
taskCompletionSource.SetResult(JObject.Parse(updateCheckResult.ToString()).ToObject<UpdateCheckResult>());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
taskCompletionSource.SetException(ex);
|
||||
}
|
||||
});
|
||||
BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesError" + guid, (error) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesComplete" + guid);
|
||||
BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesError" + guid);
|
||||
var message = "An error occurred in CheckForUpdatesAsync";
|
||||
|
||||
if (error != null && !string.IsNullOrEmpty(error.ToString()))
|
||||
{
|
||||
message = JsonConvert.SerializeObject(error);
|
||||
}
|
||||
|
||||
taskCompletionSource.SetException(new Exception(message));
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdaterCheckForUpdates", guid).FireAndForget();
|
||||
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.On("autoUpdaterCheckForUpdatesAndNotifyComplete" + guid, (updateCheckResult) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesAndNotifyComplete" + guid);
|
||||
BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesAndNotifyError" + guid);
|
||||
|
||||
if (updateCheckResult == null)
|
||||
{
|
||||
taskCompletionSource.SetResult(null);
|
||||
}
|
||||
else
|
||||
{
|
||||
taskCompletionSource.SetResult(JObject.Parse(updateCheckResult.ToString()).ToObject<UpdateCheckResult>());
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
taskCompletionSource.SetException(ex);
|
||||
}
|
||||
});
|
||||
BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesAndNotifyError" + guid, (error) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesAndNotifyComplete" + guid);
|
||||
BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesAndNotifyError" + guid);
|
||||
var message = "An error occurred in autoUpdaterCheckForUpdatesAndNotify";
|
||||
|
||||
if (error != null)
|
||||
{
|
||||
message = JsonConvert.SerializeObject(error);
|
||||
}
|
||||
|
||||
taskCompletionSource.SetException(new Exception(message));
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdaterCheckForUpdatesAndNotify", guid).FireAndForget();
|
||||
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("autoUpdaterQuitAndInstall", isSilent, isForceRunAfter).FireAndForget();
|
||||
}
|
||||
|
||||
/// <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 taskCompletionSource = new TaskCompletionSource<string>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdaterDownloadUpdateComplete" + guid, (downloadedPath) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdaterDownloadUpdateComplete" + guid);
|
||||
taskCompletionSource.SetResult(downloadedPath.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdaterDownloadUpdate", guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Feed URL.
|
||||
/// </summary>
|
||||
/// <returns>Feed URL.</returns>
|
||||
public Task<string> GetFeedURLAsync()
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("autoUpdaterGetFeedURLComplete" + guid, (downloadedPath) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("autoUpdaterGetFeedURLComplete" + guid);
|
||||
taskCompletionSource.SetResult(downloadedPath.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("autoUpdaterGetFeedURL", guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
private readonly JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma warning disable IDE0130 // Namespace does not match folder structure
|
||||
// ReSharper disable once CheckNamespace
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
internal static class BridgeConnector
|
||||
{
|
||||
public static SocketIoFacade Socket
|
||||
{
|
||||
get
|
||||
{
|
||||
return ElectronNetRuntime.GetSocket();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
#pragma warning disable IDE0130 // Namespace does not match folder structure
|
||||
// ReSharper disable once CheckNamespace
|
||||
namespace ElectronNET.API;
|
||||
|
||||
using ElectronNET.API.Serialization;
|
||||
using SocketIO.Serializer.SystemTextJson;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using SocketIO = SocketIOClient.SocketIO;
|
||||
|
||||
internal class SocketIoFacade
|
||||
{
|
||||
private readonly SocketIO _socket;
|
||||
private readonly object _lockObj = new object();
|
||||
|
||||
public SocketIoFacade(string uri)
|
||||
{
|
||||
_socket = new SocketIO(uri);
|
||||
_socket.Serializer = new SystemTextJsonSerializer(ElectronJson.Options);
|
||||
// Use default System.Text.Json serializer from SocketIOClient.
|
||||
// Outgoing args are normalized to camelCase via SerializeArg in Emit.
|
||||
}
|
||||
|
||||
public event EventHandler BridgeDisconnected;
|
||||
|
||||
public event EventHandler BridgeConnected;
|
||||
|
||||
public void Connect()
|
||||
{
|
||||
_socket.OnError += (sender, e) => { Console.WriteLine($"BridgeConnector Error: {sender} {e}"); };
|
||||
|
||||
_socket.OnConnected += (_, _) =>
|
||||
{
|
||||
Console.WriteLine("BridgeConnector connected!");
|
||||
this.BridgeConnected?.Invoke(this, EventArgs.Empty);
|
||||
};
|
||||
|
||||
_socket.OnDisconnected += (_, _) =>
|
||||
{
|
||||
Console.WriteLine("BridgeConnector disconnected!");
|
||||
this.BridgeDisconnected?.Invoke(this, EventArgs.Empty);
|
||||
};
|
||||
|
||||
_socket.ConnectAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public void On(string eventName, Action action)
|
||||
{
|
||||
lock (_lockObj)
|
||||
{
|
||||
_socket.On(eventName, _ => { Task.Run(action); });
|
||||
}
|
||||
}
|
||||
|
||||
public void On<T>(string eventName, Action<T> action)
|
||||
{
|
||||
lock (_lockObj)
|
||||
{
|
||||
_socket.On(eventName, response =>
|
||||
{
|
||||
var value = response.GetValue<T>();
|
||||
Task.Run(() => action(value));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Keep object overload for compatibility; value will be a JsonElement boxed as object.
|
||||
public void On(string eventName, Action<object> action)
|
||||
{
|
||||
lock (_lockObj)
|
||||
{
|
||||
_socket.On(eventName, response =>
|
||||
{
|
||||
var value = (object)response.GetValue<JsonElement>();
|
||||
////Console.WriteLine($"Called Event {eventName} - data {value}");
|
||||
Task.Run(() => action(value));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void Once(string eventName, Action action)
|
||||
{
|
||||
lock (_lockObj)
|
||||
{
|
||||
_socket.On(eventName, _ =>
|
||||
{
|
||||
this.Off(eventName);
|
||||
Task.Run(action);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void Once<T>(string eventName, Action<T> action)
|
||||
{
|
||||
lock (_lockObj)
|
||||
{
|
||||
_socket.On(eventName, (socketIoResponse) =>
|
||||
{
|
||||
this.Off(eventName);
|
||||
Task.Run(() => action(socketIoResponse.GetValue<T>()));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void Off(string eventName)
|
||||
{
|
||||
lock (_lockObj)
|
||||
{
|
||||
_socket.Off(eventName);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Emit(string eventName, params object[] args)
|
||||
{
|
||||
await _socket.EmitAsync(eventName, args).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void DisposeSocket()
|
||||
{
|
||||
_socket.Dispose();
|
||||
}
|
||||
}
|
||||
33
src/ElectronNET.API/BridgeConnector.cs
Normal file
33
src/ElectronNET.API/BridgeConnector.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
internal static class BridgeConnector
|
||||
{
|
||||
private static SocketIoFacade _socket;
|
||||
private static readonly object SyncRoot = new();
|
||||
|
||||
public static SocketIoFacade Socket
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_socket == null)
|
||||
{
|
||||
lock (SyncRoot)
|
||||
{
|
||||
if (_socket == null)
|
||||
{
|
||||
|
||||
string socketUrl = HybridSupport.IsElectronActive
|
||||
? $"http://localhost:{BridgeSettings.SocketPort}"
|
||||
: "http://localhost";
|
||||
|
||||
_socket = new SocketIoFacade(socketUrl);
|
||||
_socket.Connect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _socket;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
24
src/ElectronNET.API/BridgeSettings.cs
Normal file
24
src/ElectronNET.API/BridgeSettings.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static class BridgeSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the socket port.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The socket port.
|
||||
/// </value>
|
||||
public static string SocketPort { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the web port.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The web port.
|
||||
/// </value>
|
||||
public static string WebPort { get; internal set; }
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,25 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
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: ApiBase
|
||||
public class BrowserView
|
||||
{
|
||||
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
|
||||
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
|
||||
/// <summary>
|
||||
/// Gets the identifier.
|
||||
/// </summary>
|
||||
public override int Id { get; protected set; }
|
||||
/// <value>
|
||||
/// The identifier.
|
||||
/// </value>
|
||||
public int Id { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Render and control web pages.
|
||||
@@ -24,24 +28,38 @@ 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(() => GetPropertyAsync<Rectangle>()).Result;
|
||||
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).FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("browserView-bounds-set", Id, value);
|
||||
BridgeConnector.Socket.Emit("browserView-setBounds", Id, JObject.FromObject(value, _jsonSerializer)).FireAndForget();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// BrowserView
|
||||
/// </summary>
|
||||
internal BrowserView(int id)
|
||||
internal BrowserView(int id)
|
||||
{
|
||||
Id = id;
|
||||
|
||||
@@ -56,18 +74,24 @@ namespace ElectronNET.API
|
||||
/// <param name="options"></param>
|
||||
public void SetAutoResize(AutoResizeOptions options)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("browserView-setAutoResize", Id, options);
|
||||
BridgeConnector.Socket.Emit("browserView-setAutoResize", Id, JObject.FromObject(options, _jsonSerializer)).FireAndForget();
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public void SetBackgroundColor(string color)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("browserView-setBackgroundColor", Id, color);
|
||||
BridgeConnector.Socket.Emit("browserView-setBackgroundColor", Id, color).FireAndForget();
|
||||
}
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
2312
src/ElectronNET.API/BrowserWindow.cs
Normal file
2312
src/ElectronNET.API/BrowserWindow.cs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,25 +1,20 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Serialization;
|
||||
using System.Text.Json;
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
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: ApiBase
|
||||
public sealed class Clipboard
|
||||
{
|
||||
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
|
||||
{
|
||||
@@ -45,7 +40,21 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns>The content in the clipboard as plain text.</returns>
|
||||
public Task<string> ReadTextAsync(string type = "") => GetPropertyAsync<string>(type);
|
||||
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).FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the text into the clipboard as plain text.
|
||||
@@ -54,7 +63,7 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void WriteText(string text, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeText", text, type);
|
||||
BridgeConnector.Socket.Emit("clipboard-writeText", text, type).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -62,7 +71,21 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public Task<string> ReadHTMLAsync(string type = "") => GetPropertyAsync<string>(type);
|
||||
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).FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes markup to the clipboard.
|
||||
@@ -71,7 +94,7 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void WriteHTML(string markup, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeHTML", markup, type);
|
||||
BridgeConnector.Socket.Emit("clipboard-writeHTML", markup, type).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -79,7 +102,21 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public Task<string> ReadRTFAsync(string type = "") => GetPropertyAsync<string>(type);
|
||||
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).FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the text into the clipboard in RTF.
|
||||
@@ -88,7 +125,7 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void WriteRTF(string text, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeRTF", text, type);
|
||||
BridgeConnector.Socket.Emit("clipboard-writeHTML", text, type).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -97,7 +134,21 @@ namespace ElectronNET.API
|
||||
/// be empty strings when the bookmark is unavailable.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Task<ReadBookmark> ReadBookmarkAsync() => GetPropertyAsync<ReadBookmark>();
|
||||
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").FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the title and url into the clipboard as a bookmark.
|
||||
@@ -111,7 +162,7 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void WriteBookmark(string title, string url, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeBookmark", title, url, type);
|
||||
BridgeConnector.Socket.Emit("clipboard-writeBookmark", title, url, type).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -120,7 +171,21 @@ namespace ElectronNET.API
|
||||
/// find pasteboard whenever the application is activated.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Task<string> ReadFindTextAsync() => GetPropertyAsync<string>();
|
||||
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").FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// macOS: Writes the text into the find pasteboard as plain text. This method uses
|
||||
@@ -129,7 +194,7 @@ namespace ElectronNET.API
|
||||
/// <param name="text"></param>
|
||||
public void WriteFindText(string text)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeFindText", text);
|
||||
BridgeConnector.Socket.Emit("clipboard-writeFindText", text).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -138,7 +203,7 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void Clear(string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-clear", type);
|
||||
BridgeConnector.Socket.Emit("clipboard-clear", type).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -146,7 +211,21 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public Task<string[]> AvailableFormatsAsync(string type = "") => GetPropertyAsync<string[]>(type);
|
||||
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).FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes data to the clipboard.
|
||||
@@ -155,7 +234,7 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void Write(Data data, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-write", data, type);
|
||||
BridgeConnector.Socket.Emit("clipboard-write", JObject.FromObject(data, _jsonSerializer), type).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -163,8 +242,25 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public Task<NativeImage> ReadImageAsync(string type = "") => GetPropertyAsync<NativeImage>(type);
|
||||
public Task<NativeImage> ReadImageAsync(string type = "")
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<NativeImage>();
|
||||
|
||||
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).FireAndForget();
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an image to the clipboard.
|
||||
/// </summary>
|
||||
@@ -172,7 +268,14 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void WriteImage(NativeImage image, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeImage", JsonSerializer.Serialize(image, ElectronJson.Options), type);
|
||||
BridgeConnector.Socket.Emit("clipboard-writeImage", JsonConvert.SerializeObject(image), type).FireAndForget();
|
||||
}
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,7 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
public sealed class CommandLine
|
||||
{
|
||||
internal CommandLine()
|
||||
{
|
||||
}
|
||||
internal CommandLine() { }
|
||||
|
||||
internal static CommandLine Instance
|
||||
{
|
||||
@@ -45,7 +43,7 @@ namespace ElectronNET.API
|
||||
/// </remarks>
|
||||
public void AppendSwitch(string the_switch, string value = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("appCommandLineAppendSwitch", the_switch, value);
|
||||
BridgeConnector.Socket.Emit("appCommandLineAppendSwitch", the_switch, value).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -59,7 +57,7 @@ namespace ElectronNET.API
|
||||
/// </remarks>
|
||||
public void AppendArgument(string value)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("appCommandLineAppendArgument", value);
|
||||
BridgeConnector.Socket.Emit("appCommandLineAppendArgument", value).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -68,17 +66,21 @@ 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)
|
||||
public async Task<bool> HasSwitchAsync(string switchName, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.Once<bool>("appCommandLineHasSwitchCompleted", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("appCommandLineHasSwitch", switchName);
|
||||
BridgeConnector.Socket.On("appCommandLineHasSwitchCompleted", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("appCommandLineHasSwitchCompleted");
|
||||
taskCompletionSource.SetResult((bool)result);
|
||||
});
|
||||
|
||||
return await tcs.Task.ConfigureAwait(false);
|
||||
BridgeConnector.Socket.Emit("appCommandLineHasSwitch", switchName).FireAndForget();
|
||||
return await taskCompletionSource.Task.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,18 +93,22 @@ 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)
|
||||
public async Task<string> GetSwitchValueAsync(string switchName, CancellationToken cancellationToken = default(CancellationToken))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
|
||||
var tcs = new TaskCompletionSource<string>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.Once<string>("appCommandLineGetSwitchValueCompleted", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("appCommandLineGetSwitchValue", switchName);
|
||||
BridgeConnector.Socket.On("appCommandLineGetSwitchValueCompleted", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("appCommandLineGetSwitchValueCompleted");
|
||||
taskCompletionSource.SetResult((string)result);
|
||||
});
|
||||
|
||||
return await tcs.Task.ConfigureAwait(false);
|
||||
BridgeConnector.Socket.Emit("appCommandLineGetSwitchValue", switchName).FireAndForget();
|
||||
return await taskCompletionSource.Task.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using System;
|
||||
using ElectronNET.Runtime.Data;
|
||||
using ElectronNET.Runtime.Services;
|
||||
|
||||
namespace ElectronNET.Common
|
||||
{
|
||||
internal static class Extensions
|
||||
{
|
||||
public static bool IsUnpackaged(this StartupMethod method)
|
||||
{
|
||||
switch (method)
|
||||
{
|
||||
case StartupMethod.UnpackedElectronFirst:
|
||||
case StartupMethod.UnpackedDotnetFirst:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static string LowerFirst(this string str)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(str))
|
||||
{
|
||||
return str;
|
||||
}
|
||||
|
||||
if (str.Length == 1)
|
||||
{
|
||||
return str.ToLower();
|
||||
}
|
||||
|
||||
return char.ToLower(str[0]) + str.Substring(1);
|
||||
}
|
||||
|
||||
public static string StripAsync(this string str)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(str))
|
||||
{
|
||||
return str;
|
||||
}
|
||||
|
||||
var pos = str.LastIndexOf("Async", StringComparison.Ordinal);
|
||||
|
||||
if (pos > 0)
|
||||
{
|
||||
return str.Substring(0, pos);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
public static string StripOn(this string str)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(str) || !str.StartsWith("On", StringComparison.Ordinal))
|
||||
{
|
||||
return str;
|
||||
}
|
||||
|
||||
return str.Substring(2);
|
||||
}
|
||||
|
||||
public static string ToDashedEventName(this string str)
|
||||
{
|
||||
return string.Join("-", Regex.Split(str.StripOn(), "(?<!^)(?=[A-Z])")).ToLower(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
public static string ToCamelCaseEventName(this string str)
|
||||
{
|
||||
return str.StripOn().LowerFirst();
|
||||
}
|
||||
|
||||
public static bool IsReady(this LifetimeServiceBase service)
|
||||
{
|
||||
return service != null && service.State == LifetimeState.Ready;
|
||||
}
|
||||
|
||||
public static bool IsNotStopped(this LifetimeServiceBase service)
|
||||
{
|
||||
return service != null && service.State != LifetimeState.Stopped;
|
||||
}
|
||||
|
||||
public static bool IsNullOrStopped(this LifetimeServiceBase service)
|
||||
{
|
||||
return service == null || service.State == LifetimeState.Stopped;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,595 +0,0 @@
|
||||
namespace ElectronNET.Common
|
||||
{
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Class encapsulating out-of-process execution of console applications.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Why this class?
|
||||
/// Probably everybody who has tried to use System.Diagnotics.Process cross-platform and with reading
|
||||
/// stderr and stdout will know that it is a pretty quirky API.
|
||||
/// The code below may look weird, even non-sensical, but it works 100% reliable with all .net frameworks
|
||||
/// and .net versions and on every platform where .net runs. This is just the innermost core, that's why
|
||||
/// there are many dead ends, but it has all the crucial parts.
|
||||
/// </remarks>
|
||||
/// <seealso cref="IDisposable" />
|
||||
[SuppressMessage("ReSharper", "SuspiciousLockOverSynchronizationPrimitive")]
|
||||
public class ProcessRunner : IDisposable
|
||||
{
|
||||
private volatile Process process;
|
||||
private readonly StringBuilder stdOut = new StringBuilder(4 * 1024);
|
||||
private readonly StringBuilder stdErr = new StringBuilder(4 * 1024);
|
||||
|
||||
private volatile ManualResetEvent stdOutEvent;
|
||||
private volatile ManualResetEvent stdErrEvent;
|
||||
private volatile Stopwatch stopwatch;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="ProcessRunner" /> class.</summary>
|
||||
/// <param name="name">A name identifying the process to execute.</param>
|
||||
public ProcessRunner(string name)
|
||||
{
|
||||
this.Name = name;
|
||||
}
|
||||
|
||||
public event EventHandler<EventArgs> ProcessExited;
|
||||
|
||||
public bool IsDisposed { get; private set; }
|
||||
|
||||
private Process Process
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.process;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get
|
||||
{
|
||||
var proc = this.process;
|
||||
if (proc != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return !proc.HasExited;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gets the name identifying the process.</summary>
|
||||
/// <value>The name.</value>
|
||||
public string Name { get; }
|
||||
|
||||
public string CommandLine { get; private set; }
|
||||
|
||||
public string ExecutableFileName { get; private set; }
|
||||
|
||||
public string WorkingFolder { get; private set; }
|
||||
|
||||
public bool RecordStandardOutput { get; set; }
|
||||
|
||||
public bool RecordStandardError { get; set; }
|
||||
|
||||
public string StandardOutput
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (this.stdOut)
|
||||
{
|
||||
return this.stdOut.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string StandardError
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (this.stdErr)
|
||||
{
|
||||
return this.stdErr.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int? LastExitCode { get; private set; }
|
||||
|
||||
public bool Run(string exeFileName, string commandLineArgs, string workingDirectory)
|
||||
{
|
||||
this.CommandLine = commandLineArgs;
|
||||
this.WorkingFolder = workingDirectory;
|
||||
this.ExecutableFileName = exeFileName;
|
||||
|
||||
var startInfo = new RunnerParams(exeFileName)
|
||||
{
|
||||
Arguments = commandLineArgs,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardInput = true,
|
||||
ErrorDialog = false,
|
||||
CreateNoWindow = true,
|
||||
WorkingDirectory = workingDirectory
|
||||
};
|
||||
|
||||
return this.Run(startInfo);
|
||||
}
|
||||
|
||||
protected bool Run(RunnerParams runnerParams)
|
||||
{
|
||||
if (this.IsDisposed)
|
||||
{
|
||||
throw new ObjectDisposedException(this.GetType().ToString());
|
||||
}
|
||||
|
||||
this.Close();
|
||||
|
||||
this.LastExitCode = null;
|
||||
|
||||
lock (this.stdOut)
|
||||
{
|
||||
this.stdOut.Clear();
|
||||
}
|
||||
|
||||
lock (this.stdErr)
|
||||
{
|
||||
this.stdErr.Clear();
|
||||
}
|
||||
|
||||
this.stdOutEvent = new ManualResetEvent(false);
|
||||
this.stdErrEvent = new ManualResetEvent(false);
|
||||
|
||||
if (!this.OnBeforeStartProcessCore(runnerParams))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var startInfo = new ProcessStartInfo(runnerParams.FileName)
|
||||
{
|
||||
Arguments = runnerParams.Arguments,
|
||||
UseShellExecute = runnerParams.UseShellExecute,
|
||||
RedirectStandardOutput = runnerParams.RedirectStandardOutput,
|
||||
RedirectStandardError = runnerParams.RedirectStandardError,
|
||||
RedirectStandardInput = runnerParams.RedirectStandardInput,
|
||||
ErrorDialog = runnerParams.ErrorDialog,
|
||||
CreateNoWindow = runnerParams.CreateNoWindow,
|
||||
WorkingDirectory = runnerParams.WorkingDirectory
|
||||
};
|
||||
|
||||
foreach (var variableSetting in runnerParams.EnvironmentVariables)
|
||||
{
|
||||
startInfo.EnvironmentVariables[variableSetting.Key] = variableSetting.Value;
|
||||
}
|
||||
|
||||
var proc = new Process { StartInfo = startInfo };
|
||||
|
||||
proc.EnableRaisingEvents = true;
|
||||
|
||||
this.RegisterProcessEvents(proc);
|
||||
|
||||
this.process = proc;
|
||||
|
||||
try
|
||||
{
|
||||
this.process.Start();
|
||||
this.stopwatch = Stopwatch.StartNew();
|
||||
this.process.BeginOutputReadLine();
|
||||
this.process.BeginErrorReadLine();
|
||||
this.process.Refresh();
|
||||
this.OnProcessStartedCore();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.OnProcessErrorCore(ex);
|
||||
this.Close();
|
||||
throw;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<bool> WriteAsync(string data)
|
||||
{
|
||||
var proc = this.Process;
|
||||
if (proc != null && !proc.HasExited)
|
||||
{
|
||||
try
|
||||
{
|
||||
await proc.StandardInput.WriteAsync(data).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("{0}.{1}: {2}", ex, nameof(ProcessRunner), nameof(this.WriteAsync));
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool WaitForExit()
|
||||
{
|
||||
var proc = this.process;
|
||||
|
||||
if (proc == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Wait for process and all I/O to finish.
|
||||
proc.WaitForExit();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.OnProcessErrorCore(ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sychronously waits for the specified amount and ends the process afterwards.</summary>
|
||||
/// <param name="timeoutMs">The timeout ms.</param>
|
||||
/// <remarks>This method allows for a clean exit, since it also waits until the StandardOutput and
|
||||
/// StandardError pipes are processed to the end.</remarks>
|
||||
/// <returns>true, if the process has exited gracefully; false otherwise.</returns>
|
||||
public bool WaitAndKill(int timeoutMs)
|
||||
{
|
||||
var proc = this.process;
|
||||
|
||||
if (proc == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (timeoutMs <= 0)
|
||||
{
|
||||
throw new ArgumentException("Argument must be greater then 0", nameof(timeoutMs));
|
||||
}
|
||||
|
||||
// Timed waiting. We need to wait for I/O ourselves.
|
||||
if (!proc.WaitForExit(timeoutMs))
|
||||
{
|
||||
this.Cancel();
|
||||
}
|
||||
|
||||
// Wait for the I/O to finish.
|
||||
var waitMs = (int)(timeoutMs - this.stopwatch.ElapsedMilliseconds);
|
||||
waitMs = Math.Max(waitMs, 10);
|
||||
this.stdOutEvent?.WaitOne(waitMs);
|
||||
|
||||
waitMs = (int)(timeoutMs - this.stopwatch.ElapsedMilliseconds);
|
||||
waitMs = Math.Max(waitMs, 10);
|
||||
return this.stdErrEvent?.WaitOne(waitMs) ?? false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Cleanup.
|
||||
this.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Asynchronously waits for the specified amount and ends the process afterwards.</summary>
|
||||
/// <param name="timeoutMs">The timeout ms.</param>
|
||||
/// <remarks>Tjhis method performs the wait operation on a threadpool thread.
|
||||
/// Only recommended for short timeouts and situations where a synchronous call is undesired.</remarks>
|
||||
/// <returns>true, if the process has exited gracefully; false otherwise.</returns>
|
||||
public Task<bool> WaitAndKillAsync(int timeoutMs)
|
||||
{
|
||||
var task = Task.Run(() => this.WaitAndKill(timeoutMs));
|
||||
return task;
|
||||
}
|
||||
|
||||
/// <summary>Waits asynchronously for the process to exit.</summary>
|
||||
/// <param name="timeoutMs">The timeout ms.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>true, if the process has exited, false if the process is still running.</returns>
|
||||
/// <remarks>
|
||||
/// This methods waits until the process has existed or the
|
||||
/// <paramref name="timeoutMs" /> has elapsed.
|
||||
/// This method does not end the process itself.
|
||||
/// </remarks>
|
||||
public Task<bool> WaitForExitAsync(int timeoutMs, CancellationToken cancellationToken = default)
|
||||
{
|
||||
timeoutMs = Math.Max(0, timeoutMs);
|
||||
|
||||
var timeoutSource = new CancellationTokenSource(timeoutMs);
|
||||
var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken);
|
||||
|
||||
return this.WaitForExitAsync(linkedSource.Token);
|
||||
}
|
||||
|
||||
/// <summary>Waits asynchronously for the process to exit.</summary>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <remarks>This methods waits until the process has existed or the
|
||||
/// <paramref name="cancellationToken"/> has been triggered.
|
||||
/// This method does not end the process itself.</remarks>
|
||||
/// <returns>true, if the process has exited, false if the process is still running.</returns>
|
||||
public async Task<bool> WaitForExitAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var proc = this.process;
|
||||
|
||||
if (proc == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
|
||||
// Use local function instead of a lambda to allow proper deregistration of the event
|
||||
void ProcessExited(object sender, EventArgs e)
|
||||
{
|
||||
tcs.TrySetResult(true);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
proc.EnableRaisingEvents = true;
|
||||
proc.Exited += ProcessExited;
|
||||
|
||||
if (proc.HasExited)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
using (cancellationToken.Register(() => tcs.TrySetResult(false)))
|
||||
{
|
||||
return await tcs.Task.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
proc.Exited -= ProcessExited;
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel()
|
||||
{
|
||||
var proc = this.process;
|
||||
|
||||
if (proc != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Invalidate cached data to requery.
|
||||
proc.Refresh();
|
||||
|
||||
// We need to do this in case of a non-UI proc
|
||||
// or one to be forced to cancel.
|
||||
if (!proc.HasExited)
|
||||
{
|
||||
// Cancel all pending IO ops.
|
||||
proc.CancelErrorRead();
|
||||
proc.CancelOutputRead();
|
||||
}
|
||||
|
||||
if (!proc.HasExited)
|
||||
{
|
||||
proc.Kill();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Kill will throw when/if the process has already exited.
|
||||
}
|
||||
}
|
||||
|
||||
var outEvent = this.stdOutEvent;
|
||||
this.stdOutEvent = null;
|
||||
if (outEvent != null)
|
||||
{
|
||||
lock (outEvent)
|
||||
{
|
||||
outEvent.Close();
|
||||
outEvent.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
var errEvent = this.stdErrEvent;
|
||||
this.stdErrEvent = null;
|
||||
if (errEvent != null)
|
||||
{
|
||||
lock (errEvent)
|
||||
{
|
||||
errEvent.Close();
|
||||
errEvent.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Close()
|
||||
{
|
||||
this.Cancel();
|
||||
|
||||
var proc = this.process;
|
||||
this.process = null;
|
||||
if (proc != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.UnRegisterProcessEvents(proc);
|
||||
|
||||
// Dispose in all cases.
|
||||
proc.Close();
|
||||
proc.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.OnProcessErrorCore(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void OnDispose()
|
||||
{
|
||||
}
|
||||
|
||||
void IDisposable.Dispose()
|
||||
{
|
||||
this.IsDisposed = true;
|
||||
this.Close();
|
||||
this.OnDispose();
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return string.Format("{0}: {1} {2}", this.GetType().Name, this.Name, this.process);
|
||||
}
|
||||
|
||||
protected virtual bool OnBeforeStartProcessCore(RunnerParams processRunnerInfo)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected virtual void OnProcessStartedCore()
|
||||
{
|
||||
}
|
||||
|
||||
protected virtual void OnProcessErrorCore(Exception processException)
|
||||
{
|
||||
}
|
||||
|
||||
protected virtual void OnProcessExitCore(int exitCode)
|
||||
{
|
||||
}
|
||||
|
||||
private void RegisterProcessEvents(Process proc)
|
||||
{
|
||||
proc.ErrorDataReceived += this.Process_ErrorDataReceived;
|
||||
proc.OutputDataReceived += this.Process_OutputDataReceived;
|
||||
proc.Exited += this.Process_Exited;
|
||||
}
|
||||
|
||||
private void UnRegisterProcessEvents(Process proc)
|
||||
{
|
||||
proc.ErrorDataReceived -= this.Process_ErrorDataReceived;
|
||||
proc.OutputDataReceived -= this.Process_OutputDataReceived;
|
||||
proc.Exited -= this.Process_Exited;
|
||||
}
|
||||
|
||||
private void Process_Exited(object sender, EventArgs e)
|
||||
{
|
||||
this.WaitForExitAfterExited();
|
||||
this.SetExitCode();
|
||||
this.OnProcessExitCore(this.LastExitCode ?? -9998);
|
||||
this.ProcessExited?.Invoke(this, new EventArgs());
|
||||
}
|
||||
|
||||
private void WaitForExitAfterExited()
|
||||
{
|
||||
try
|
||||
{
|
||||
// This shouldn't throw here, but the mono process implementation doesn't always behave as it should.
|
||||
this.process.WaitForExit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Error when calling WaitForExit after exited event has fired: {0}.{1}: {2}", ex, nameof(ProcessRunner), nameof(this.WaitForExitAfterExited));
|
||||
}
|
||||
}
|
||||
|
||||
private void SetExitCode()
|
||||
{
|
||||
int exitCode = -9999;
|
||||
|
||||
try
|
||||
{
|
||||
if (this.Process != null)
|
||||
{
|
||||
exitCode = this.Process.ExitCode;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore error.
|
||||
}
|
||||
|
||||
this.LastExitCode = exitCode;
|
||||
}
|
||||
|
||||
private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
|
||||
{
|
||||
if (this.RecordStandardError)
|
||||
{
|
||||
lock (this.stdErr)
|
||||
{
|
||||
this.stdErr.AppendLine(e.Data);
|
||||
}
|
||||
}
|
||||
|
||||
if (e.Data != null)
|
||||
{
|
||||
Console.WriteLine("|| " + e.Data);
|
||||
}
|
||||
else
|
||||
{
|
||||
var evt = this.stdErrEvent;
|
||||
if (evt != null)
|
||||
{
|
||||
lock (evt)
|
||||
{
|
||||
try
|
||||
{
|
||||
evt.Set();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore error.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
|
||||
{
|
||||
if (this.RecordStandardOutput)
|
||||
{
|
||||
lock (this.stdOut)
|
||||
{
|
||||
this.stdOut.AppendLine(e.Data);
|
||||
}
|
||||
}
|
||||
|
||||
if (e.Data != null)
|
||||
{
|
||||
Console.WriteLine("|| " + e.Data);
|
||||
}
|
||||
else
|
||||
{
|
||||
var evt = this.stdOutEvent;
|
||||
if (evt != null)
|
||||
{
|
||||
lock (evt)
|
||||
{
|
||||
try
|
||||
{
|
||||
evt.Set();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore error.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
namespace ElectronNET.Common
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
public sealed class RunnerParams
|
||||
{
|
||||
private string fileName;
|
||||
private string arguments;
|
||||
private string directory;
|
||||
private string userName;
|
||||
private string verb;
|
||||
private ProcessWindowStyle windowStyle;
|
||||
|
||||
/// <summary>
|
||||
/// Default constructor. At least the <see cref='ProcessStartInfo.FileName'/>
|
||||
/// property must be set before starting the process.
|
||||
/// </summary>
|
||||
public RunnerParams()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies the name of the application or document that is to be started.
|
||||
/// </summary>
|
||||
public RunnerParams(string fileName)
|
||||
{
|
||||
this.fileName = fileName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies the name of the application that is to be started, as well as a set
|
||||
/// of command line arguments to pass to the application.
|
||||
/// </summary>
|
||||
public RunnerParams(string fileName, string arguments)
|
||||
{
|
||||
this.fileName = fileName;
|
||||
this.arguments = arguments;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies the set of command line arguments to use when starting the application.
|
||||
/// </summary>
|
||||
public string Arguments
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.arguments ?? string.Empty;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
this.arguments = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool CreateNoWindow { get; set; }
|
||||
|
||||
public Dictionary<string, string> EnvironmentVariables { get; set; } = new Dictionary<string, string>();
|
||||
|
||||
public bool RedirectStandardInput { get; set; }
|
||||
|
||||
public bool RedirectStandardOutput { get; set; }
|
||||
|
||||
public bool RedirectStandardError { get; set; }
|
||||
|
||||
public Encoding StandardInputEncoding { get; set; }
|
||||
|
||||
public Encoding StandardErrorEncoding { get; set; }
|
||||
|
||||
public Encoding StandardOutputEncoding { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para>
|
||||
/// Returns or sets the application, document, or URL that is to be launched.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public string FileName
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.fileName ?? string.Empty;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
this.fileName = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns or sets the initial directory for the process that is started.
|
||||
/// Specify "" to if the default is desired.
|
||||
/// </summary>
|
||||
public string WorkingDirectory
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.directory ?? string.Empty;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
this.directory = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool ErrorDialog { get; set; }
|
||||
|
||||
public IntPtr ErrorDialogParentHandle { get; set; }
|
||||
|
||||
public string UserName
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.userName ?? string.Empty;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
this.userName = value;
|
||||
}
|
||||
}
|
||||
|
||||
[DefaultValue("")]
|
||||
public string Verb
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.verb ?? string.Empty;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
this.verb = value;
|
||||
}
|
||||
}
|
||||
|
||||
[DefaultValue(ProcessWindowStyle.Normal)]
|
||||
public ProcessWindowStyle WindowStyle
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.windowStyle;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
if (!Enum.IsDefined(typeof(ProcessWindowStyle), value))
|
||||
{
|
||||
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessWindowStyle));
|
||||
}
|
||||
|
||||
this.windowStyle = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool UseShellExecute { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,54 @@
|
||||
namespace ElectronNET.Converter;
|
||||
|
||||
using ElectronNET.API.Entities;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Linq;
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace ElectronNET.API.Converter;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class ModifierTypeListConverter : JsonConverter<List<ModifierType>>
|
||||
{
|
||||
public override List<ModifierType> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="reader"></param>
|
||||
/// <param name="objectType"></param>
|
||||
/// <param name="existingValue"></param>
|
||||
/// <param name="hasExistingValue"></param>
|
||||
/// <param name="serializer"></param>
|
||||
/// <returns></returns>
|
||||
public override List<ModifierType> ReadJson(JsonReader reader, Type objectType, List<ModifierType> existingValue, bool hasExistingValue, JsonSerializer serializer)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.Null)
|
||||
var token = JToken.Load(reader);
|
||||
|
||||
if (token.Type == JTokenType.Null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var list = new List<ModifierType>();
|
||||
if (reader.TokenType != JsonTokenType.StartArray)
|
||||
{
|
||||
throw new JsonException("Expected array for ModifierType list");
|
||||
}
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.EndArray) break;
|
||||
if (reader.TokenType != JsonTokenType.String) throw new JsonException("Expected string enum value");
|
||||
var s = reader.GetString();
|
||||
list.Add((ModifierType)Enum.Parse(typeof(ModifierType), s, ignoreCase: true));
|
||||
}
|
||||
return list;
|
||||
|
||||
return token.ToObject<List<string>>().Select(m => (ModifierType)Enum.Parse(typeof(ModifierType), m)).ToList();
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, List<ModifierType> value, JsonSerializerOptions options)
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="writer"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="serializer"></param>
|
||||
public override void WriteJson(JsonWriter writer, List<ModifierType> value, JsonSerializer serializer)
|
||||
{
|
||||
writer.WriteStartArray();
|
||||
|
||||
foreach (var modifier in value)
|
||||
{
|
||||
writer.WriteStringValue(modifier.ToString());
|
||||
writer.WriteValue(modifier.ToString());
|
||||
}
|
||||
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Serialization;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ElectronNET.Converter;
|
||||
|
||||
public class PageSizeConverter : JsonConverter<PageSize>
|
||||
{
|
||||
public override PageSize Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.String)
|
||||
{
|
||||
return reader.GetString();
|
||||
}
|
||||
else if (reader.TokenType == JsonTokenType.StartObject)
|
||||
{
|
||||
return JsonSerializer.Deserialize<PageSize>(ref reader, ElectronJson.Options);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new JsonException("Invalid value for PageSize. Expected string or an object.");
|
||||
}
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, PageSize value, JsonSerializerOptions options)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var str = (string)value;
|
||||
|
||||
if (str is not null)
|
||||
{
|
||||
writer.WriteStringValue(str);
|
||||
}
|
||||
else
|
||||
{
|
||||
JsonSerializer.Serialize(writer, value, ElectronJson.Options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Serialization;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ElectronNET.Converter;
|
||||
|
||||
public class TitleBarOverlayConverter : JsonConverter<TitleBarOverlay>
|
||||
{
|
||||
public override TitleBarOverlay Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False)
|
||||
{
|
||||
return (bool)reader.GetBoolean();
|
||||
}
|
||||
else if (reader.TokenType == JsonTokenType.StartObject)
|
||||
{
|
||||
using var doc = JsonDocument.ParseValue(ref reader);
|
||||
return doc.RootElement.Deserialize<TitleBarOverlay>(ElectronJson.Options);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new JsonException("Invalid value for TitleBarOverlay. Expected boolean or an object.");
|
||||
}
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, TitleBarOverlay value, JsonSerializerOptions options)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var @bool = (bool?)value;
|
||||
if (@bool.HasValue)
|
||||
{
|
||||
writer.WriteBooleanValue(@bool.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
JsonSerializer.Serialize(writer, value, ElectronJson.Options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
152
src/ElectronNET.API/Cookies.cs
Normal file
152
src/ElectronNET.API/Cookies.cs
Normal file
@@ -0,0 +1,152 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Query and modify a session's cookies.
|
||||
/// </summary>
|
||||
public class Cookies
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the identifier.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The identifier.
|
||||
/// </value>
|
||||
public int Id { get; private set; }
|
||||
|
||||
internal Cookies(int id)
|
||||
{
|
||||
Id = id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emitted when a cookie is changed because it was added, edited, removed, or expired.
|
||||
/// </summary>
|
||||
public event Action<Cookie, CookieChangedCause, bool> OnChanged
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_changed == null)
|
||||
{
|
||||
BridgeConnector.Socket.On("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>();
|
||||
_changed(cookie, cause, removed);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-webContents-session-cookies-changed", Id).FireAndForget();
|
||||
}
|
||||
_changed += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_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>
|
||||
/// <param name="filter">
|
||||
/// </param>
|
||||
/// <returns>A task which resolves an array of cookie objects.</returns>
|
||||
public Task<Cookie[]> GetAsync(CookieFilter filter)
|
||||
{
|
||||
var taskCompletionSource = 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.Off("webContents-session-cookies-get-completed" + guid);
|
||||
taskCompletionSource.SetResult(result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-get", Id, JObject.FromObject(filter, _jsonSerializer), guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="details"></param>
|
||||
/// <returns></returns>
|
||||
public Task SetAsync(CookieDetails details)
|
||||
{
|
||||
var taskCompletionSource = 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.Emit("webContents-session-cookies-set", Id, JObject.FromObject(details, _jsonSerializer), guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the cookies matching url and name
|
||||
/// </summary>
|
||||
/// <param name="url">The URL associated with the cookie.</param>
|
||||
/// <param name="name">The name of cookie to remove.</param>
|
||||
/// <returns>A task which resolves when the cookie has been removed</returns>
|
||||
public Task RemoveAsync(string url, string name)
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<object>();
|
||||
var 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);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-remove", Id, url, name, guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes any unwritten cookies data to disk.
|
||||
/// </summary>
|
||||
/// <returns>A task which resolves when the cookie store has been flushed</returns>
|
||||
public Task FlushStoreAsync()
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<object>();
|
||||
var 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);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-flushStore", Id, guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ElectronNET.API
|
||||
@@ -13,9 +16,7 @@ namespace ElectronNET.API
|
||||
private static Dialog _dialog;
|
||||
private static object _syncRoot = new object();
|
||||
|
||||
internal Dialog()
|
||||
{
|
||||
}
|
||||
internal Dialog() { }
|
||||
|
||||
internal static Dialog Instance
|
||||
{
|
||||
@@ -25,7 +26,7 @@ namespace ElectronNET.API
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
if (_dialog == null)
|
||||
if(_dialog == null)
|
||||
{
|
||||
_dialog = new Dialog();
|
||||
}
|
||||
@@ -46,16 +47,20 @@ namespace ElectronNET.API
|
||||
/// <returns>An array of file paths chosen by the user</returns>
|
||||
public Task<string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<string[]>();
|
||||
var taskCompletionSource = new TaskCompletionSource<string[]>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.Once<string[]>("showOpenDialogComplete" + guid, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("showOpenDialog",
|
||||
browserWindow,
|
||||
options,
|
||||
guid);
|
||||
BridgeConnector.Socket.On("showOpenDialogComplete" + guid, (filePaths) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("showOpenDialogComplete" + guid);
|
||||
|
||||
return tcs.Task;
|
||||
var result = ((JArray)filePaths).ToObject<string[]>();
|
||||
taskCompletionSource.SetResult(result);
|
||||
});
|
||||
|
||||
|
||||
BridgeConnector.Socket.Emit("showOpenDialog", JObject.FromObject(browserWindow, _jsonSerializer), JObject.FromObject(options, _jsonSerializer), guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -66,16 +71,18 @@ 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 tcs = new TaskCompletionSource<string>();
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.Once<string>("showSaveDialogComplete" + guid, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("showSaveDialog",
|
||||
browserWindow,
|
||||
options,
|
||||
guid);
|
||||
BridgeConnector.Socket.On("showSaveDialogComplete" + guid, (filename) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("showSaveDialogComplete" + guid);
|
||||
|
||||
return tcs.Task;
|
||||
taskCompletionSource.SetResult(filename.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("showSaveDialog", JObject.FromObject(browserWindow, _jsonSerializer), JObject.FromObject(options, _jsonSerializer), guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -89,7 +96,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 this.ShowMessageBoxAsync(null, new MessageBoxOptions(message)).ConfigureAwait(false);
|
||||
return await ShowMessageBoxAsync(null, new MessageBoxOptions(message));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -103,7 +110,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 this.ShowMessageBoxAsync(null, messageBoxOptions).ConfigureAwait(false);
|
||||
return await ShowMessageBoxAsync(null, messageBoxOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -116,7 +123,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 this.ShowMessageBoxAsync(browserWindow, new MessageBoxOptions(message)).ConfigureAwait(false);
|
||||
return await ShowMessageBoxAsync(browserWindow, new MessageBoxOptions(message));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -129,39 +136,33 @@ 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 tcs = new TaskCompletionSource<MessageBoxResult>();
|
||||
var taskCompletionSource = new TaskCompletionSource<MessageBoxResult>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.Once<JsonElement>("showMessageBoxComplete" + guid, (args) =>
|
||||
BridgeConnector.Socket.On("showMessageBoxComplete" + guid, (args) =>
|
||||
{
|
||||
// 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();
|
||||
BridgeConnector.Socket.Off("showMessageBoxComplete" + guid);
|
||||
|
||||
tcs.SetResult(new MessageBoxResult
|
||||
var result = ((JArray)args);
|
||||
|
||||
taskCompletionSource.SetResult(new MessageBoxResult
|
||||
{
|
||||
Response = response,
|
||||
CheckboxChecked = checkbox
|
||||
Response = (int)result.First,
|
||||
CheckboxChecked = (bool)result.Last
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
if (browserWindow == null)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("showMessageBox", messageBoxOptions, guid);
|
||||
BridgeConnector.Socket.Emit("showMessageBox", JObject.FromObject(messageBoxOptions, _jsonSerializer), guid).FireAndForget();
|
||||
}
|
||||
else
|
||||
{
|
||||
BridgeConnector.Socket.Emit("showMessageBox",
|
||||
browserWindow,
|
||||
messageBoxOptions,
|
||||
guid);
|
||||
BridgeConnector.Socket.Emit("showMessageBox", JObject.FromObject(browserWindow, _jsonSerializer), JObject.FromObject(messageBoxOptions, _jsonSerializer), guid).FireAndForget();
|
||||
}
|
||||
|
||||
return tcs.Task;
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -176,7 +177,7 @@ namespace ElectronNET.API
|
||||
/// <param name="content">The text content to display in the error box.</param>
|
||||
public void ShowErrorBox(string title, string content)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("showErrorBox", title, content);
|
||||
BridgeConnector.Socket.Emit("showErrorBox", title, content).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -201,18 +202,24 @@ namespace ElectronNET.API
|
||||
/// <returns></returns>
|
||||
public Task ShowCertificateTrustDialogAsync(BrowserWindow browserWindow, CertificateTrustDialogOptions options)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<object>();
|
||||
string guid = Guid.NewGuid().ToString();
|
||||
var taskCompletionSource = new TaskCompletionSource<object>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.Once("showCertificateTrustDialogComplete" + guid, () => tcs.SetResult(null));
|
||||
BridgeConnector.Socket.Emit("showCertificateTrustDialog",
|
||||
browserWindow,
|
||||
options,
|
||||
guid);
|
||||
BridgeConnector.Socket.On("showCertificateTrustDialogComplete" + guid, () =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("showCertificateTrustDialogComplete" + guid);
|
||||
taskCompletionSource.SetResult(null);
|
||||
});
|
||||
|
||||
return tcs.Task;
|
||||
BridgeConnector.Socket.Emit("showCertificateTrustDialog", JObject.FromObject(browserWindow, _jsonSerializer), JObject.FromObject(options, _jsonSerializer), guid).FireAndForget();
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Extensions;
|
||||
using ElectronNET.API.Serialization;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
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
|
||||
{
|
||||
@@ -53,13 +54,18 @@ namespace ElectronNET.API
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var tcs = new TaskCompletionSource<int>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
var taskCompletionSource = new TaskCompletionSource<int>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.Once<int>("dock-bounce-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("dock-bounce", type.GetDescription());
|
||||
BridgeConnector.Socket.On("dock-bounce-completed", (id) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("dock-bounce-completed");
|
||||
taskCompletionSource.SetResult((int) id);
|
||||
});
|
||||
|
||||
return await tcs.Task
|
||||
BridgeConnector.Socket.Emit("dock-bounce", type.GetDescription()).FireAndForget();
|
||||
|
||||
return await taskCompletionSource.Task
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -70,7 +76,7 @@ namespace ElectronNET.API
|
||||
/// <param name="id">Id of the request.</param>
|
||||
public void CancelBounce(int id)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("dock-cancelBounce", id);
|
||||
BridgeConnector.Socket.Emit("dock-cancelBounce", id).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -79,7 +85,7 @@ namespace ElectronNET.API
|
||||
/// <param name="filePath"></param>
|
||||
public void DownloadFinished(string filePath)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("dock-downloadFinished", filePath);
|
||||
BridgeConnector.Socket.Emit("dock-downloadFinished", filePath).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -88,7 +94,7 @@ namespace ElectronNET.API
|
||||
/// <param name="text"></param>
|
||||
public void SetBadge(string text)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("dock-setBadge", text);
|
||||
BridgeConnector.Socket.Emit("dock-setBadge", text).FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -100,13 +106,18 @@ namespace ElectronNET.API
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var tcs = new TaskCompletionSource<string>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.Once<string>("dock-getBadge-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("dock-getBadge");
|
||||
BridgeConnector.Socket.On("dock-getBadge-completed", (text) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("dock-getBadge-completed");
|
||||
taskCompletionSource.SetResult((string) text);
|
||||
});
|
||||
|
||||
return await tcs.Task
|
||||
BridgeConnector.Socket.Emit("dock-getBadge").FireAndForget();
|
||||
|
||||
return await taskCompletionSource.Task
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -116,7 +127,7 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
public void Hide()
|
||||
{
|
||||
BridgeConnector.Socket.Emit("dock-hide");
|
||||
BridgeConnector.Socket.Emit("dock-hide").FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -124,7 +135,7 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
public void Show()
|
||||
{
|
||||
BridgeConnector.Socket.Emit("dock-show");
|
||||
BridgeConnector.Socket.Emit("dock-show").FireAndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -137,13 +148,18 @@ namespace ElectronNET.API
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.Once<bool>("dock-isVisible-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("dock-isVisible");
|
||||
BridgeConnector.Socket.On("dock-isVisible-completed", (isVisible) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("dock-isVisible-completed");
|
||||
taskCompletionSource.SetResult((bool) isVisible);
|
||||
});
|
||||
|
||||
return await tcs.Task
|
||||
BridgeConnector.Socket.Emit("dock-isVisible").FireAndForget();
|
||||
|
||||
return await taskCompletionSource.Task
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -154,14 +170,7 @@ 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>
|
||||
@@ -170,15 +179,15 @@ namespace ElectronNET.API
|
||||
public void SetMenu(MenuItem[] menuItems)
|
||||
{
|
||||
menuItems.AddMenuItemsId();
|
||||
BridgeConnector.Socket.Emit("dock-setMenu", new[] { menuItems });
|
||||
BridgeConnector.Socket.Emit("dock-setMenu", JArray.FromObject(menuItems, _jsonSerializer)).FireAndForget();
|
||||
_items.AddRange(menuItems);
|
||||
|
||||
BridgeConnector.Socket.Off("dockMenuItemClicked");
|
||||
BridgeConnector.Socket.On<string>("dockMenuItemClicked", (id) =>
|
||||
{
|
||||
MenuItem menuItem = _items.GetMenuItem(id);
|
||||
BridgeConnector.Socket.On("dockMenuItemClicked", (id) => {
|
||||
MenuItem menuItem = _items.GetMenuItem(id.ToString());
|
||||
menuItem?.Click();
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -189,13 +198,18 @@ namespace ElectronNET.API
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var tcs = new TaskCompletionSource<Menu>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
var taskCompletionSource = new TaskCompletionSource<Menu>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.Once<Menu>("dock-getMenu-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("dock-getMenu");
|
||||
BridgeConnector.Socket.On("dock-getMenu-completed", (menu) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("dock-getMenu-completed");
|
||||
taskCompletionSource.SetResult(((JObject)menu).ToObject<Menu>());
|
||||
});
|
||||
|
||||
return await tcs.Task
|
||||
BridgeConnector.Socket.Emit("dock-getMenu").FireAndForget();
|
||||
|
||||
return await taskCompletionSource.Task
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -206,9 +220,13 @@ namespace ElectronNET.API
|
||||
/// <param name="image"></param>
|
||||
public void SetIcon(string image)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("dock-setIcon", image);
|
||||
BridgeConnector.Socket.Emit("dock-setIcon", image).FireAndForget();
|
||||
}
|
||||
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
92
src/ElectronNET.API/Electron.cs
Normal file
92
src/ElectronNET.API/Electron.cs
Normal file
@@ -0,0 +1,92 @@
|
||||
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 system’s 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; } }
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,47 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<Import Project="..\common.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net6.0;net8.0;net10.0</TargetFrameworks>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<PackageOutputPath>..\..\artifacts</PackageOutputPath>
|
||||
<PackageId>$(PackageNamePrefix).API</PackageId>
|
||||
<Title>$(PackageId)</Title>
|
||||
<PackageId>ElectronNET.API</PackageId>
|
||||
<Authors>Gregor Biswanger, Florian Rappl</Authors>
|
||||
<Company />
|
||||
<Product>Electron.NET</Product>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<PackageProjectUrl>https://github.com/ElectronNET/Electron.NET/</PackageProjectUrl>
|
||||
<Description>Building cross platform electron based desktop apps with .NET Core and ASP.NET Core.
|
||||
This package contains the API to access the "native" electron API.</Description>
|
||||
<RepositoryUrl>https://github.com/ElectronNET/Electron.NET/</RepositoryUrl>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<PublishRepositoryUrl>true</PublishRepositoryUrl>
|
||||
<PackageTags>electron aspnetcore</PackageTags>
|
||||
<PackageReleaseNotes>Changelog: https://github.com/ElectronNET/Electron.NET/blob/main/Changelog.md</PackageReleaseNotes>
|
||||
<PackageIcon>PackageIcon.png</PackageIcon>
|
||||
<Version>99.0.0.0</Version>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<IncludeSymbols>True</IncludeSymbols>
|
||||
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||
<Nullable>disable</Nullable>
|
||||
<Description>$(DescriptionFirstPart) This package contains the API to access the "native" electron API.</Description>
|
||||
<RootNamespace>ElectronNET</RootNamespace>
|
||||
<NoWarn>1701;1702;4014;CS4014;CA1416;CS1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<None Remove="ElectronNET.API.csproj.DotSettings" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="PackageIcon.png" Pack="true" PackagePath="\" />
|
||||
<None Include="../../README.md" Pack="true" PackagePath="\" />
|
||||
</ItemGroup>
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Windows_NT'">
|
||||
<Exec Command="$(ProjectDir)devCleanup.cmd" IgnoreExitCode="true" />
|
||||
</Target>
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(OS)' != 'Windows_NT'">
|
||||
<Exec Command="$(ProjectDir)devCleanup.sh" IgnoreExitCode="true" />
|
||||
</Target>
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0">
|
||||
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="SocketIOClient" Version="3.1.2" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="8.0.16" />
|
||||
<PackageReference Include="System.Text.Json" Version="8.0.5" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="SocketIOClient" Version="3.0.8" />
|
||||
<PackageReference Include="SocketIOClient.Newtonsoft.Json" Version="3.0.7" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers" Version="0.4.410601">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ElectronNET.AspNet" />
|
||||
<InternalsVisibleTo Include="ElectronNET.Core.AspNet" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -1,3 +0,0 @@
|
||||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<s:String x:Key="/Default/CodeInspection/Daemon/ConfigureAwaitAnalysisMode/@EntryValue">Library</s:String>
|
||||
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=entities/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
|
||||
@@ -1,55 +0,0 @@
|
||||
namespace ElectronNET
|
||||
{
|
||||
using ElectronNET.API;
|
||||
using ElectronNET.Runtime;
|
||||
using ElectronNET.Runtime.Controllers;
|
||||
using ElectronNET.Runtime.Data;
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public static class ElectronNetRuntime
|
||||
{
|
||||
internal static StartupManager StartupManager;
|
||||
|
||||
internal const int DefaultSocketPort = 8000;
|
||||
internal const int DefaultWebPort = 8001;
|
||||
internal const string ElectronPortArgumentName = "electronPort";
|
||||
internal const string ElectronPidArgumentName = "electronPID";
|
||||
|
||||
/// <summary>Initializes the <see cref="ElectronNetRuntime"/> class.</summary>
|
||||
static ElectronNetRuntime()
|
||||
{
|
||||
StartupManager = new StartupManager();
|
||||
StartupManager.Initialize();
|
||||
}
|
||||
|
||||
public static int? ElectronSocketPort { get; internal set; }
|
||||
|
||||
public static int? AspNetWebPort { get; internal set; }
|
||||
|
||||
public static StartupMethod StartupMethod { get; internal set; }
|
||||
|
||||
public static DotnetAppType DotnetAppType { get; internal set; }
|
||||
|
||||
public static string ElectronExecutable { get; internal set; }
|
||||
|
||||
public static ImmutableList<string> ProcessArguments { get; internal set; }
|
||||
|
||||
public static BuildInfo BuildInfo { get; internal set; }
|
||||
|
||||
public static IElectronNetRuntimeController RuntimeController => RuntimeControllerCore;
|
||||
|
||||
// The below properties are non-public
|
||||
internal static RuntimeControllerBase RuntimeControllerCore { get; set; }
|
||||
|
||||
internal static int? ElectronProcessId { get; set; }
|
||||
|
||||
internal static Func<Task> OnAppReadyCallback { get; set; }
|
||||
|
||||
internal static SocketIoFacade GetSocket()
|
||||
{
|
||||
return RuntimeControllerCore?.Socket;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,6 @@ namespace ElectronNET.API.Entities
|
||||
/// <summary>
|
||||
/// Gets or sets the dataURL
|
||||
/// </summary>
|
||||
public string DataUrl { get; set; }
|
||||
public string DataUrl { get; set; }
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user