Compare commits

..

8 Commits

Author SHA1 Message Date
Florian Rappl
2910833e61 Corrected paths 2023-04-04 17:26:52 +02:00
Florian Rappl
42e816e85c Updated sample connector 2023-04-04 16:40:54 +02:00
Florian Rappl
03c08503cc Updated build system with template 2023-04-04 16:40:45 +02:00
Florian Rappl
555f0378b4 Improved code helpers 2023-04-04 15:40:24 +02:00
Florian Rappl
79580327bd Removed all warnings. 2023-04-04 15:11:12 +02:00
Florian Rappl
f6d17406cd Cleanup and improvements 2023-04-04 14:31:25 +02:00
Florian Rappl
9e79665690 Improved the README 2023-04-03 18:19:30 +02:00
Florian Rappl
9f98b5ca85 Modernized the host bridge 2023-04-03 18:16:59 +02:00
521 changed files with 14151 additions and 39601 deletions

View File

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

BIN
.github/WikiLinks.exe vendored

Binary file not shown.

View File

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

View File

@@ -1,36 +1,40 @@
name: Build and Publish
name: CI
on: [push]
on: [push, pull_request]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
concurrency:
group: build-publish-${{ github.ref }}
cancel-in-progress: true
jobs:
Integration-Tests:
uses: ./.github/workflows/integration-tests.yml
name: '1'
Publish:
needs: [Integration-Tests]
runs-on: windows-latest
timeout-minutes: 10
name: '2 / Publish'
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: |

View File

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

View File

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

View File

@@ -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'

View File

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

View File

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

1
.gitignore vendored
View File

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

View File

@@ -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"
}
]
}
}
}

View File

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

4
.vscode/launch.json vendored
View File

@@ -10,9 +10,9 @@
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceRoot}/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
View File

@@ -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",

View File

@@ -1,139 +1,377 @@
# 0.4.1
# 23.6.2
## ElectronNET.Core
## ElectronNET.API
- Fixed handling of `Center` property for windows (#1001)
- Added missing methods on `Cookies` (#1000)
* Fixed escaping of URL (#735) @cosmo0
* Changed `ZoomFactor` type from `int` to `double` (#754) @Yuvix25
# 0.4.0
## ElectronNET.CLI
## ElectronNET.Core
* (none)
- Fixed ElectronSingleInstance handling (#996) @softworkz
- Fixed `PackageId` handling (#993) @softworkz
- Added cross-platform npm restore and check mismatch on publish (#988) @softworkz
## Infrastructure
# 0.3.1
* Changed build system to NUKE #757 @FlorianRappl
* Updated target framework for host project #753 @r-pankevicius
## ElectronNET.Core
# 23.6.1
- Fixed issue transforming the project ID (#989, #990) @softworkz
## ElectronNET.CLI
# 0.3.0
* New Feature: Upgrade to .NET 6 support
## ElectronNET.Core
## ElectronNET.API
- Updated infrastructure (#937, #939) @softworkz
- Updated all model classes to Electron API 39.2 (#949) @softworkz
- Fixed output path for `electron-builder` (#942) @softworkz
- Fixed floating point display resolution (#944) @softworkz
- Fixed error in case of missing electron-host-hook (#978)
- Fixed previous API break using exposed `JsonElement` objects (#938) @softworkz
- Fixed and improved several test cases (#962) @softworkz
- Fixed startup of Electron.NET from VS Code Debug Adapter (#952)
- Fixed the `BrowserWindowOptions` (#945) @softworkz
- Fixed example for `AutoMenuHide` to reflect platform capabilities (#982) @markatosi
- Added several migration checks for publishing (#966) @softworkz
- Added more test runners for E2E tests (#950, #951) @agracio
- Added dynamic updates for tray menu (#973) @davidroth
- Added matrix tests with 6 runners and 2 electron version (#948) @softworkz
- Added additional APIs for WebContents (#958) @agracio
- Added documentation for MacOS package publish (#983) @markatosi
- Added sample application for `ElectronHostHook` (#967) @adityashirsatrao007
* 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)
# 0.2.0
# 13.5.1
## ElectronNET.Core
ElectronNET.CLI:
- Updated dependencies (#930) @softworkz
- Updated integration tests (#931) @softworkz
- Updated `ElectronNET.Host` (#935) @softworkz
- Removed transition period specific build configuration (#928) @softworkz
- Added `IsRunningBlazor` option to `BrowserWindowOptions` (#926)
- Added platform support attributes (#929) @softworkz
* 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)
# 0.1.0
# 11.5.1
## ElectronNET.Core
ElectronNET.CLI:
- 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
* 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)
# 0.0.18
ElectronNET.API:
## ElectronNET.Core
* 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)
### Highlights
Example for the Dock Menu
- **Complete MSBuild Integration**: Eliminated CLI tool dependency, moved all build processes to MSBuild with deep Visual Studio integration
- **Modernized Architecture**: Restructured process lifecycle with .NET launching first and running Electron as child process for better control and reliability
- **Cross-Platform Development**: Build and debug Linux applications directly from Windows Visual Studio via WSL integration
- **Flexible Electron Versioning**: Removed version lock-in, users can now select any Electron version with build-time validation
- **Enhanced Debugging Experience**: ASP.NET-first debugging with Hot Reload support and improved process termination handling
- **Console App Support**: No longer requires ASP.NET - now works with simple console applications for file system or remote server HTML/JS
`Electron.Dock.SetMenu(new [] {
new MenuItem {
Label = "Dock Menu Item",
Click = () => {
// do something
}
},
});`
### Build System & Project Structure
Example for consuming the activate event (MacOs only)
- 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
`Electron.App.On("activate", obj => {
var hasWindows = (bool)obj;
// do something
});`
### Development Experience
* 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)
- 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)
# 9.31.2
### Debugging & Runtime
* Electron-Builder fixed for Windows builds.
- 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
# 9.31.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: 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)
### Package & Distribution
ElectronNET.API:
- 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
* 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)
### Migration & Compatibility
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)
- 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
Thank you for donation [Phil Seeman](https://github.com/mpnow) ❤
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.
# 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

View File

@@ -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

View File

@@ -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>

377
README.md
View File

@@ -2,195 +2,215 @@
[![donate](https://img.shields.io/badge/Donate-Donorbox-green.svg)](https://donorbox.org/electron-net) [![Gitter](https://badges.gitter.im/ElectronNET/community.svg)](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Build status](https://github.com/ElectronNET/Electron.NET/actions/workflows/ci.yml/badge.svg)](https://github.com/ElectronNET/Electron.NET/actions/workflows/ci.yml)
# 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 run by the Electron side) is still the primary way, there's more flexibility now. Both .NET and Electron are now able to launch the other for better lifetime management, and when you don't need a local web server (like when running content from files or remote servers), you can drop the ASP.NET stack altogether and go with a lightweight console app instead.
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: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.API/)
* ElectronNET.Core.API: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.API.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.API/)
* ElectronNET.Core.AspNet: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.AspNet.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.AspNet/)
[![NuGet](https://img.shields.io/nuget/v/ElectronNET.API.svg?style=flat-square) ElectronNET.API ](https://www.nuget.org/packages/ElectronNET.API/) | [![NuGet](https://img.shields.io/nuget/v/ElectronNET.CLI.svg?style=flat-square) ElectronNET.CLI](https://www.nuget.org/packages/ElectronNET.CLI/)
## 🛠 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
[![Gitter](https://badges.gitter.im/ElectronNET/community.svg)](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
Besides the chat on Gitter and the issues [discussed here](https://github.com/ElectronNET/Electron.NET/issues) you can also use [StackOverflow](https://stackoverflow.com/questions/tagged/electron.net) with the tag `electron.net`.
If you want to sponsor the further maintenance and development of this project [see the donate section](#-donate).
## 👩‍🏫 Usage
To activate and communicate with the "native" (sort of native...) Electron API include the [ElectronNET.API NuGet package](https://www.nuget.org/packages/ElectronNET.API/) in your ASP.NET Core app.
```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();
}
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseElectron(args);
public static async Task ElectronAppReady()
{
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions { Show = false });
// Is optional, but you can use the Electron.NET API-Classes directly with DI (relevant if you wont more encoupled code)
builder.Services.AddElectron();
browserWindow.OnReadyToShow += () => browserWindow.Show();
}
var app = builder.Build();
...
await app.StartAsync();
// Open the Electron-Window here
await Electron.WindowManager.CreateWindowAsync();
app.WaitForShutdown();
```
### Minimal API Example
## Setup using Normal-API
For a minimal API you can use:
### Program.cs
You start Electron.NET up with an `UseElectron` WebHostBuilder-Extension.
```csharp
using ElectronNET;
using ElectronNET.API;
using ElectronNET.API.Entities;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddElectron(); // <- might be useful to set up DI
builder.UseElectron(args, async () =>
{
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions { Show = false, AutoHideMenuBar = true });
browserWindow.OnReadyToShow += () => browserWindow.Show();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseElectron(args);
webBuilder.UseStartup<Startup>();
});
```
### Blazor
### Startup.cs
For a project with Blazor you can use:
Open the Electron Window in the *Startup.cs* file:
```cs
using ElectronNET.API;
using ElectronNET.API.Entities;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddRazorComponents()
.AddInteractiveWebAssemblyComponents();
builder.Services.AddElectron(); // <-- might be useful to set up DI
builder.UseElectron(args, async () =>
```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var options = new BrowserWindowOptions {
Show = false,
IsRunningBlazor = true, // <-- crucial
};
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux())
options.AutoHideMenuBar = true;
var browserWindow = await Electron.WindowManager.CreateWindowAsync(options);
browserWindow.OnReadyToShow += () => browserWindow.Show();
});
//...
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
Electron.WindowManager.CreateWindowAsync();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents<BlazorApp.Components.App>()
.AddInteractiveWebAssemblyRenderMode();
app.Run();
```
The `IsRunningBlazor` option makes sure to set up the renderer in a way that Blazor can just run without any interference. This includes things such as HMR for development.
## 🚀 Starting the Application
## 🚀 Starting and Debugging 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:
Just press `F5` in Visual Studio or use dotnet for debugging.
```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
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!
@@ -206,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();
}
```

View File

@@ -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>

View File

@@ -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>

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

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

View File

@@ -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

View File

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

View File

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

View File

@@ -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.

View File

@@ -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>

View File

@@ -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

View File

@@ -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.4.1" />
</ItemGroup>
```
> [!WARNING]
> Specifying `OutputType` property is crucial in order to get the ability of WSL debugging. Especially it is not included in ASP.NET projects.
> When you migrate from ASP.NET to a console application, be sure to add this to the project file.
### 4. Implement Basic Structure
Here's a complete console application example:
```csharp
using System;
using System.Threading.Tasks;
using ElectronNET.API.Entities;
namespace MyElectronApp
public class Program
{
public static async Task Main(string[] args)
{
var runtimeController = ElectronNetRuntime.RuntimeController;
try
{
// Start Electron runtime
await runtimeController.Start();
await runtimeController.WaitReadyTask;
// Initialize your Electron app
await InitializeApp();
// Wait for shutdown
await runtimeController.WaitStoppedTask.ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
await runtimeController.Stop().ConfigureAwait(false);
await runtimeController.WaitStoppedTask.WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
}
}
private static async Task InitializeApp()
{
// Create main window
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions
{
Show = false,
WebPreferences = new WebPreferences
{
// Add these two when using file:// URLs
WebSecurity = false,
AllowRunningInsecureContent = true,
NodeIntegration = false,
ContextIsolation = true
}
});
// Load your content (file system, remote URL, etc.)
await browserWindow.WebContents.LoadURLAsync("https://example.com");
// Show window when ready
browserWindow.OnReadyToShow += () => browserWindow.Show();
}
}
```
## 📁 Content Sources
### File System Content
Serve HTML/JS files from your project:
```csharp
// In your project root, create wwwroot/index.html
var fileInfo = new FileInfo(Environment.ProcessPath);
var exeFolder = fileInfo.DirectoryName;
var htmlPath = Path.Combine(exeFolder, "wwwroot/index.html");
var url = new Uri(htmlPath, UriKind.Absolute);
await browserWindow.WebContents.LoadFileAsync(url.ToString());
```
### Remote Content
Load content from any web server:
```csharp
await browserWindow.WebContents.LoadURLAsync("https://your-server.com/app");
```
## 🚀 Next Steps
- **[Debugging](../Using/Debugging.md)** - Learn about debugging console applications
- **[Package Building](../Using/Package-Building.md)** - Create distributable packages
- **[Migration Guide](../Core/Migration-Guide.md)** - Moving from ASP.NET projects
## 💡 Benefits of Console Apps
**Simpler Architecture** - No ASP.NET complexity when not needed
**Flexible Content** - Use any HTML/JS source
**Faster Development** - Less overhead for simple applications
**Easy Deployment** - Minimal dependencies
**Better Performance** - Lighter weight than full web applications

View File

@@ -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

View File

@@ -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).

View File

@@ -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

View File

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

View File

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

View File

@@ -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

View File

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

View File

@@ -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
![Startup Modes](../images/startup_modes.png)
The image above illustrates how each combination of deployment type, application type, and initialization order affects the process lifecycle.
## 🚀 Development Workflows
### Debugging Workflow
**ASP.NET-First Debugging** (Recommended)
```json
// launchSettings.json
{
"ASP.Net (unpackaged)": {
"commandName": "Project",
"commandLineArgs": "-unpackeddotnet"
}
}
```
**Electron-First Debugging**
```json
// launchSettings.json
{
"Electron (unpackaged)": {
"commandName": "Executable",
"executablePath": "node",
"commandLineArgs": "node_modules/electron/cli.js main.js -unpackedelectron"
}
}
```
### Production Deployment
**Dotnet-First Deployment**
```bash
# Build and package
dotnet publish -c Release -r win-x64
cd publish\Release\net8.0\win-x64
npm install
npx electron-builder
# Run with dotnet-first
MyApp.exe -dotnetpacked
```
**Electron-First Deployment** (Default)
```bash
# Run packaged application (no special flags needed)
MyApp.exe
```
## 🔍 Process Lifecycle Management
### Automatic Cleanup
ElectronNET.Core automatically manages process lifecycle:
- **Graceful shutdown** when main window is closed
- **Proper cleanup** of child processes
- **Error handling** for process failures
- **Cross-platform compatibility** for process management
### Manual Control
Access runtime controller for advanced scenarios:
```csharp
var runtime = ElectronNetRuntime.RuntimeController;
// Wait for Electron to be ready
await runtime.WaitReadyTask;
// Stop Electron runtime
await runtime.Stop();
await runtime.WaitStoppedTask;
```
## 🛠 Troubleshooting
### Common Startup Issues
**"Electron process not found"**
- Ensure Node.js 22.x is installed
- Check that .NET build succeeded
- Verify RuntimeIdentifier is set correctly
**"Port conflicts"**
- Use different ports for different startup modes
- Check that no other instances are running
- Verify firewall settings
**"Process won't terminate"**
- Use dotnet-first mode for better cleanup
- Check for unhandled exceptions
- Verify all windows are properly closed
## 💡 Best Practices
### Choose the Right Mode
- **Development**: Use .NET-first for C# debugging, Electron-first for Node.js debugging
- **Production**: Use .NET-first for better process control, Electron-first for traditional behavior
- **Cross-platform**: Use .NET-first for consistent behavior across platforms
### Environment Configuration
```xml
<!-- .csproj -->
<PropertyGroup>
<ElectronNETCoreEnvironment>Production</ElectronNETCoreEnvironment>
</PropertyGroup>
```
## 🚀 Next Steps
- **[Debugging](Debugging.md)** - Debug different startup modes
- **[Package Building](Package-Building.md)** - Package for different deployment scenarios
- **[Migration Guide](../Core/Migration-Guide.md)** - Update existing apps for new startup methods
## 🎯 Summary
The flexible startup system ensures ElectronNET.Core works optimally in every scenario while providing the control and debugging experience .NET developers expect. Choose the appropriate mode based on your development workflow and deployment requirements.

View File

@@ -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.

View File

@@ -1,52 +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)
- [Migration Checks](Core/Migration-Checks.md)
- [Advanced Migration](Core/Advanced-Migration-Topics.md)
# Getting Started
- [System Requirements](GettingStarted/System-Requirements.md)
- [With ASP.Net](GettingStarted/ASP.Net.md)
- [With a Console App](GettingStarted/Console-App.md)
# Using Electron.NET
- [Configuration](Using/Configuration.md)
- [Startup-Methods](Using/Startup-Methods.md)
- [Debugging](Using/Debugging.md)
- [Package Building](Using/Package-Building.md)
- [Adding a `custom_main.js`](Using/Custom_main.md)
# API Reference
- [API Overview](API/Overview.md)
- [Electron.App](API/App.md)
- [Electron.Dialog](API/Dialog.md)
- [Electron.Menu](API/Menu.md)
- [Electron.WindowManager](API/WindowManager.md)
- [Electron.Shell](API/Shell.md)
- [Electron.Screen](API/Screen.md)
- [Electron.Notification](API/Notification.md)
- [Electron.Tray](API/Tray.md)
- [Electron.Clipboard](API/Clipboard.md)
- [Electron.Dock](API/Dock.md)
- [Electron.HostHook](API/HostHook.md)
- [Electron.IpcMain](API/IpcMain.md)
- [Electron.GlobalShortcut](API/GlobalShortcut.md)
- [Electron.AutoUpdater](API/AutoUpdater.md)
- [Electron.NativeTheme](API/NativeTheme.md)
- [Electron.PowerMonitor](API/PowerMonitor.md)
# Release Information
- [Package Description](RelInfo/Package-Description.md)
- [Changelog](RelInfo/Changelog.md)

Binary file not shown.

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -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);

View File

@@ -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;
}
}

View File

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

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace></RootNamespace>
<NoWarn>CS0649;CS0169</NoWarn>
<NukeRootDirectory>..</NukeRootDirectory>
@@ -11,13 +11,11 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build" Version="18.0.2" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="18.0.2" />
<PackageReference Include="Nuke.Common" Version="10.1.0" />
<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>

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -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 systems notification area.
/// </summary>
public static Tray Tray
{
get
{
return Tray.Instance;
}
}
/// <summary>
/// Detect keyboard events when the application does not have keyboard focus.
/// </summary>
public static GlobalShortcut GlobalShortcut
{
get
{
return GlobalShortcut.Instance;
}
}
/// <summary>
/// Manage files and URLs using their default applications.
/// </summary>
public static Shell Shell
{
get
{
return Shell.Instance;
}
}
/// <summary>
/// Retrieve information about screen size, displays, cursor position, etc.
/// </summary>
public static Screen Screen
{
get
{
return Screen.Instance;
}
}
/// <summary>
/// Perform copy and paste operations on the system clipboard.
/// </summary>
public static Clipboard Clipboard
{
get
{
return Clipboard.Instance;
}
}
/// <summary>
/// Allows you to execute native JavaScript/TypeScript code from the host process.
///
/// It is only possible if the Electron.NET CLI has previously added an
/// ElectronHostHook directory:
/// <c>electronize add HostHook</c>
/// </summary>
public static HostHook HostHook
{
get
{
return HostHook.Instance;
}
}
/// <summary>
/// Allows you to execute native Lock and Unlock process.
/// </summary>
public static PowerMonitor PowerMonitor
{
get
{
return PowerMonitor.Instance;
}
}
/// <summary>
/// Read and respond to changes in Chromium's native color theme.
/// </summary>
public static NativeTheme NativeTheme
{
get
{
return NativeTheme.Instance;
}
}
/// <summary>
/// Control your app in the macOS dock.
/// </summary>
public static Dock Dock
{
get
{
return Dock.Instance;
}
}
/// <summary>
/// Electeon extensions to the Nodejs process object.
/// </summary>
public static Process Process
{
get
{
return Process.Instance;
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,116 +0,0 @@
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class Display
{
/// <summary>
/// Gets or sets the accelerometer support status; can be 'available', 'unavailable', or 'unknown'.
/// </summary>
public string AccelerometerSupport { get; set; }
/// <summary>
/// Gets or sets the bounds.
/// </summary>
/// <value>
/// The bounds of the display in DIP points.
/// </value>
public Rectangle Bounds { get; set; }
/// <summary>
/// Gets or sets the number of bits per pixel.
/// </summary>
public int ColorDepth { get; set; }
/// <summary>
/// Gets or sets the color space description used for color conversions.
/// </summary>
public string ColorSpace { get; set; }
/// <summary>
/// Gets or sets the number of bits per color component.
/// </summary>
public int DepthPerComponent { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the display is detected by the system.
/// </summary>
public bool Detected { get; set; }
/// <summary>
/// Gets or sets the display refresh rate.
/// </summary>
public double DisplayFrequency { get; set; }
/// <summary>
/// Gets or sets the unique identifier associated with the display. A value of -1 means the display is invalid or the correct id is not yet known, and a value of -10 means the display is a virtual display assigned to a unified desktop.
/// </summary>
public long Id { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the display is internal (true) or external (false).
/// </summary>
public bool Internal { get; set; }
/// <summary>
/// Gets or sets the user-friendly label, determined by the platform.
/// </summary>
public string Label { get; set; }
/// <summary>
/// Gets or sets the maximum cursor size in native pixels.
/// </summary>
public Size MaximumCursorSize { get; set; }
/// <summary>
/// Gets or sets the display's origin in pixel coordinates. Only available on windowing systems that position displays in pixel coordinates (e.g., X11).
/// </summary>
public Point NativeOrigin { get; set; }
/// <summary>
/// Gets or sets the screen rotation in clock-wise degrees. Can be 0, 90, 180, or 270.
/// </summary>
public int Rotation { get; set; }
/// <summary>
/// Gets or sets the output device's pixel scale factor.
/// </summary>
public double ScaleFactor { get; set; }
/// <summary>
/// Gets or sets the touch support status; can be 'available', 'unavailable', or 'unknown'.
/// </summary>
public string TouchSupport { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the display is monochrome.
/// </summary>
public bool Monochrome { get; set; }
/// <summary>
/// Gets or sets the size.
/// </summary>
/// <value>
/// The size.
/// </value>
public Size Size { get; set; }
/// <summary>
/// Gets or sets the work area of the display in DIP points.
/// </summary>
/// <value>
/// The work area of the display in DIP points.
/// </value>
public Rectangle WorkArea { get; set; }
/// <summary>
/// Gets or sets the size of the work area.
/// </summary>
/// <value>
/// The size of the work area.
/// </value>
public Size WorkAreaSize { get; set; }
}
}

View File

@@ -1,69 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API
{
/// <summary>
///
/// </summary>
public enum DisplayBalloonIconType
{
none,
info,
warning,
error,
custom
}
/// <remarks>Up-to-date with Electron API 39.2</remarks>
[SupportedOSPlatform("Windows")]
public class DisplayBalloonOptions
{
/// <summary>
/// Gets or sets the icon.
/// </summary>
/// <value>
/// The icon.
/// </value>
public string Icon { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>
/// The title.
/// </value>
public string Title { get; set; }
/// <summary>
/// Gets or sets the content.
/// </summary>
/// <value>
/// The content.
/// </value>
public string Content { get; set; }
/// <summary>
/// (optional) - Icon type for the balloon: none, info, warning, error or custom.
/// Default is custom.
/// </summary>
public DisplayBalloonIconType IconType { get; set; } = DisplayBalloonIconType.custom;
/// <summary>
/// (optional) - Use the large version of the icon. Default is true.
/// Maps to Windows NIIF_LARGE_ICON.
/// </summary>
public bool LargeIcon { get; set; } = true;
/// <summary>
/// (optional) - Do not play the associated sound. Default is false.
/// Maps to Windows NIIF_NOSOUND.
/// </summary>
public bool NoSound { get; set; }
/// <summary>
/// (optional) - Do not display the balloon if the current user is in "quiet time".
/// Default is false. Maps to Windows NIIF_RESPECT_QUIET_TIME.
/// </summary>
public bool RespectQuietTime { get; set; }
}
}

View File

@@ -1,28 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public enum FileIconSize
{
/// <summary>
/// small - 16x16 (per app.getFileIcon size mapping).
/// </summary>
small,
/// <summary>
/// normal - 32x32 (per app.getFileIcon size mapping).
/// </summary>
normal,
/// <summary>
/// large - 48x48 on Linux, 32x32 on Windows, unsupported on macOS (per app.getFileIcon size mapping).
/// </summary>
[SupportedOSPlatform("Linux")]
[SupportedOSPlatform("Windows")]
large
}
}

View File

@@ -1,100 +0,0 @@
using System.Text.Json.Serialization;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Graphics Feature Status from chrome://gpu/ as returned by app.getGPUFeatureStatus().
/// Each field reflects the status of a GPU capability reported by Chromium.
///
/// Possible values for all fields:
/// - disabled_software: Software only. Hardware acceleration disabled (yellow)
/// - disabled_off: Disabled (red)
/// - disabled_off_ok: Disabled (yellow)
/// - unavailable_software: Software only, hardware acceleration unavailable (yellow)
/// - unavailable_off: Unavailable (red)
/// - unavailable_off_ok: Unavailable (yellow)
/// - enabled_readback: Hardware accelerated but at reduced performance (yellow)
/// - enabled_force: Hardware accelerated on all pages (green)
/// - enabled: Hardware accelerated (green)
/// - enabled_on: Enabled (green)
/// - enabled_force_on: Force enabled (green)
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class GPUFeatureStatus
{
/// <summary>
/// Gets or sets the status for Canvas.
/// </summary>
[JsonPropertyName("2d_canvas")]
public string Canvas { get; set; }
/// <summary>
/// Gets or sets the status for Flash.
/// </summary>
[JsonPropertyName("flash_3d")]
public string Flash3D { get; set; }
/// <summary>
/// Gets or sets the status for Flash Stage3D.
/// </summary>
[JsonPropertyName("flash_stage3d")]
public string FlashStage3D { get; set; }
/// <summary>
/// Gets or sets the status for Flash Stage3D Baseline profile.
/// </summary>
[JsonPropertyName("flash_stage3d_baseline")]
public string FlashStage3dBaseline { get; set; }
/// <summary>
/// Gets or sets the status for Compositing.
/// </summary>
[JsonPropertyName("gpu_compositing")]
public string GpuCompositing { get; set; }
/// <summary>
/// Gets or sets the status for Multiple Raster Threads.
/// </summary>
[JsonPropertyName("multiple_raster_threads")]
public string MultipleRasterThreads { get; set; }
/// <summary>
/// Gets or sets the status for Native GpuMemoryBuffers.
/// </summary>
[JsonPropertyName("native_gpu_memory_buffers")]
public string NativeGpuMemoryBuffers { get; set; }
/// <summary>
/// Gets or sets the status for Rasterization.
/// </summary>
public string Rasterization { get; set; }
/// <summary>
/// Gets or sets the status for Video Decode.
/// </summary>
[JsonPropertyName("video_decode")]
public string VideoDecode { get; set; }
/// <summary>
/// Gets or sets the status for Video Encode.
/// </summary>
[JsonPropertyName("video_encode")]
public string VideoEncode { get; set; }
/// <summary>
/// Gets or sets the status for VPx Video Decode.
/// </summary>
[JsonPropertyName("vpx_decode")]
public string VpxDecode { get; set; }
/// <summary>
/// Gets or sets the status for WebGL.
/// </summary>
public string Webgl { get; set; }
/// <summary>
/// Gets or sets the status for WebGL2.
/// </summary>
public string Webgl2 { get; set; }
}
}

View File

@@ -1,18 +0,0 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// Represents a postData item for loadURL/webContents.loadURL options.
/// Valid types per Electron docs: 'rawData' and 'file'.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public interface IPostData
{
/// <summary>
/// One of the following:
/// rawData - <see cref="UploadRawData"/>.
/// file - <see cref="UploadFile"/>.
/// Based on Electron postData definitions.
/// </summary>
public string Type { get; }
}
}

View File

@@ -1,162 +0,0 @@
using System.Collections.Generic;
namespace ElectronNET.API.Entities
{
using ElectronNET.Converter;
using System.Text.Json.Serialization;
/// <summary>
/// Input event payload as used by webContents 'input-event' and 'before-input-event'.
/// Fields map to KeyboardEvent properties where noted, and type/modifiers follow Electron's InputEvent structure.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class InputEvent
{
/// <summary>
/// Equivalent to KeyboardEvent.key.
/// </summary>
public string Key { get; set; } = "";
/// <summary>
/// Equivalent to KeyboardEvent.code.
/// </summary>
public string Code { get; set; } = "";
/// <summary>
/// Equivalent to KeyboardEvent.repeat.
/// </summary>
public bool IsAutoRepeat { get; set; } = false;
/// <summary>
/// Equivalent to KeyboardEvent.isComposing.
/// </summary>
public bool IsComposing { get; set; } = false;
/// <summary>
/// Equivalent to KeyboardEvent.shiftKey.
/// </summary>
public bool Shift { get; set; } = false;
/// <summary>
/// Equivalent to KeyboardEvent.controlKey.
/// </summary>
public bool Control { get; set; } = false;
/// <summary>
/// Equivalent to KeyboardEvent.altKey.
/// </summary>
public bool Alt { get; set; } = false;
/// <summary>
/// Equivalent to KeyboardEvent.metaKey.
/// </summary>
public bool Meta { get; set; } = false;
/// <summary>
/// Equivalent to KeyboardEvent.location.
/// </summary>
public int Location { get; set; } = 0;
/// <summary>
/// An array of modifiers of the event, can be `shift`, `control`, `ctrl`, `alt`,
/// `meta`, `command`, `cmd`, `iskeypad`, `isautorepeat`, `leftbuttondown`,
/// `middlebuttondown`, `rightbuttondown`, `capslock`, `numlock`, `left`, `right`.
/// </summary>
[JsonConverter(typeof(ModifierTypeListConverter))]
public List<ModifierType> Modifiers { get; set; }
/// <summary>
/// For MouseInputEvent: The x-coordinate of the event (Integer).
/// </summary>
public int? X { get; set; }
/// <summary>
/// For MouseInputEvent: The y-coordinate of the event (Integer).
/// </summary>
public int? Y { get; set; }
/// <summary>
/// For MouseInputEvent: The button pressed, can be 'left', 'middle', or 'right' (optional).
/// </summary>
public string Button { get; set; }
/// <summary>
/// For MouseInputEvent: Global x in screen coordinates (Integer, optional).
/// </summary>
public int? GlobalX { get; set; }
/// <summary>
/// For MouseInputEvent: Global y in screen coordinates (Integer, optional).
/// </summary>
public int? GlobalY { get; set; }
/// <summary>
/// For MouseInputEvent: Movement delta on x-axis since last event (Integer, optional).
/// </summary>
public int? MovementX { get; set; }
/// <summary>
/// For MouseInputEvent: Movement delta on y-axis since last event (Integer, optional).
/// </summary>
public int? MovementY { get; set; }
/// <summary>
/// For MouseInputEvent: Click count (Integer, optional).
/// </summary>
public int? ClickCount { get; set; }
/// <summary>
/// For MouseWheelInputEvent: Horizontal scroll delta (Integer, optional).
/// </summary>
public int? DeltaX { get; set; }
/// <summary>
/// For MouseWheelInputEvent: Vertical scroll delta (Integer, optional).
/// </summary>
public int? DeltaY { get; set; }
/// <summary>
/// For MouseWheelInputEvent: Horizontal wheel ticks (Integer, optional).
/// </summary>
public int? WheelTicksX { get; set; }
/// <summary>
/// For MouseWheelInputEvent: Vertical wheel ticks (Integer, optional).
/// </summary>
public int? WheelTicksY { get; set; }
/// <summary>
/// For MouseWheelInputEvent: Horizontal acceleration ratio (Integer, optional).
/// </summary>
public int? AccelerationRatioX { get; set; }
/// <summary>
/// For MouseWheelInputEvent: Vertical acceleration ratio (Integer, optional).
/// </summary>
public int? AccelerationRatioY { get; set; }
/// <summary>
/// For MouseWheelInputEvent: True if wheel deltas are precise (optional).
/// </summary>
public bool? HasPreciseScrollingDeltas { get; set; }
/// <summary>
/// For MouseWheelInputEvent: True if the target can scroll (optional).
/// </summary>
public bool? CanScroll { get; set; }
/// <summary>
/// Can be `undefined`, `mouseDown`, `mouseUp`, `mouseMove`, `mouseEnter`,
/// `mouseLeave`, `contextMenu`, `mouseWheel`, `rawKeyDown`, `keyDown`, `keyUp`, `char`,
/// `gestureScrollBegin`, `gestureScrollEnd`, `gestureScrollUpdate`,
/// `gestureFlingStart`, `gestureFlingCancel`, `gesturePinchBegin`,
/// `gesturePinchEnd`, `gesturePinchUpdate`, `gestureTapDown`, `gestureShowPress`,
/// `gestureTap`, `gestureTapCancel`, `gestureShortPress`, `gestureLongPress`,
/// `gestureLongTap`, `gestureTwoFingerTap`, `gestureTapUnconfirmed`,
/// `gestureDoubleTap`, `touchStart`, `touchMove`, `touchEnd`, `touchCancel`,
/// `touchScrollStarted`, `pointerDown`, `pointerUp`, `pointerMove`,
/// `pointerRawUpdate`, `pointerCancel` or `pointerCausedUaAction`.
/// </summary>
public InputEventType Type { get; set; }
}
}

View File

@@ -1,29 +0,0 @@
using System.Text.Json.Serialization;
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Jump List category definition used with app.setJumpList(categories).
/// Matches Electron's JumpListCategory structure.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
[SupportedOSPlatform("windows")]
public class JumpListCategory
{
/// <summary>
/// Gets or sets the name; must be set if <c>type</c> is <c>custom</c>, otherwise it should be omitted.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the array of <see cref="JumpListItem"/> objects if <c>type</c> is <c>tasks</c> or <c>custom</c>; otherwise it should be omitted.
/// </summary>
public JumpListItem[] Items { get; set; }
/// <summary>
/// Gets or sets the category type. One of: <c>tasks</c> | <c>frequent</c> | <c>recent</c> | <c>custom</c>.
/// </summary>
public JumpListCategoryType Type { get; set; }
}
}

View File

@@ -1,65 +0,0 @@
using System.Text.Json.Serialization;
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Jump List item used in app.setJumpList(categories) on Windows.
/// Matches Electron's JumpListItem structure.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
[SupportedOSPlatform("windows")]
public class JumpListItem
{
/// <summary>
/// Gets or sets the command line arguments when <c>program</c> is executed. Should only be set if <c>type</c> is <c>task</c>.
/// </summary>
public string Args { get; set; }
/// <summary>
/// Gets or sets the description of the task (displayed in a tooltip). Should only be set if <c>type</c> is <c>task</c>. Maximum length 260 characters.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the index of the icon in the resource file. If a resource file contains multiple
/// icons this value can be used to specify the zero-based index of the icon that
/// should be displayed for this task. If a resource file contains only one icon,
/// this property should be set to zero.
/// </summary>
public int IconIndex { get; set; }
/// <summary>
/// Gets or sets the absolute path to an icon to be displayed in a Jump List, which can be an
/// arbitrary resource file that contains an icon(e.g. .ico, .exe, .dll). You can
/// usually specify process.execPath to show the program icon.
/// </summary>
public string IconPath { get; set; }
/// <summary>
/// Gets or sets the path of the file to open; should only be set if <c>type</c> is <c>file</c>.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Gets or sets the path of the program to execute, usually specify process.execPath
/// which opens the current program. Should only be set if <c>type</c> is <c>task</c>.
/// </summary>
public string Program { get; set; }
/// <summary>
/// Gets or sets the text to be displayed for the item in the Jump List. Should only be set if <c>type</c> is <c>task</c>.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the item type. One of: <c>task</c> | <c>separator</c> | <c>file</c>.
/// </summary>
public JumpListItemType Type { get; set; }
/// <summary>
/// Gets or sets the working directory. Default is empty.
/// </summary>
public string WorkingDirectory { get; set; }
}
}

View File

@@ -1,37 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Windows launch entry as returned by app.getLoginItemSettings().launchItems.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
[SupportedOSPlatform("windows")]
public class LoginItemLaunchItem
{
/// <summary>
/// Name value of a registry entry.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The executable to an app that corresponds to a registry entry.
/// </summary>
public string Path { get; set; }
/// <summary>
/// The command-line arguments to pass to the executable.
/// </summary>
public string[] Args { get; set; }
/// <summary>
/// One of <c>user</c> or <c>machine</c>. Indicates whether the registry entry is under HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE.
/// </summary>
public string Scope { get; set; }
/// <summary>
/// True if the app registry key is startup approved and therefore shows as enabled in Task Manager and Windows settings.
/// </summary>
public bool Enabled { get; set; }
}
}

View File

@@ -1,65 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Return object for app.getLoginItemSettings() on macOS and Windows.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class LoginItemSettings
{
/// <summary>
/// <see langword="true"/> if the app is set to open at login.
/// </summary>
public bool OpenAtLogin { get; set; }
/// <summary>
/// <see langword="true"/> if the app is set to open as hidden at login. Deprecated on macOS 13 and up; not available
/// on <see href="https://www.electronjs.org/docs/tutorial/mac-app-store-submission-guide">MAS builds</see>.
/// </summary>
[SupportedOSPlatform("macos")]
public bool OpenAsHidden { get; set; }
/// <summary>
/// <see langword="true"/> if the app was opened at login automatically. This setting is not available
/// on <see href="https://www.electronjs.org/docs/tutorial/mac-app-store-submission-guide">MAS builds</see>.
/// </summary>
[SupportedOSPlatform("macos")]
public bool WasOpenedAtLogin { get; set; }
/// <summary>
/// <see langword="true"/> if the app was opened as a hidden login item. This indicates that the app should not
/// open any windows at startup. Deprecated on macOS 13 and up; not available on
/// <see href="https://www.electronjs.org/docs/tutorial/mac-app-store-submission-guide">MAS builds</see>.
/// </summary>
[SupportedOSPlatform("macos")]
public bool WasOpenedAsHidden { get; set; }
/// <summary>
/// <see langword="true"/> if the app was opened as a login item that should restore the state from the previous
/// session. This indicates that the app should restore the windows that were open the last time the app was closed.
/// Deprecated on macOS 13 and up; not available on <see href="https://www.electronjs.org/docs/tutorial/mac-app-store-submission-guide">MAS builds</see>.
/// </summary>
[SupportedOSPlatform("macos")]
public bool RestoreState { get; set; }
/// <summary>
/// macOS status: one of <c>not-registered</c>, <c>enabled</c>, <c>requires-approval</c>, or <c>not-found</c>.
/// </summary>
[SupportedOSPlatform("macos")]
public string Status { get; set; }
/// <summary>
/// Windows: true if app is set to open at login and its run key is not deactivated.
/// Differs from <c>OpenAtLogin</c> as it ignores the <c>args</c> option; this is true if the given executable would be launched at login with any arguments.
/// </summary>
[SupportedOSPlatform("windows")]
public bool ExecutableWillLaunchAtLogin { get; set; }
/// <summary>
/// Windows launch entries found in registry.
/// </summary>
[SupportedOSPlatform("windows")]
public LoginItemLaunchItem[] LaunchItems { get; set; }
}
}

View File

@@ -1,34 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
public class LoginItemSettingsOptions
{
/// <summary>
/// The executable path to compare against. Defaults to process.execPath.
/// </summary>
[SupportedOSPlatform("windows")]
public string Path { get; set; }
/// <summary>
/// The command-line arguments to compare against. Defaults to an empty array.
/// </summary>
[SupportedOSPlatform("windows")]
public string[] Args { get; set; }
/// <summary>
/// The type of service to query on macOS 13+. Defaults to 'mainAppService'. Only available on macOS 13 and up.
/// </summary>
[SupportedOSPlatform("macos")]
public string Type { get; set; }
/// <summary>
/// The name of the service. Required if type is non-default. Only available on macOS 13 and up.
/// </summary>
[SupportedOSPlatform("macos")]
public string ServiceName { get; set; }
}
}

View File

@@ -1,62 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Settings object for app.setLoginItemSettings() on macOS and Windows.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class LoginSettings
{
/// <summary>
/// <see langword="true"/> to open the app at login, <see langword="false"/> to remove the app as a login item.
/// Defaults to <see langword="false"/>.
/// </summary>
public bool OpenAtLogin { get; set; }
/// <summary>
/// <see langword="true"/> to open the app as hidden. Defaults to <see langword="false"/>. The user can edit this
/// setting from the System Preferences so app.getLoginItemSettings().wasOpenedAsHidden should be checked when the app is
/// opened to know the current value. This setting is not available on <see href="https://www.electronjs.org/docs/tutorial/mac-app-store-submission-guide">MAS builds</see> and does not work on macOS 13 and up.
/// </summary>
[SupportedOSPlatform("macos")]
public bool OpenAsHidden { get; set; }
/// <summary>
/// The executable to launch at login. Defaults to process.execPath.
/// </summary>
[SupportedOSPlatform("windows")]
public string Path { get; set; }
/// <summary>
/// The command-line arguments to pass to the executable. Defaults to an empty
/// array.Take care to wrap paths in quotes.
/// </summary>
[SupportedOSPlatform("windows")]
public string[] Args { get; set; }
/// <summary>
/// The type of service to add as a login item. Defaults to 'mainAppService'. Only available on macOS 13 and up.
/// </summary>
[SupportedOSPlatform("macos")]
public string Type { get; set; }
/// <summary>
/// The name of the service. Required if <c>Type</c> is non-default. Only available on macOS 13 and up.
/// </summary>
[SupportedOSPlatform("macos")]
public string ServiceName { get; set; }
/// <summary>
/// Change the startup approved registry key and enable/disable the app in Task Manager and Windows Settings. Defaults to true.
/// </summary>
[SupportedOSPlatform("windows")]
public bool Enabled { get; set; } = true;
/// <summary>
/// Value name to write into registry. Defaults to the app's AppUserModelId().
/// </summary>
[SupportedOSPlatform("windows")]
public string Name { get; set; }
}
}

View File

@@ -1,42 +0,0 @@
namespace ElectronNET.API.Entities;
/// <summary>
/// Margins object used by webContents.print options and webContents.printToPDF.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class Margins
{
/// <summary>
/// Gets or sets the margin type. Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen,
/// you will also need to specify `top`, `bottom`, `left`, and `right`.
/// </summary>
public string MarginType { get; set; }
/// <summary>
/// Gets or sets the top margin of the printed web page. Units depend on API:
/// - webContents.print: pixels
/// - webContents.printToPDF: inches
/// </summary>
public double Top { get; set; }
/// <summary>
/// Gets or sets the bottom margin of the printed web page. Units depend on API:
/// - webContents.print: pixels
/// - webContents.printToPDF: inches
/// </summary>
public double Bottom { get; set; }
/// <summary>
/// Gets or sets the left margin of the printed web page. Units depend on API:
/// - webContents.print: pixels
/// - webContents.printToPDF: inches
/// </summary>
public double Left { get; set; }
/// <summary>
/// Gets or sets the right margin of the printed web page. Units depend on API:
/// - webContents.print: pixels
/// - webContents.printToPDF: inches
/// </summary>
public double Right { get; set; }
}

View File

@@ -1,28 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Process memory info as returned by process.getProcessMemoryInfo().
/// Values are reported in Kilobytes.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class MemoryInfo
{
/// <summary>
/// Gets or sets the amount of memory currently pinned to actual physical RAM.
/// </summary>
public int WorkingSetSize { get; set; }
/// <summary>
/// Gets or sets the maximum amount of memory that has ever been pinned to actual physical RAM.
/// </summary>
public int PeakWorkingSetSize { get; set; }
/// <summary>
/// Gets or sets the amount of memory not shared by other processes, such as JS heap or HTML content. Windows only.
/// </summary>
[SupportedOSPlatform("windows")]
public int PrivateBytes { get; set; }
}
}

View File

@@ -1,150 +0,0 @@
using System;
using System.Text.Json.Serialization;
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class MenuItem
{
/// <summary>
/// Will be called with click(menuItem, browserWindow, event) when the menu item is
/// clicked.
/// </summary>
[JsonIgnore]
public Action Click { get; set; }
/// <summary>
/// Gets or sets the action (role) of the menu item. When specified, the click property will be ignored.
/// </summary>
public MenuRole Role { get; set; }
/// <summary>
/// Gets or sets the menu item type. Can be normal, separator, submenu, checkbox, radio, header (macOS 14+), or palette (macOS 14+).
/// </summary>
public MenuType Type { get; set; }
/// <summary>
/// Gets or sets the label.
/// </summary>
/// <value>
/// The label.
/// </value>
public string Label { get; set; }
/// <summary>
/// Gets or sets the sublabel.
/// </summary>
/// <value>
/// The sublabel.
/// </value>
[SupportedOSPlatform("macos")]
public string Sublabel { get; set; }
/// <summary>
/// Hover text for this menu item (macOS).
/// </summary>
[SupportedOSPlatform("macos")]
public string ToolTip { get; set; }
/// <summary>
/// Gets or sets the accelerator.
/// </summary>
/// <value>
/// The accelerator.
/// </value>
public string Accelerator { get; set; }
/// <summary>
/// Gets or sets the icon.
/// </summary>
/// <value>
/// The icon.
/// </value>
public string Icon { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the item is enabled. If false, the menu item will be greyed out and unclickable.
/// </summary>
public bool Enabled { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether the item is visible. If false, the menu item will be entirely hidden.
/// </summary>
public bool Visible { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether the accelerator should work when the item is hidden. Default is true (macOS).
/// When false, prevents the accelerator from triggering the item if the item is not visible.
/// </summary>
[SupportedOSPlatform("macos")]
public bool? AcceleratorWorksWhenHidden { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the accelerator should be registered with the system or only displayed (Linux/Windows). Defaults to true.
/// </summary>
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
public bool? RegisterAccelerator { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the item is checked. Should only be specified for checkbox or radio items.
/// </summary>
public bool Checked { get; set; }
/// <summary>
/// Should be specified for submenu type menu items. If submenu is specified, the
/// type: 'submenu' can be omitted.If the value is not a Menu then it will be
/// automatically converted to one using Menu.buildFromTemplate.
/// </summary>
public MenuItem[] Submenu { get; set; }
/// <summary>
/// The item to share when the role is shareMenu (macOS).
/// </summary>
[SupportedOSPlatform("macos")]
public SharingItem SharingItem { get; set; }
/// <summary>
/// Gets or sets a unique id within a single menu. If defined then it can be used as a reference for placement.
/// </summary>
public string Id { get; internal set; }
/// <summary>
/// This field allows fine-grained definition of the specific location within a given menu.
/// </summary>
public string Position { get; set; }
/// <summary>
/// Gets or sets a list of item ids. Inserts this item before the item(s) with the specified id(s).
/// If the referenced item doesn't exist the item will be inserted at the end of the menu.
/// Also implies that this item should be placed in the same group as the referenced item(s).
/// </summary>
public string[] Before { get; set; }
/// <summary>
/// Gets or sets a list of item ids. Inserts this item after the item(s) with the specified id(s).
/// If the referenced item doesn't exist the item will be inserted at the end of the menu.
/// </summary>
public string[] After { get; set; }
/// <summary>
/// Gets or sets a list of item ids. Places this item's containing group before the containing group
/// of the item(s) with the specified id(s).
/// </summary>
public string[] BeforeGroupContaining { get; set; }
/// <summary>
/// Gets or sets a list of item ids. Places this item's containing group after the containing group
/// of the item(s) with the specified id(s).
/// </summary>
public string[] AfterGroupContaining { get; set; }
}
}

View File

@@ -1,48 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Menu item types matching Electron's MenuItem.type values.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public enum MenuType
{
/// <summary>
/// Normal menu item.
/// </summary>
normal,
/// <summary>
/// Separator between items.
/// </summary>
separator,
/// <summary>
/// Submenu container.
/// </summary>
submenu,
/// <summary>
/// Checkbox item.
/// </summary>
checkbox,
/// <summary>
/// Radio item.
/// </summary>
radio,
/// <summary>
/// Header item (macOS 14+).
/// </summary>
[SupportedOSPlatform("macos")]
header,
/// <summary>
/// Palette item (macOS 14+).
/// </summary>
[SupportedOSPlatform("macos")]
palette
}
}

View File

@@ -1,93 +0,0 @@
using System.Text.Json.Serialization;
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Options for dialog.showMessageBox / dialog.showMessageBoxSync.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class MessageBoxOptions
{
/// <summary>
/// Gets or sets the type. Can be "none", "info", "error", "question" or "warning". On Windows, "question" displays the same icon as "info", unless you set an icon using the "icon" option. On macOS, both "warning" and "error" display the same warning icon.
/// </summary>
public MessageBoxType Type { get; set; }
/// <summary>
/// Gets or sets the array of texts for buttons. On Windows, an empty array will result in one button labeled "OK".
/// </summary>
public string[] Buttons { get; set; }
/// <summary>
/// Gets or sets the index of the button in the buttons array which will be selected by default when the message box opens.
/// </summary>
public int DefaultId { get; set; }
/// <summary>
/// Gets or sets the title of the message box; some platforms will not show it.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the content of the message box.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Gets or sets the extra information of the message.
/// </summary>
public string Detail { get; set; }
/// <summary>
/// Gets or sets the checkbox label. If provided, the message box will include a checkbox with the given label.
/// </summary>
public string CheckboxLabel { get; set; }
/// <summary>
/// Gets or sets the initial checked state of the checkbox. Defaults to false.
/// </summary>
public bool CheckboxChecked { get; set; }
/// <summary>
/// Gets or sets the icon for the message box.
/// </summary>
public string Icon { get; set; }
/// <summary>
/// Gets or sets the custom width of the text in the message box.
/// </summary>
[SupportedOSPlatform("macos")]
public int? TextWidth { get; set; }
/// <summary>
/// Gets or sets the index of the button to be used to cancel the dialog via the Esc key. By default this is assigned to the first button with "cancel" or "no" as the label. If no such labeled buttons exist and this option is not set, 0 will be used.
/// </summary>
public int CancelId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to disable Windows command-links behavior (noLink).
/// On Windows Electron will try to figure out which one of the buttons are common buttons (like "Cancel" or "Yes"), and show the others as command links in the dialog. Set to true to disable this behavior.
/// </summary>
[SupportedOSPlatform("windows")]
public bool NoLink { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to normalize the keyboard access keys across platforms. Default is false. Enabling this assumes '&amp;' is used in the button labels for the placement of the keyboard
/// shortcut access key and labels will be converted so they work correctly on each
/// platform, '&amp;' characters are removed on macOS, converted to '_' on Linux, and left
/// untouched on Windows. For example, a button label of "View" will be converted to "Vie_w" on Linux and "View" on macOS and can be selected via Alt-W on Windows and
/// Linux.
/// </summary>
public bool NormalizeAccessKeys { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MessageBoxOptions"/> class.
/// </summary>
/// <param name="message">The message.</param>
public MessageBoxOptions(string message)
{
Message = message;
}
}
}

View File

@@ -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
{
/// <yremarks>Project-specific: JSON converter for NativeImage; no MCP structure equivalent.</yremarks>
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);
}
}
}

View File

@@ -1,22 +0,0 @@
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
[SupportedOSPlatform("macos")]
public class NotificationAction
{
/// <summary>
/// Gets or sets the label for the action.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Gets or sets the type of action; can be 'button'.
/// </summary>
public string Type { get; set; }
}
}

View File

@@ -1,38 +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; }
/// <summary>
/// Error description string.
/// </summary>
public string ErrorDescription { get; set; }
/// <summary>
/// True if the event pertains to the main frame.
/// </summary>
public bool IsMainFrame { get; set; }
/// <summary>
/// The process id for the frame.
/// </summary>
public int FrameProcessId { get; set; }
/// <summary>
/// The routing id for the frame.
/// </summary>
public int FrameRoutingId { get; set; }
}

View File

@@ -1,23 +0,0 @@
namespace ElectronNET.API.Entities;
/// <summary>
/// 'did-navigate' event details for main frame navigation.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class OnDidNavigateInfo
{
/// <summary>
/// The URL navigated to.
/// </summary>
public string Url { get; set; }
/// <summary>
/// HTTP response code (-1 for non-HTTP navigations).
/// </summary>
public int HttpResponseCode { get; set; }
/// <summary>
/// HTTP status text (empty for non-HTTP navigations).
/// </summary>
public string HttpStatusText { get; set; }
}

View File

@@ -1,26 +0,0 @@
using System.Text.Json.Serialization;
namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
public class OpenDevToolsOptions
{
/// <summary>
/// Opens the DevTools with specified dock state. Can be left, right, bottom, undocked, or detach.
/// Defaults to the last used dock state. In undocked mode it's possible to dock back; in detach mode it's not.
/// </summary>
public DevToolsMode Mode { get; set; }
/// <summary>
/// Whether to bring the opened DevTools window to the foreground. Default is true.
/// </summary>
public bool Activate { get; set; } = true;
/// <summary>
/// A title for the DevTools window (only visible in undocked or detach mode).
/// </summary>
public string Title { get; set; }
}
}

View File

@@ -1,32 +0,0 @@
using System.ComponentModel;
using System.Runtime.Versioning;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Controls the behavior of OpenExternal.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public class OpenExternalOptions
{
/// <summary>
/// Gets or sets whether to bring the opened application to the foreground. The default is <see langword="true"/>.
/// </summary>
[SupportedOSPlatform("macos")]
[DefaultValue(true)]
public bool Activate { get; set; } = true;
/// <summary>
/// Gets or sets the working directory.
/// </summary>
[SupportedOSPlatform("windows")]
public string WorkingDirectory { get; set; }
/// <summary>
/// Gets or sets a value indicating a user-initiated launch that enables tracking of frequently used programs and other behaviors. The default is <see langword="false"/>.
/// </summary>
[SupportedOSPlatform("windows")]
[DefaultValue(false)]
public bool LogUsage { get; set; } = false;
}
}

View File

@@ -1,38 +0,0 @@
namespace ElectronNET.API.Entities;
public class PageSize
{
private readonly string _value;
/// <summary>
/// Represents the page size for printing/PDF.
/// Matches Electron semantics: either a named size (e.g. 'A4', 'Letter', 'Legal', 'Tabloid', 'Ledger', etc.)
/// or a custom size specified by Height and Width in inches.
/// </summary>
/// <remarks>Up-to-date with Electron API 39.2</remarks>
public PageSize()
{
}
private PageSize(string value) : this() => _value = value;
/// <summary>
/// Gets or sets the custom page height in inches (when using object form instead of a named size).
/// </summary>
public double Height { get; set; }
/// <summary>
/// Gets or sets the custom page width in inches (when using object form instead of a named size).
/// </summary>
public double Width { get; set; }
/// <summary>
/// Implicit conversion to string to represent named page sizes (e.g. 'A4', 'Letter').
/// </summary>
public static implicit operator string(PageSize pageSize) => pageSize?._value;
/// <summary>
/// Implicit conversion from string to represent named page sizes (e.g. 'A4', 'Letter').
/// </summary>
public static implicit operator PageSize(string value) => new(value);
}

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