mirror of
https://github.com/ElectronNET/Electron.NET.git
synced 2026-02-04 13:44:47 +00:00
Compare commits
374 Commits
23.6.2-alp
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8009348941 | ||
|
|
b3b124bde1 | ||
|
|
21226e1ef0 | ||
|
|
7174118a3e | ||
|
|
092789a5ec | ||
|
|
bff3fffcbd | ||
|
|
456135a562 | ||
|
|
300f52510c | ||
|
|
d85a64f515 | ||
|
|
53698d1d44 | ||
|
|
04a224aa4f | ||
|
|
891da140b7 | ||
|
|
17f761d184 | ||
|
|
9f6489891e | ||
|
|
c8f1cdf59f | ||
|
|
6c95dfd476 | ||
|
|
b180fc2ea8 | ||
|
|
682a1c38ed | ||
|
|
809b0a6be7 | ||
|
|
ae3f755648 | ||
|
|
7e6760a428 | ||
|
|
29fdbb5315 | ||
|
|
36bba6a49f | ||
|
|
44a010e0ed | ||
|
|
25770db138 | ||
|
|
1c99ab02cc | ||
|
|
73c56e2450 | ||
|
|
30037fce69 | ||
|
|
69048d5565 | ||
|
|
d9c8e04b5c | ||
|
|
368ef412bb | ||
|
|
cb20fbad25 | ||
|
|
89cdf2f55b | ||
|
|
1c62c1f132 | ||
|
|
d3e3188681 | ||
|
|
4f95043309 | ||
|
|
13f1203ccc | ||
|
|
9d0378798b | ||
|
|
1d6ef7a250 | ||
|
|
2d6d4e2320 | ||
|
|
df8e269d5c | ||
|
|
bdfbcd5b77 | ||
|
|
19e785f53f | ||
|
|
0b453177b5 | ||
|
|
8ed7f27722 | ||
|
|
321b8cd9e5 | ||
|
|
b326f863d8 | ||
|
|
f148fe6a14 | ||
|
|
515d325731 | ||
|
|
f32a40fe17 | ||
|
|
c53a5a9163 | ||
|
|
8d4cdddc46 | ||
|
|
70e8f85123 | ||
|
|
5a7cbd972f | ||
|
|
33da428c45 | ||
|
|
f1b4766360 | ||
|
|
e070759645 | ||
|
|
49eaa5e129 | ||
|
|
b3f5a3c52b | ||
|
|
0d732ce99e | ||
|
|
218b99808b | ||
|
|
7f507a6d86 | ||
|
|
81b3793966 | ||
|
|
1baa5c6200 | ||
|
|
5f76804065 | ||
|
|
70ffebf39d | ||
|
|
0a54735f35 | ||
|
|
1ac371b3da | ||
|
|
e854451043 | ||
|
|
331c2f548c | ||
|
|
b00adcbd38 | ||
|
|
ed6d24dbb1 | ||
|
|
2c82206c62 | ||
|
|
d0eb0880b1 | ||
|
|
0321804128 | ||
|
|
f548ff08d4 | ||
|
|
bbc7c79d5a | ||
|
|
2389ae32bd | ||
|
|
42fecbdc98 | ||
|
|
95e02e2655 | ||
|
|
153625ba51 | ||
|
|
c97f914e7a | ||
|
|
d95b41fbae | ||
|
|
2b2b26e13b | ||
|
|
9bb2adca78 | ||
|
|
88d2daacb1 | ||
|
|
c90f003519 | ||
|
|
daa9f399e9 | ||
|
|
6246b44d68 | ||
|
|
347c1ef0e4 | ||
|
|
7c8eeef225 | ||
|
|
44a820e285 | ||
|
|
8ccc7bfdd0 | ||
|
|
cf185fd2fb | ||
|
|
4ee11aaeae | ||
|
|
f1063bbe98 | ||
|
|
7c39d28f81 | ||
|
|
e52bf69dee | ||
|
|
46d395ad12 | ||
|
|
c0e3a595c3 | ||
|
|
65db66b4e9 | ||
|
|
ce8a86baf5 | ||
|
|
7eaf84a021 | ||
|
|
90f5f5dbe2 | ||
|
|
e09ef35be4 | ||
|
|
dae521180f | ||
|
|
c81ed54fff | ||
|
|
276ce8f4dc | ||
|
|
20212cdca7 | ||
|
|
0acdc65271 | ||
|
|
c92a54fbda | ||
|
|
4de7760556 | ||
|
|
3821ca60ea | ||
|
|
59887cce5f | ||
|
|
77834d0f2e | ||
|
|
6761119241 | ||
|
|
41d9f0afc7 | ||
|
|
1d554fda60 | ||
|
|
2f4d37d823 | ||
|
|
1815951092 | ||
|
|
aa483ebaa4 | ||
|
|
9b4e0e4504 | ||
|
|
d05191d1e2 | ||
|
|
ef41329a91 | ||
|
|
edafa8ccdb | ||
|
|
55c035323b | ||
|
|
2e5c6200a6 | ||
|
|
be518a7a10 | ||
|
|
9e9558b837 | ||
|
|
5f6e4a9e9d | ||
|
|
b89c08ee96 | ||
|
|
8ff875435b | ||
|
|
bfad0cd45a | ||
|
|
91ed116cb1 | ||
|
|
54eac4b521 | ||
|
|
ac05ded844 | ||
|
|
5434b0ec8e | ||
|
|
20acd31f1a | ||
|
|
f53d071bd9 | ||
|
|
2cf3095450 | ||
|
|
0ec791da9d | ||
|
|
0580942a59 | ||
|
|
8e8d88c48f | ||
|
|
61476e3ca4 | ||
|
|
9488576d8f | ||
|
|
ff1b802838 | ||
|
|
c98ad58290 | ||
|
|
a30239e3a6 | ||
|
|
17f24749cd | ||
|
|
7558037b91 | ||
|
|
e4485fd483 | ||
|
|
1a964b405e | ||
|
|
dfcb2345f3 | ||
|
|
3f10d6b5dd | ||
|
|
90c3eb2c88 | ||
|
|
dbf76a1d6d | ||
|
|
8e7892ebd4 | ||
|
|
30b547b8d3 | ||
|
|
30b4d92291 | ||
|
|
6c9027faf3 | ||
|
|
c712027ea3 | ||
|
|
7889057022 | ||
|
|
68c50f1c1e | ||
|
|
1006355bb7 | ||
|
|
12c5391164 | ||
|
|
8ba24c0f2f | ||
|
|
bb7ae8d711 | ||
|
|
385dcfbf52 | ||
|
|
515430ff96 | ||
|
|
a6d67a4dfe | ||
|
|
946b2af81a | ||
|
|
1e483e9cc4 | ||
|
|
5305e17ba9 | ||
|
|
442084a3e5 | ||
|
|
cd205edabb | ||
|
|
10bf461b51 | ||
|
|
5b0ab76d38 | ||
|
|
349762bd5e | ||
|
|
0b49467186 | ||
|
|
6fa65aa149 | ||
|
|
816e9c0fe9 | ||
|
|
c81b0e537f | ||
|
|
b89e3caa17 | ||
|
|
e8c5de63c9 | ||
|
|
d7b9174853 | ||
|
|
5ba4ab24d5 | ||
|
|
c6ff957d9a | ||
|
|
c37f98dcd6 | ||
|
|
0188051d6c | ||
|
|
3eb8507985 | ||
|
|
546668a2c0 | ||
|
|
68feffba02 | ||
|
|
12d2fcb484 | ||
|
|
979cf72d4c | ||
|
|
14bf7fdcd8 | ||
|
|
f89f2e7591 | ||
|
|
9a0a494bc5 | ||
|
|
41a2b075c9 | ||
|
|
adc1e81743 | ||
|
|
d8062aae00 | ||
|
|
0522bc425b | ||
|
|
168eceac8c | ||
|
|
4736bc640c | ||
|
|
18b1317fc5 | ||
|
|
dfe04f14d0 | ||
|
|
9d6861ffcd | ||
|
|
d8b0d0443d | ||
|
|
71ced8db56 | ||
|
|
fc69598b09 | ||
|
|
60a278c41f | ||
|
|
9d25795b7a | ||
|
|
5b597cc12c | ||
|
|
707c0f5a7b | ||
|
|
bb59bc8365 | ||
|
|
423ea57af7 | ||
|
|
8dcc3721eb | ||
|
|
dc27511aa5 | ||
|
|
dd465baebf | ||
|
|
04210955a3 | ||
|
|
4129cc17a6 | ||
|
|
bc0f601dd8 | ||
|
|
95fd7aa665 | ||
|
|
402147b8ef | ||
|
|
ed7cc434ea | ||
|
|
c5fb5f62d9 | ||
|
|
84989cda25 | ||
|
|
84b3c59353 | ||
|
|
c1e7b84ec6 | ||
|
|
9bb7dcfa62 | ||
|
|
c0e711940d | ||
|
|
d03458094b | ||
|
|
14962e1983 | ||
|
|
d79b73e960 | ||
|
|
21ae89bc70 | ||
|
|
7927a95cb8 | ||
|
|
758e6a41e3 | ||
|
|
61421ddd66 | ||
|
|
98d085f112 | ||
|
|
cf0b12ed0a | ||
|
|
4c3065c64b | ||
|
|
2a6d2117e9 | ||
|
|
93f457dd0f | ||
|
|
6001a3c481 | ||
|
|
4671b9b32a | ||
|
|
de7f98136e | ||
|
|
87668f5606 | ||
|
|
ea688026d0 | ||
|
|
b6b9292478 | ||
|
|
408f83e401 | ||
|
|
689a002dc2 | ||
|
|
f919289628 | ||
|
|
2c544a83e9 | ||
|
|
2b393079ae | ||
|
|
79d3d3f0b1 | ||
|
|
688d6d83cc | ||
|
|
7bcc5c9878 | ||
|
|
0cfadb36f5 | ||
|
|
568c785412 | ||
|
|
2944e69b21 | ||
|
|
8df9eff3bc | ||
|
|
14f43f4574 | ||
|
|
d96eebd5ee | ||
|
|
23fac3263f | ||
|
|
935de8a1a5 | ||
|
|
c2ba55e333 | ||
|
|
be1887c930 | ||
|
|
1852802667 | ||
|
|
5bdabd94ba | ||
|
|
2bc2b4bb70 | ||
|
|
771b1109f7 | ||
|
|
56258d1be8 | ||
|
|
88766adaf6 | ||
|
|
341ebe2bb1 | ||
|
|
0c5cc3ba9d | ||
|
|
bb5779a941 | ||
|
|
0dd263e2b8 | ||
|
|
0a0e26a9dd | ||
|
|
7b812bfae7 | ||
|
|
82814d91d9 | ||
|
|
fcb589d58e | ||
|
|
c914bb8f14 | ||
|
|
bf3e149d43 | ||
|
|
6060e355bd | ||
|
|
868451408c | ||
|
|
bef7a42fbb | ||
|
|
50b49068d8 | ||
|
|
cf87904210 | ||
|
|
0b05b2f5a4 | ||
|
|
1ea4c1343d | ||
|
|
5d5e0b848c | ||
|
|
2d626ab319 | ||
|
|
2e051762dd | ||
|
|
96063bbe7d | ||
|
|
471289813a | ||
|
|
d0d214cd24 | ||
|
|
43ce20d60f | ||
|
|
40d6558613 | ||
|
|
ae12eb49ee | ||
|
|
2a26b46f91 | ||
|
|
78b59f62c9 | ||
|
|
667a1b290e | ||
|
|
c5d9ba0e43 | ||
|
|
f81424978e | ||
|
|
7fcb2f05bd | ||
|
|
69129a6f02 | ||
|
|
bcde1032af | ||
|
|
3a42c479dd | ||
|
|
c6c73a7c8a | ||
|
|
d1db928222 | ||
|
|
b06d20450b | ||
|
|
3811b7ea20 | ||
|
|
9275f2a765 | ||
|
|
feddf5f8f4 | ||
|
|
e4ce61c965 | ||
|
|
1e93d91e66 | ||
|
|
77efea50ed | ||
|
|
5ea368bb16 | ||
|
|
0dca0e90f9 | ||
|
|
c0c3aaebdc | ||
|
|
14722e1f63 | ||
|
|
d6e39fef24 | ||
|
|
74b80b3177 | ||
|
|
0f3f29eae3 | ||
|
|
f634dc45ed | ||
|
|
c6b9de2afa | ||
|
|
9a615ca7e0 | ||
|
|
f9601a6e3e | ||
|
|
8daf4d1498 | ||
|
|
c01ef407af | ||
|
|
dc019adb10 | ||
|
|
f7de17f1ee | ||
|
|
ca748384cf | ||
|
|
4c880cb627 | ||
|
|
e46ba98c8d | ||
|
|
4b9fe4656e | ||
|
|
fdb8be46b7 | ||
|
|
e361367a95 | ||
|
|
7ca40bcaec | ||
|
|
1864c21c10 | ||
|
|
0775b91dd4 | ||
|
|
f55dbc14c0 | ||
|
|
6472f34a75 | ||
|
|
91714f5807 | ||
|
|
6182320003 | ||
|
|
5125ee0109 | ||
|
|
21c17dc82b | ||
|
|
dbcd4ac940 | ||
|
|
286978c523 | ||
|
|
96ae77ceb4 | ||
|
|
a893ccd646 | ||
|
|
2edad2d329 | ||
|
|
7be796f77b | ||
|
|
19da7f47b1 | ||
|
|
d22532488e | ||
|
|
30558dea5f | ||
|
|
464eaca593 | ||
|
|
df3bd122df | ||
|
|
eabcc3a6b6 | ||
|
|
2b5435381f | ||
|
|
0d63383899 | ||
|
|
f31fe19652 | ||
|
|
0a80367e3e | ||
|
|
34761456ad | ||
|
|
e4e96bbcc4 | ||
|
|
1253df3d9a | ||
|
|
b8b634beb3 | ||
|
|
94dc82ec62 | ||
|
|
53ccf4d302 | ||
|
|
bf0bdc8386 | ||
|
|
73a3e331dc | ||
|
|
a15db713ad | ||
|
|
4be5cef3ef | ||
|
|
e2d03d6818 | ||
|
|
0dc8369fb3 |
137
.github/CONTRIBUTING.md
vendored
Normal file
137
.github/CONTRIBUTING.md
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
# Contributing
|
||||
|
||||
## Project Scope
|
||||
|
||||
The Electron.NET project ultimately tries to provide a framework for developing cross-platform client applications on the basis of .NET and Electron. Anything that is related to this goal will be considered. The project aims to be as close to Electron with .NET as a basis as possible. If your contribution does not reflect that goal, the chances of accepting it are limited.
|
||||
|
||||
## Code License
|
||||
|
||||
This is an open source project falling under the [MIT License](../LICENSE). By using, distributing, or contributing to this project, you accept and agree that all code within the Electron.NET project and its libraries are licensed under MIT license.
|
||||
|
||||
## Becoming a Contributor
|
||||
|
||||
Usually appointing someone as a contributor follows this process:
|
||||
|
||||
1. An individual contributes actively via discussions (reporting bugs, giving feedback to existing or opening new issues) and / or pull requests
|
||||
2. The individual is either directly asked, invited or asks for contributor rights on the project
|
||||
3. The individual uses the contribution rights to sustain or increase the active contributions
|
||||
|
||||
Every contributor might have to sign the contributor's license agreement (CLA) to establish a legal trust between the project and its contributors.
|
||||
|
||||
## Working on Electron.NET
|
||||
|
||||
### Issue Discussion
|
||||
|
||||
Discussion of issues should be placed transparently in the issue tracker here on GitHub.
|
||||
|
||||
* [General issues, bugs, new features](https://github.com/ElectronNET/Electron.NET/issues)
|
||||
* [General discussions, help, exchange of ideas](https://github.com/ElectronNET/Electron.NET/discussions)
|
||||
|
||||
### Modifying the code
|
||||
|
||||
Electron.NET and its libraries uses features from the latest versions of C# (e.g., C# 10). You will therefore need a C# compiler that is up for the job.
|
||||
|
||||
1. Fork and clone the repo.
|
||||
2. First try to build the ElectronNET.Core library and see if you get the tests running.
|
||||
3. You will be required to resolve some dependencies via NuGet.
|
||||
|
||||
The build system of Electron.NET uses NUKE.
|
||||
|
||||
### Code Conventions
|
||||
|
||||
Most parts in the Electron.NET project are fairly straight forward. Among these are:
|
||||
|
||||
* Always use statement blocks for control statements, e.g., in a for-loop, if-condition, ...
|
||||
* You may use a simple (throw) statement in case of enforcing contracts on argument
|
||||
* Be explicit about modifiers (some files follow an older convention of the code base, but we settled on the explicit style)
|
||||
|
||||
### Development Workflow
|
||||
|
||||
1. If no issue already exists for the work you'll be doing, create one to document the problem(s) being solved and self-assign.
|
||||
2. Otherwise please let us know that you are working on the problem. Regular status updates (e.g. "still in progress", "no time anymore", "practically done", "pull request issued") are highly welcome.
|
||||
3. Create a new branch—please don't work in the `main` branch directly. It is reserved for releases. We recommend naming the branch to match the issue being addressed (`feature/#777` or `issue-777`).
|
||||
4. Add failing tests for the change you want to make. Tests are crucial and should be taken from W3C (or other specification).
|
||||
5. Fix stuff. Always go from edge case to edge case.
|
||||
6. All tests should pass now. Also your new implementation should not break existing tests.
|
||||
7. Update the documentation to reflect any changes. (or document such changes in the original issue)
|
||||
8. Push to your fork or push your issue-specific branch to the main repository, then submit a pull request against `develop`.
|
||||
|
||||
Just to illustrate the git workflow for Electron.NET a little bit more we've added the following graphs.
|
||||
|
||||
Initially, Electron.NET starts at the `main` branch. This branch should contain the latest stable (or released) version.
|
||||
|
||||
Here we now created a new branch called `develop`. This is the development branch.
|
||||
|
||||
Now active work is supposed to be done. Therefore a new branch should be created. Let's create one:
|
||||
|
||||
```sh
|
||||
git checkout -b feature/#777
|
||||
```
|
||||
|
||||
There may be many of these feature branches. Most of them are also pushed to the server for discussion or synchronization.
|
||||
|
||||
```sh
|
||||
git push -u origin feature/#777
|
||||
```
|
||||
|
||||
Now feature branches may be closed when they are done. Here we simply merge with the feature branch(es). For instance the following command takes the `feature/#777` branch from the server and merges it with the `develop` branch.
|
||||
|
||||
```sh
|
||||
git checkout develop
|
||||
git pull
|
||||
git pull origin feature/#777
|
||||
git push
|
||||
```
|
||||
|
||||
Finally, we may have all the features that are needed to release a new version of Electron.NET. Here we tag the release. For instance for the 1.0 release we use `v1.0`.
|
||||
|
||||
```sh
|
||||
git checkout main
|
||||
git merge develop
|
||||
git tag v1.0
|
||||
```
|
||||
|
||||
(The last part is automatically performed by our CI system. Don't tag manually.)
|
||||
|
||||
### Versioning
|
||||
|
||||
The rules of [semver](http://semver.org/) don't necessarily apply here, but we will try to stay quite close to them.
|
||||
|
||||
Prior to version 1.0.0 we use the following scheme:
|
||||
|
||||
1. MINOR versions for reaching a feature milestone potentially combined with dramatic API changes
|
||||
2. PATCH versions for refinements (e.g. performance improvements, bug fixes)
|
||||
|
||||
After releasing version 1.0.0 the scheme changes to become:
|
||||
|
||||
1. MAJOR versions at maintainers' discretion following significant changes to the codebase (e.g., API changes)
|
||||
2. MINOR versions for backwards-compatible enhancements (e.g., performance improvements)
|
||||
3. PATCH versions for backwards-compatible bug fixes (e.g., spec compliance bugs, support issues)
|
||||
|
||||
#### Code style
|
||||
|
||||
Regarding code style like indentation and whitespace, **follow the conventions you see used in the source already.** In general most of the [C# coding guidelines from Microsoft](https://msdn.microsoft.com/en-us/library/ff926074.aspx) are followed. This project prefers type inference with `var` to explicitly stating (redundant) information.
|
||||
|
||||
It is also important to keep a certain `async`-flow and to always use `ConfigureAwait(false)` in conjunction with an `await` expression.
|
||||
|
||||
## Backwards Compatibility
|
||||
|
||||
We always try to remain backwards compatible beyond the currently supported versions of .NET.
|
||||
|
||||
For instance, in December 2025 there have been activity to remove .NET 6 support from the codebase. We rejected this. Key points:
|
||||
|
||||
1. We have absolutely no need to drop `.net6` support. It doesn't hurt us in any way.
|
||||
2. Many are still using `.net6`, including Electron.NET (non-Core) users. It doesn't make sense to force them to update two things at the same time (.NET + Electron.NET).
|
||||
3. We MUST NOT and NEVER update `Microsoft.Build.Utilities.Core`. This will make Electron.NET stop working on older Visual Studio and MSBuild versions. There's are also no reasons to update it in the first place.
|
||||
|
||||
It's important to note that the Microsoft label of "Out of support" on .NET has almost no practical meaning. We've rarely (if ever) seen any bugs fixed in the same .NET version which mattered. The bugs that all new .NET versions have are much worse than mature .NET versions which are declared as "out of support". Keep in mind that the LTS matters most for active development / ongoing supported projects. If, e.g., a TV has been released a decade ago it most likely won't be patched. Still, you might want to deploy applications to it, which then naturally would involve being based on "out of support" versions of the framework.
|
||||
|
||||
TL;DR: Unless there is a technical reason (e.g., a crucial new API not being available) we should not drop "out of support" .NET versions. At the time of writing (December 2025) the minimum supported .NET version remains at `.net6`.
|
||||
|
||||
## Timeline
|
||||
|
||||
**All of this information is related to ElectronNET.Core pre-v1!**
|
||||
|
||||
We pretty much release whenever we have something new (i.e., do fixes such as a 0.1.1, or add new features, such as a 0.2.0) quite quickly.
|
||||
|
||||
We will go for a 1.0.0 release of this as early as ~mid of January 2026 (unless we find some critical things or want to extend the beta phase for ElectronNET.Core). This should be sufficient time to get some user input and have enough experience to call it stable.
|
||||
BIN
.github/WikiLinks.exe
vendored
Normal file
BIN
.github/WikiLinks.exe
vendored
Normal file
Binary file not shown.
@@ -1,40 +1,36 @@
|
||||
name: CI
|
||||
name: Build and Publish
|
||||
|
||||
on: [push, pull_request]
|
||||
on: [push]
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
|
||||
|
||||
concurrency:
|
||||
group: build-publish-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
runs-on: ubuntu-latest
|
||||
Integration-Tests:
|
||||
uses: ./.github/workflows/integration-tests.yml
|
||||
name: '1'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Setup dotnet
|
||||
uses: actions/setup-dotnet@v1
|
||||
with:
|
||||
dotnet-version: |
|
||||
6.0.x
|
||||
7.0.x
|
||||
|
||||
- name: Build
|
||||
run: ./build.sh
|
||||
|
||||
windows:
|
||||
Publish:
|
||||
needs: [Integration-Tests]
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 10
|
||||
name: '2 / Publish'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup dotnet
|
||||
uses: actions/setup-dotnet@v1
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: |
|
||||
6.0.x
|
||||
7.0.x
|
||||
8.0.x
|
||||
10.0.x
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
39
.github/workflows/PR Validation.yml
vendored
Normal file
39
.github/workflows/PR Validation.yml
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
name: PR Validation
|
||||
|
||||
on: [pull_request]
|
||||
|
||||
concurrency:
|
||||
group: pr-validation-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
Whitespace-Check:
|
||||
uses: ./.github/workflows/trailing-whitespace-check.yml
|
||||
secrets: inherit
|
||||
name: '1'
|
||||
|
||||
Tests:
|
||||
needs: Whitespace-Check
|
||||
uses: ./.github/workflows/integration-tests.yml
|
||||
secrets: inherit
|
||||
name: '2'
|
||||
|
||||
build:
|
||||
needs: [Whitespace-Check, Tests]
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 10
|
||||
name: '3 / Build'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup dotnet
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: |
|
||||
6.0.x
|
||||
8.0.x
|
||||
10.0.x
|
||||
|
||||
- name: Build
|
||||
run: .\build.ps1
|
||||
220
.github/workflows/integration-tests.yml
vendored
Normal file
220
.github/workflows/integration-tests.yml
vendored
Normal file
@@ -0,0 +1,220 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
concurrency:
|
||||
group: integration-tests-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: ${{ matrix.os }} API-${{ matrix.electronVersion }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-22.04, ubuntu-24.04, windows-2022, windows-2025, macos-14, macos-15-intel, macos-26]
|
||||
electronVersion: ['30.4.0', '38.2.2']
|
||||
include:
|
||||
- os: ubuntu-22.04
|
||||
rid: linux-x64
|
||||
- os: ubuntu-24.04
|
||||
rid: linux-x64
|
||||
- os: windows-2022
|
||||
rid: win-x64
|
||||
- os: windows-2025
|
||||
rid: win-x64
|
||||
- os: macos-14
|
||||
rid: osx-arm64
|
||||
- os: macos-15-intel
|
||||
rid: osx-x64
|
||||
- os: macos-26
|
||||
rid: osx-arm64
|
||||
|
||||
env:
|
||||
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1
|
||||
DOTNET_NOLOGO: 1
|
||||
CI: true
|
||||
ELECTRON_ENABLE_LOGGING: 1
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Random delay (0-20 seconds)
|
||||
shell: bash
|
||||
run: |
|
||||
DELAY=$((RANDOM % 21))
|
||||
echo "Waiting for $DELAY seconds..."
|
||||
sleep $DELAY
|
||||
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj
|
||||
|
||||
- name: Build
|
||||
run: dotnet build --no-restore -c Release -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj
|
||||
|
||||
- name: Install Linux GUI dependencies
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
set -e
|
||||
sudo apt-get update
|
||||
. /etc/os-release
|
||||
if [ "$VERSION_ID" = "24.04" ]; then ALSA_PKG=libasound2t64; else ALSA_PKG=libasound2; fi
|
||||
echo "Using ALSA package: $ALSA_PKG"
|
||||
sudo apt-get install -y xvfb \
|
||||
libgtk-3-0 libnss3 libgdk-pixbuf-2.0-0 libdrm2 libgbm1 libxss1 libxtst6 libatk-bridge2.0-0 libatk1.0-0 libatspi2.0-0 libx11-xcb1 "$ALSA_PKG"
|
||||
|
||||
- name: Run tests (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
mkdir -p test-results
|
||||
xvfb-run -a dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj \
|
||||
-c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} \
|
||||
--logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" \
|
||||
--logger "console;verbosity=detailed" \
|
||||
--results-directory test-results
|
||||
|
||||
- name: Run tests (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path test-results | Out-Null
|
||||
dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj -c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} --logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" --logger "console;verbosity=detailed" --results-directory test-results
|
||||
|
||||
- name: Run tests (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
mkdir -p test-results
|
||||
dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj -c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} --logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" --logger "console;verbosity=detailed" --results-directory test-results
|
||||
|
||||
- name: Upload raw test results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: test-results-${{ matrix.os }}-electron-${{ matrix.electronVersion }}
|
||||
path: test-results/*.trx
|
||||
retention-days: 7
|
||||
|
||||
summary:
|
||||
name: Test Results
|
||||
runs-on: ubuntu-24.04
|
||||
if: always()
|
||||
needs: [tests]
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
checks: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Download all test results
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: test-results
|
||||
|
||||
- name: Setup .NET (for CTRF conversion)
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Install CTRF TRX→CTRF converter (dotnet tool)
|
||||
run: |
|
||||
dotnet new tool-manifest
|
||||
dotnet tool install DotnetCtrfJsonReporter --local
|
||||
|
||||
- name: Convert TRX → CTRF and clean names (filePath=OS|Electron X.Y.Z)
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p ctrf
|
||||
shopt -s globstar nullglob
|
||||
conv=0
|
||||
for trx in test-results/**/*.trx; do
|
||||
base="$(basename "$trx" .trx)" # e.g. ubuntu-22.04-electron-30.4.0
|
||||
os="${base%%-electron-*}"
|
||||
electron="${base#*-electron-}"
|
||||
label="$os|Electron $electron"
|
||||
outdir="ctrf/${label}"
|
||||
mkdir -p "$outdir"
|
||||
out="${outdir}/ctrf-report.json"
|
||||
|
||||
dotnet tool run DotnetCtrfJsonReporter -p "$trx" -d "$outdir" -f "ctrf-report.json"
|
||||
|
||||
jq --arg fp "$label" '.results.tests |= map(.filePath = $fp)' "$out" > "${out}.tmp" && mv "${out}.tmp" "$out"
|
||||
|
||||
echo "Converted & normalized $trx -> $out"
|
||||
conv=$((conv+1))
|
||||
done
|
||||
echo "Processed $conv TRX file(s)"
|
||||
|
||||
- name: Publish Test Report
|
||||
if: always()
|
||||
uses: ctrf-io/github-test-reporter@v1
|
||||
with:
|
||||
report-path: 'ctrf/**/*.json'
|
||||
summary: true
|
||||
pull-request: false
|
||||
status-check: false
|
||||
status-check-name: 'Integration Tests'
|
||||
use-suite-name: true
|
||||
update-comment: true
|
||||
always-group-by: true
|
||||
overwrite-comment: true
|
||||
exit-on-fail: true
|
||||
group-by: 'suite'
|
||||
upload-artifact: true
|
||||
fetch-previous-results: true
|
||||
summary-report: false
|
||||
summary-delta-report: true
|
||||
github-report: true
|
||||
test-report: false
|
||||
test-list-report: false
|
||||
failed-report: true
|
||||
failed-folded-report: false
|
||||
skipped-report: true
|
||||
suite-folded-report: true
|
||||
suite-list-report: false
|
||||
file-report: true
|
||||
previous-results-report: true
|
||||
insights-report: true
|
||||
flaky-report: true
|
||||
flaky-rate-report: true
|
||||
fail-rate-report: false
|
||||
slowest-report: false
|
||||
report-order: 'summary-delta-report,failed-report,skipped-report,suite-folded-report,file-report,previous-results-report,github-report'
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
- name: Save PR Number
|
||||
if: github.event_name == 'pull_request'
|
||||
run: echo "PR_NUMBER=${{ github.event.pull_request.number }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Write PR Number to File
|
||||
if: github.event_name == 'pull_request'
|
||||
run: echo "$PR_NUMBER" > pr_number.txt
|
||||
shell: bash
|
||||
|
||||
- name: Upload PR Number Artifact
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: pr_number
|
||||
path: pr_number.txt
|
||||
|
||||
- name: Summary
|
||||
run: echo "All matrix test jobs completed."
|
||||
81
.github/workflows/pr-comment.yml
vendored
Normal file
81
.github/workflows/pr-comment.yml
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
name: Create PR Comments
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [ "PR Validation" ]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
pr-comment:
|
||||
name: Post Test Result as PR comment
|
||||
runs-on: ubuntu-24.04
|
||||
if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'cancelled'
|
||||
|
||||
steps:
|
||||
- name: Download CTRF artifact
|
||||
uses: dawidd6/action-download-artifact@v8
|
||||
with:
|
||||
github_token: ${{ github.token }}
|
||||
run_id: ${{ github.event.workflow_run.id }}
|
||||
name: ctrf-report
|
||||
path: ctrf
|
||||
|
||||
- name: Download PR Number Artifact
|
||||
uses: dawidd6/action-download-artifact@v8
|
||||
with:
|
||||
github_token: ${{ github.token }}
|
||||
run_id: ${{ github.event.workflow_run.id }}
|
||||
name: pr_number
|
||||
path: pr_number
|
||||
|
||||
- name: Read PR Number
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
FILE='pr_number/pr_number.txt'
|
||||
|
||||
# Ensure file exists
|
||||
if [ ! -f "$FILE" ] || [ -L "$FILE" ]; then
|
||||
echo "Error: $FILE is missing or is not a regular file." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Chec file size
|
||||
if [ "$(wc -c < "$FILE" | tr -d ' ')" -gt 200 ]; then
|
||||
echo "Error: $FILE is too large." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Read first line
|
||||
PR_NUMBER=""
|
||||
IFS= read -r PR_NUMBER < "$FILE" || true
|
||||
|
||||
# Validate whether it's a number
|
||||
if ! [[ "$PR_NUMBER" =~ ^[0-9]{1,10}$ ]]; then
|
||||
echo "Error: PR_NUMBER is not a valid integer on the first line." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf 'PR_NUMBER=%s\n' "$PR_NUMBER" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Post PR Comment
|
||||
uses: ctrf-io/github-test-reporter@v1
|
||||
with:
|
||||
report-path: 'ctrf/**/*.json'
|
||||
issue: ${{ env.PR_NUMBER }}
|
||||
|
||||
summary: true
|
||||
pull-request: true
|
||||
use-suite-name: true
|
||||
update-comment: true
|
||||
always-group-by: true
|
||||
overwrite-comment: true
|
||||
upload-artifact: false
|
||||
|
||||
pull-request-report: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
59
.github/workflows/publish-wiki.yml
vendored
Normal file
59
.github/workflows/publish-wiki.yml
vendored
Normal file
@@ -0,0 +1,59 @@
|
||||
name: Publish wiki
|
||||
on:
|
||||
push:
|
||||
branches: [electronnet_core, main]
|
||||
workflow_dispatch:
|
||||
concurrency:
|
||||
group: publish-wiki
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: write
|
||||
jobs:
|
||||
publish-wiki:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Remove level 1 headings from Markdown files
|
||||
shell: bash
|
||||
run: |
|
||||
find docs/ -name '*.md' -exec sed -i '1d' {} \;
|
||||
- name: Move all files to root folder
|
||||
shell: bash
|
||||
run: |
|
||||
mv docs/*/* docs/
|
||||
- name: Delete unwanted files
|
||||
shell: bash
|
||||
run: |
|
||||
# rm docs/*.xlsm
|
||||
# rm docs/*.pptx
|
||||
rm docs/*.shproj
|
||||
- name: Stripping file extensions....
|
||||
uses: softworkz/strip-markdown-extensions-from-links-action@main
|
||||
with:
|
||||
path: ./docs/
|
||||
- name: Copy Changelog
|
||||
shell: bash
|
||||
run: |
|
||||
cp Changelog.md docs/RelInfo/ 2>/dev/null || true
|
||||
- name: Copy images to wiki/wiki folder
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir docs/wiki
|
||||
cp docs/*.svg docs/wiki/ 2>/dev/null || true
|
||||
cp docs/*.png docs/wiki/ 2>/dev/null || true
|
||||
cp docs/*.jpg docs/wiki/ 2>/dev/null || true
|
||||
cp docs/*.gif docs/wiki/ 2>/dev/null || true
|
||||
cp docs/*.mp4 docs/wiki/ 2>/dev/null || true
|
||||
- name: Commit and push changes
|
||||
run: |
|
||||
git config --global user.name "GitHub Action"
|
||||
git config --global user.email "action@github.com"
|
||||
git add -A
|
||||
git commit -m "Automatically update Markdown files" || echo "No changes to commit"
|
||||
- uses: Andrew-Chen-Wang/github-wiki-action@v4.4.0
|
||||
with:
|
||||
path: docs/
|
||||
ignore: |
|
||||
'**/*.xlsm'
|
||||
'**/*.pptx'
|
||||
'**/*.shproj'
|
||||
49
.github/workflows/retry-test-jobs.yml
vendored
Normal file
49
.github/workflows/retry-test-jobs.yml
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
name: Tests auto-rerun
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [ "PR Validation", "Build and Publish" ]
|
||||
types: [ completed ]
|
||||
|
||||
jobs:
|
||||
rerun-failed-matrix-jobs-once:
|
||||
if: >
|
||||
${{
|
||||
github.event.workflow_run.conclusion == 'failure' &&
|
||||
github.event.workflow_run.run_attempt == 1
|
||||
}}
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Decide whether to rerun (only if matrix jobs failed)
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_ID: ${{ github.event.workflow_run.id }}
|
||||
run: |
|
||||
echo "Inspecting jobs of workflow run $RUN_ID in $REPO"
|
||||
|
||||
jobs_json="$(gh api -R $REPO repos/$REPO/actions/runs/$RUN_ID/jobs)"
|
||||
|
||||
echo "Jobs and conclusions:"
|
||||
echo "$jobs_json" | jq '.jobs[] | {name: .name, conclusion: .conclusion}'
|
||||
|
||||
failed_matrix_jobs=$(echo "$jobs_json" | jq -r '
|
||||
[ .jobs[]
|
||||
| select(.conclusion == "failure"
|
||||
and (.name | contains(" API-")))
|
||||
]
|
||||
| length // 0
|
||||
')
|
||||
failed_matrix_jobs=${failed_matrix_jobs:-0}
|
||||
|
||||
if [ "${failed_matrix_jobs}" -gt 0 ]; then
|
||||
echo "Detected failing Integration Tests jobs – re-running failed jobs for this run."
|
||||
gh run rerun -R "$REPO" "$RUN_ID" --failed
|
||||
else
|
||||
echo "Only non-matrix jobs (like Test Results) failed – not auto-rerunning."
|
||||
fi
|
||||
84
.github/workflows/trailing-whitespace-check.yml
vendored
Normal file
84
.github/workflows/trailing-whitespace-check.yml
vendored
Normal file
@@ -0,0 +1,84 @@
|
||||
name: Whitespace Check
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
check-whitespace:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check for trailing whitespace
|
||||
run: |
|
||||
echo "Checking for trailing whitespace in changed files..."
|
||||
|
||||
# Get the base branch
|
||||
BASE_SHA="${{ github.event.pull_request.base.sha }}"
|
||||
HEAD_SHA="${{ github.event.pull_request.head.sha }}"
|
||||
|
||||
# Get list of changed files (excluding deleted files)
|
||||
CHANGED_FILES=$(git diff --name-only --diff-filter=d "$BASE_SHA" "$HEAD_SHA")
|
||||
|
||||
if [ -z "$CHANGED_FILES" ]; then
|
||||
echo "No files to check."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# File patterns to check (text files)
|
||||
PATTERNS="\.cs$|\.csproj$|\.sln$|\.ts$|\.html$|\.css$|\.scss$"
|
||||
|
||||
# Directories and file patterns to exclude
|
||||
EXCLUDE_PATTERNS="(^|\/)(\.|node_modules|bin|obj|artifacts|packages|\.vs|\.nuke\/temp)($|\/)"
|
||||
|
||||
ERRORS_FOUND=0
|
||||
TEMP_FILE=$(mktemp)
|
||||
|
||||
while IFS= read -r file; do
|
||||
# Skip if file doesn't exist (shouldn't happen with --diff-filter=d, but just in case)
|
||||
if [ ! -f "$file" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
# Check if file matches patterns to check
|
||||
if ! echo "$file" | grep -qE "$PATTERNS"; then
|
||||
continue
|
||||
fi
|
||||
|
||||
# Check if file should be excluded
|
||||
if echo "$file" | grep -qE "$EXCLUDE_PATTERNS"; then
|
||||
continue
|
||||
fi
|
||||
|
||||
# Find trailing whitespace lines, excluding XML doc placeholder lines that are exactly "/// " (one space)
|
||||
MATCHES=$(grep -n '[[:space:]]$' "$file" | grep -vE '^[0-9]+:[[:space:]]*/// $' || true)
|
||||
|
||||
if [ -n "$MATCHES" ]; then
|
||||
echo "❌ Trailing whitespace found in: $file"
|
||||
echo "$MATCHES" | head -10
|
||||
TOTAL=$(echo "$MATCHES" | wc -l)
|
||||
if [ "$TOTAL" -gt 10 ]; then
|
||||
echo " ... and $(($TOTAL - 10)) more lines"
|
||||
fi
|
||||
echo "1" >> "$TEMP_FILE"
|
||||
fi
|
||||
done <<< "$CHANGED_FILES"
|
||||
|
||||
ERRORS_FOUND=$(wc -l < "$TEMP_FILE" 2>/dev/null || echo "0")
|
||||
rm -f "$TEMP_FILE"
|
||||
|
||||
if [ "$ERRORS_FOUND" -gt 0 ]; then
|
||||
echo ""
|
||||
echo "❌ Found trailing whitespace in $ERRORS_FOUND file(s)."
|
||||
echo "Please remove trailing whitespace from the files listed above."
|
||||
exit 1
|
||||
else
|
||||
echo "✅ No trailing whitespace found in changed files."
|
||||
exit 0
|
||||
fi
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -266,3 +266,4 @@ __pycache__/
|
||||
|
||||
# Nuke build tool
|
||||
.nuke/temp
|
||||
/publish.cmd
|
||||
|
||||
@@ -1,19 +1,54 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"title": "Build Schema",
|
||||
"$ref": "#/definitions/build",
|
||||
"definitions": {
|
||||
"build": {
|
||||
"type": "object",
|
||||
"Host": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"AppVeyor",
|
||||
"AzurePipelines",
|
||||
"Bamboo",
|
||||
"Bitbucket",
|
||||
"Bitrise",
|
||||
"GitHubActions",
|
||||
"GitLab",
|
||||
"Jenkins",
|
||||
"Rider",
|
||||
"SpaceAutomation",
|
||||
"TeamCity",
|
||||
"Terminal",
|
||||
"TravisCI",
|
||||
"VisualStudio",
|
||||
"VSCode"
|
||||
]
|
||||
},
|
||||
"ExecutableTarget": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Clean",
|
||||
"Compile",
|
||||
"Default",
|
||||
"Package",
|
||||
"PrePublish",
|
||||
"Publish",
|
||||
"PublishPackages",
|
||||
"PublishPreRelease",
|
||||
"PublishRelease",
|
||||
"Restore",
|
||||
"RunUnitTests"
|
||||
]
|
||||
},
|
||||
"Verbosity": {
|
||||
"type": "string",
|
||||
"description": "",
|
||||
"enum": [
|
||||
"Verbose",
|
||||
"Normal",
|
||||
"Minimal",
|
||||
"Quiet"
|
||||
]
|
||||
},
|
||||
"NukeBuild": {
|
||||
"properties": {
|
||||
"Configuration": {
|
||||
"type": "string",
|
||||
"description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)",
|
||||
"enum": [
|
||||
"Debug",
|
||||
"Release"
|
||||
]
|
||||
},
|
||||
"Continue": {
|
||||
"type": "boolean",
|
||||
"description": "Indicates to continue a previously failed build attempt"
|
||||
@@ -23,25 +58,8 @@
|
||||
"description": "Shows the help text for this build assembly"
|
||||
},
|
||||
"Host": {
|
||||
"type": "string",
|
||||
"description": "Host for execution. Default is 'automatic'",
|
||||
"enum": [
|
||||
"AppVeyor",
|
||||
"AzurePipelines",
|
||||
"Bamboo",
|
||||
"Bitbucket",
|
||||
"Bitrise",
|
||||
"GitHubActions",
|
||||
"GitLab",
|
||||
"Jenkins",
|
||||
"Rider",
|
||||
"SpaceAutomation",
|
||||
"TeamCity",
|
||||
"Terminal",
|
||||
"TravisCI",
|
||||
"VisualStudio",
|
||||
"VSCode"
|
||||
]
|
||||
"$ref": "#/definitions/Host"
|
||||
},
|
||||
"NoLogo": {
|
||||
"type": "boolean",
|
||||
@@ -62,10 +80,6 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"ReleaseNotesFilePath": {
|
||||
"type": "string",
|
||||
"description": "ReleaseNotesFilePath - To determine the SemanticVersion"
|
||||
},
|
||||
"Root": {
|
||||
"type": "string",
|
||||
"description": "Root directory during build execution"
|
||||
@@ -74,71 +88,50 @@
|
||||
"type": "array",
|
||||
"description": "List of targets to be skipped. Empty list skips all dependencies",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Clean",
|
||||
"Compile",
|
||||
"CompileSample",
|
||||
"CreatePackages",
|
||||
"Default",
|
||||
"ElectronizeCustomWin7TargetSample",
|
||||
"ElectronizeGenericTargetSample",
|
||||
"ElectronizeLinuxTargetSample",
|
||||
"ElectronizeMacOsTargetSample",
|
||||
"ElectronizeWindowsTargetSample",
|
||||
"Package",
|
||||
"PrePublish",
|
||||
"Publish",
|
||||
"PublishPackages",
|
||||
"PublishPreRelease",
|
||||
"PublishRelease",
|
||||
"Restore",
|
||||
"RunUnitTests"
|
||||
]
|
||||
"$ref": "#/definitions/ExecutableTarget"
|
||||
}
|
||||
},
|
||||
"Solution": {
|
||||
"type": "string",
|
||||
"description": "Path to a solution file that is automatically loaded"
|
||||
},
|
||||
"Target": {
|
||||
"type": "array",
|
||||
"description": "List of targets to be invoked. Default is '{default_target}'",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Clean",
|
||||
"Compile",
|
||||
"CompileSample",
|
||||
"CreatePackages",
|
||||
"Default",
|
||||
"ElectronizeCustomWin7TargetSample",
|
||||
"ElectronizeGenericTargetSample",
|
||||
"ElectronizeLinuxTargetSample",
|
||||
"ElectronizeMacOsTargetSample",
|
||||
"ElectronizeWindowsTargetSample",
|
||||
"Package",
|
||||
"PrePublish",
|
||||
"Publish",
|
||||
"PublishPackages",
|
||||
"PublishPreRelease",
|
||||
"PublishRelease",
|
||||
"Restore",
|
||||
"RunUnitTests"
|
||||
]
|
||||
"$ref": "#/definitions/ExecutableTarget"
|
||||
}
|
||||
},
|
||||
"Verbosity": {
|
||||
"type": "string",
|
||||
"description": "Logging verbosity during build execution. Default is 'Normal'",
|
||||
"enum": [
|
||||
"Minimal",
|
||||
"Normal",
|
||||
"Quiet",
|
||||
"Verbose"
|
||||
]
|
||||
"$ref": "#/definitions/Verbosity"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"CommonPropsFilePath": {
|
||||
"type": "string",
|
||||
"description": "common.props file path - to determine the configured version"
|
||||
},
|
||||
"Configuration": {
|
||||
"type": "string",
|
||||
"description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)",
|
||||
"enum": [
|
||||
"Debug",
|
||||
"Release"
|
||||
]
|
||||
},
|
||||
"ReleaseNotesFilePath": {
|
||||
"type": "string",
|
||||
"description": "ReleaseNotesFilePath - To determine the lates changelog version"
|
||||
},
|
||||
"Solution": {
|
||||
"type": "string",
|
||||
"description": "Path to a solution file that is automatically loaded"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$ref": "#/definitions/NukeBuild"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"$schema": "./build.schema.json",
|
||||
"Solution": "src/ElectronNET.sln"
|
||||
"Solution": "src/ElectronNET.Lean.sln"
|
||||
}
|
||||
4
.vscode/launch.json
vendored
4
.vscode/launch.json
vendored
@@ -10,9 +10,9 @@
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceRoot}/ElectronNET.CLI/bin/Debug/netcoreapp2.0/dotnet-electronize.dll",
|
||||
"program": "${workspaceRoot}/src/ElectronNET.CLI/bin/Debug/net8.0/dotnet-electronize.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceRoot}/ElectronNET.CLI",
|
||||
"cwd": "${workspaceRoot}/src/ElectronNET.CLI",
|
||||
// For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
|
||||
"console": "internalConsole",
|
||||
"stopAtEntry": false,
|
||||
|
||||
2
.vscode/tasks.json
vendored
2
.vscode/tasks.json
vendored
@@ -7,7 +7,7 @@
|
||||
"label": "build",
|
||||
"type": "shell",
|
||||
"command": "dotnet",
|
||||
"args": ["build", "${workspaceRoot}/ElectronNET.CLI/ElectronNET.CLI.csproj"],
|
||||
"args": ["build", "${workspaceRoot}/src/ElectronNET.CLI/ElectronNET.CLI.csproj"],
|
||||
"problemMatcher": "$msCompile",
|
||||
"group": {
|
||||
"_id": "build",
|
||||
|
||||
470
Changelog.md
470
Changelog.md
@@ -1,377 +1,139 @@
|
||||
# 23.6.2
|
||||
# 0.4.1
|
||||
|
||||
## ElectronNET.API
|
||||
## ElectronNET.Core
|
||||
|
||||
- Fixed handling of `Center` property for windows (#1001)
|
||||
- Added missing methods on `Cookies` (#1000)
|
||||
|
||||
* Fixed escaping of URL (#735) @cosmo0
|
||||
* Changed `ZoomFactor` type from `int` to `double` (#754) @Yuvix25
|
||||
# 0.4.0
|
||||
|
||||
## ElectronNET.CLI
|
||||
## ElectronNET.Core
|
||||
|
||||
* (none)
|
||||
- Fixed ElectronSingleInstance handling (#996) @softworkz
|
||||
- Fixed `PackageId` handling (#993) @softworkz
|
||||
- Added cross-platform npm restore and check mismatch on publish (#988) @softworkz
|
||||
|
||||
## Infrastructure
|
||||
# 0.3.1
|
||||
|
||||
* Changed build system to NUKE #757 @FlorianRappl
|
||||
* Updated target framework for host project #753 @r-pankevicius
|
||||
## ElectronNET.Core
|
||||
|
||||
# 23.6.1
|
||||
- Fixed issue transforming the project ID (#989, #990) @softworkz
|
||||
|
||||
# 0.3.0
|
||||
|
||||
## ElectronNET.CLI
|
||||
## ElectronNET.Core
|
||||
|
||||
* New Feature: Upgrade to .NET 6 support
|
||||
- Updated infrastructure (#937, #939) @softworkz
|
||||
- Updated all model classes to Electron API 39.2 (#949) @softworkz
|
||||
- Fixed output path for `electron-builder` (#942) @softworkz
|
||||
- Fixed floating point display resolution (#944) @softworkz
|
||||
- Fixed error in case of missing electron-host-hook (#978)
|
||||
- Fixed previous API break using exposed `JsonElement` objects (#938) @softworkz
|
||||
- Fixed and improved several test cases (#962) @softworkz
|
||||
- Fixed startup of Electron.NET from VS Code Debug Adapter (#952)
|
||||
- Fixed the `BrowserWindowOptions` (#945) @softworkz
|
||||
- Fixed example for `AutoMenuHide` to reflect platform capabilities (#982) @markatosi
|
||||
- Added several migration checks for publishing (#966) @softworkz
|
||||
- Added more test runners for E2E tests (#950, #951) @agracio
|
||||
- Added dynamic updates for tray menu (#973) @davidroth
|
||||
- Added matrix tests with 6 runners and 2 electron version (#948) @softworkz
|
||||
- Added additional APIs for WebContents (#958) @agracio
|
||||
- Added documentation for MacOS package publish (#983) @markatosi
|
||||
- Added sample application for `ElectronHostHook` (#967) @adityashirsatrao007
|
||||
|
||||
## ElectronNET.API
|
||||
# 0.2.0
|
||||
|
||||
* New Feature: Native Electron 23.2.0 support, but not all new API features included (we search contributors)
|
||||
* New Feature: Upgrade to .NET 6 support
|
||||
* New Feature: Changed Web-Socket .NET Library to [SocketIOClient](https://github.com/doghappy/socket.io-client-csharp)
|
||||
* Breaking Changes: We removed deprecated API events/methods from ElectronNET.API [(More Details)](https://www.electronjs.org/docs/latest/breaking-changes)
|
||||
|
||||
# 13.5.1
|
||||
## ElectronNET.Core
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* New Feature: Using exit code instead of seek for the term 'error' (thanks [TSrgy](https://github.com/TSrgy)) [\#562](https://github.com/ElectronNET/Electron.NET/pull/562)
|
||||
* Fixed bug: Allow for property overrides to be passed in (thanks [danatcofo](https://github.com/danatcofo)) [\#531](https://github.com/ElectronNET/Electron.NET/pull/531)
|
||||
Use `/p:propertyName=value` or `/property:propertyName=value` to pass in property overrides. This is equivalent to the `-p:` option documented here: [https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-publish](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-publish)
|
||||
* Fixed bug: Add ability to pass an argument for "Version" for both the "dotnet publish" and "electron-builder" commands (thanks [tub5](https://github.com/tub5)) [\#546](https://github.com/ElectronNET/Electron.NET/pull/546)
|
||||
* Fixed bug: Version flag not persisting with the referenced executable (thanks [tub5](https://github.com/tub5)) [\#585](https://github.com/ElectronNET/Electron.NET/pull/585)
|
||||
* Fixed bug: Changes PublishSingleFile default to false for NET5 compatibility (thanks [cristiangiagante](https://github.com/cristiangiagante)) [\#570](https://github.com/ElectronNET/Electron.NET/pull/570)
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* New Feature: Native Electron 13.1.5 support, but not all new features (we search contributors)
|
||||
* Breaking API Changes (from native Electron 13.1.5):
|
||||
- `Shell.MoveItemToTrashAsync` renamed with `Shell.TrashItemAsync`
|
||||
- The deprecated extension APIs have been removed: `BrowserWindow.GetAllExtensionsAsync()`, `BrowserWindow.RemoveExtension()`, `BrowserWindow.AddExtensionAsync()`. Use the session APIs instead: `Session.GetAllExtensionsAsync()`, `Session.RemoveExtension()`, `Session.LoadExtensionAsync()`.
|
||||
* New Feature: singleInstance handle command line arguments [\#520](https://github.com/ElectronNET/Electron.NET/issues/520)
|
||||
* New Feature: Add WebContents [insertCSS](https://www.electronjs.org/docs/api/web-contents#contentsinsertcsscss-options) functionality (thanks [nfichter](https://github.com/nfichter)) [\#559](https://github.com/ElectronNET/Electron.NET/pull/559)
|
||||
* New Feature: Allow IpcMain to send IPC messages to BrowserViews (thanks [nfichter](https://github.com/nfichter)) [\#560](https://github.com/ElectronNET/Electron.NET/pull/560)
|
||||
* New Feature: Add support for proxies that require basic username/password authentication (thanks [nfichter](https://github.com/nfichter)) [\#561](https://github.com/ElectronNET/Electron.NET/pull/561)
|
||||
* New Feature: Add PostData to LoadURLOptions to allow http-posts in LoadURL calls (thanks [Funkrusha](https://github.com/Funkrusha)) [\#547](https://github.com/ElectronNET/Electron.NET/pull/547)
|
||||
* Fixed bug: Fix splash screen interaction causing crashes, ghost dragging, and resizable behavior #540 (thanks [MiniguyBrendan](https://github.com/MiniguyBrendan)) [\#540](https://github.com/ElectronNET/Electron.NET/pull/540)
|
||||
* Fixed bug: Vibrancy serialization fix (thanks [tantumalice](https://github.com/tantumalice)) [\#573](https://github.com/ElectronNET/Electron.NET/pull/573)
|
||||
- Updated dependencies (#930) @softworkz
|
||||
- Updated integration tests (#931) @softworkz
|
||||
- Updated `ElectronNET.Host` (#935) @softworkz
|
||||
- Removed transition period specific build configuration (#928) @softworkz
|
||||
- Added `IsRunningBlazor` option to `BrowserWindowOptions` (#926)
|
||||
- Added platform support attributes (#929) @softworkz
|
||||
|
||||
# 11.5.1
|
||||
# 0.1.0
|
||||
|
||||
ElectronNET.CLI:
|
||||
## ElectronNET.Core
|
||||
|
||||
* New Feature: Added new build and start commandline options for single exe (thanks [nathanwienand](https://github.com/nathanwienand)) [\#506](https://github.com/ElectronNET/Electron.NET/pull/506)
|
||||
* New Feature: Set a description of the app in `electron.manifest.json` (thanks [BurtsevC](https://github.com/BurtsevC)) [\#433](https://github.com/ElectronNET/Electron.NET/pull/433)
|
||||
* New Feature: Set a target for the start command (thanks [gabecook](https://github.com/gabecook)) [\#463](https://github.com/ElectronNET/Electron.NET/pull/463)
|
||||
* New Feature: `electronize init` support for F# projects (thanks [kojo12228](https://github.com/kojo12228)) [\#457](https://github.com/ElectronNET/Electron.NET/pull/457)
|
||||
* New Feature: Linux support for the buildAll.sh (thanks [duncanawoods](https://github.com/duncanawoods)) [\#465](https://github.com/ElectronNET/Electron.NET/pull/465)
|
||||
* Fixed bug: ERR_UNKNOWN_URL_SCHEME by intercepting file:// protocol (thanks [duncanawoods](https://github.com/duncanawoods)) [\#467](https://github.com/ElectronNET/Electron.NET/pull/467)
|
||||
- Updated `PrintToPDFOptions` to also allow specifying the `PageSize` with an object (#769)
|
||||
- Updated splashscreen image to have 0 margin (#622)
|
||||
- Updated the IPC API w.r.t. naming and consistency (#905) @agracio
|
||||
- Updated the IPC bridge w.r.t. synchronization and thread-safety (#918) @agracio
|
||||
- Updated serialization to use `System.Text.Json` replacing `Newtonsoft.Json` (#917) @Denny09310
|
||||
- Fixed parameter handling for the `sendToIpcRenderer` function (#922) @softworkz
|
||||
- Fixed synchronization on removing event handlers (#921) @softworkz
|
||||
- Fixed creation of windows with `contextIsolation` enabled (#906) @NimbusFox
|
||||
- Fixed single instance behavior using the `ElectronSingleInstance` property (#901)
|
||||
- Fixed potential race conditions (#908) @softworkz
|
||||
- Added option to use `ElectronSplashScreen` with an HTML file (#799)
|
||||
- Added option to provide floating point value as aspect ratios with `SetAspectRatio` (#793)
|
||||
- Added option to provide `TitleBarOverlay` as an object (#911) @Denny09310
|
||||
- Added `TitleBarOverlay` property to `BrowserWindowOptions` (#909)
|
||||
- Added `RoundedCorners` property to `BrowserWindowOptions`
|
||||
- Added integration tests and robustness checks (#913) @softworkz
|
||||
- Added .NET 10 as an explicit target
|
||||
|
||||
ElectronNET.API:
|
||||
# 0.0.18
|
||||
|
||||
* New Feature: Native Electron 11.1.1 support, but not all new features (we search contributors)
|
||||
* Breaking API Changes (from native Electron 11.0): - Removed: BrowserView.{destroy, fromId, fromWebContents, getAllViews} and id property of BrowserView
|
||||
* New Feature: Upgrade to .NET 5 (thanks [scottkuhl](https://github.com/scottkuhl)) [\#509](https://github.com/ElectronNET/Electron.NET/pull/509)
|
||||
* New Feature: Extension Method for adding the Electron static class members to the standard MS DI Containers, this is a QOL issue only. `services.AddElectron()` (thanks [danatcofo](https://github.com/danatcofo )) [\#528](https://github.com/ElectronNET/Electron.NET/pull/528)
|
||||
* New Feature: SetMenu completed for the Dock (MacOS) (thanks [danatcofo](https://github.com/danatcofo )) [\#528](https://github.com/ElectronNET/Electron.NET/pull/528)
|
||||
|
||||
Example for the Dock Menu
|
||||
|
||||
`Electron.Dock.SetMenu(new [] {
|
||||
new MenuItem {
|
||||
Label = "Dock Menu Item",
|
||||
Click = () => {
|
||||
// do something
|
||||
}
|
||||
},
|
||||
});`
|
||||
|
||||
Example for consuming the activate event (MacOs only)
|
||||
## ElectronNET.Core
|
||||
|
||||
`Electron.App.On("activate", obj => {
|
||||
var hasWindows = (bool)obj;
|
||||
// do something
|
||||
});`
|
||||
|
||||
* New Feature: On and Once implementations for the App and Tray to cover the plethora of events that are not mapped explicitly in those two modules. (thanks [danatcofo](https://github.com/danatcofo )) [\#528](https://github.com/ElectronNET/Electron.NET/pull/528)
|
||||
* New Feature: Adding the `EnableRemoteModule` property to the WebPreferences object. As of Electron 10, this property defaulted to false and without it exposed you can't use the remote module within a window. (thanks [danatcofo](https://github.com/danatcofo )) [\#528](https://github.com/ElectronNET/Electron.NET/pull/528)
|
||||
* New Feature: Adding a configurable default electron port. (thanks [aarong-av](https://github.com/aarong-av)) [\#505](https://github.com/ElectronNET/Electron.NET/pull/505)
|
||||
* New Feature: Added support for launching the application with a file on MacOS (thanks [dlitty](https://github.com/dlitty)) [\#478](https://github.com/ElectronNET/Electron.NET/pull/478)
|
||||
* Improved: Avoid Blocking Calls in App and AutoUpdater (thanks [freosc](https://github.com/freosc)) [\#474](https://github.com/ElectronNET/Electron.NET/pull/474)
|
||||
* Fixed bug: Maintain references between socket.io connection events (thanks [danatcofo](https://github.com/danatcofo )) [\#468](https://github.com/ElectronNET/Electron.NET/pull/486)
|
||||
* Fixed bug: Set default WebPreferences.DefaultFontSize (thanks [duncanawoods](https://github.com/duncanawoods)) [\#468](https://github.com/ElectronNET/Electron.NET/pull/468)
|
||||
### Highlights
|
||||
|
||||
# 9.31.2
|
||||
- **Complete MSBuild Integration**: Eliminated CLI tool dependency, moved all build processes to MSBuild with deep Visual Studio integration
|
||||
- **Modernized Architecture**: Restructured process lifecycle with .NET launching first and running Electron as child process for better control and reliability
|
||||
- **Cross-Platform Development**: Build and debug Linux applications directly from Windows Visual Studio via WSL integration
|
||||
- **Flexible Electron Versioning**: Removed version lock-in, users can now select any Electron version with build-time validation
|
||||
- **Enhanced Debugging Experience**: ASP.NET-first debugging with Hot Reload support and improved process termination handling
|
||||
- **Console App Support**: No longer requires ASP.NET - now works with simple console applications for file system or remote server HTML/JS
|
||||
|
||||
* Electron-Builder fixed for Windows builds.
|
||||
### Build System & Project Structure
|
||||
|
||||
# 9.31.1
|
||||
- Eliminated electron.manifest.json configuration file, replaced with MSBuild project properties
|
||||
- Introduced new package structure: ElectronNET.Core (main package), ElectronNET.Core.Api (API definitions), ElectronNET.Core.AspNet (ASP.NET integration)
|
||||
- Added Runtime Identifier (RID) selection as part of project configuration
|
||||
- Restructured build folder layout to use standard .NET format (bin\net8.0\win-x64) instead of bin\Desktop
|
||||
- Implemented incremental build support for Electron assets to improve build performance
|
||||
- Added custom MSBuild tasks for Electron-specific build operations
|
||||
|
||||
ElectronNET.CLI:
|
||||
### Development Experience
|
||||
|
||||
* New Feature: Added config parameter (thanks [konstantingross](https://github.com/konstantingross)) [\#409](https://github.com/ElectronNET/Electron.NET/pull/409)
|
||||
* New Feature: Set the configuration environment with the electron.manifest.json file.
|
||||
* Fixed bug: Custom user path removed and replaced by the correct directory with VS macro (When ElectronNET.CLI is the Startup Project, press F5 (Debug) and the ElectronNET.WebApp starts correctly without error!) (thanks [konstantingross](https://github.com/konstantingross)) [\#409](https://github.com/ElectronNET/Electron.NET/pull/409)
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* New Feature: Native Electron 9.0.3 support, but not all new features (we search contributors)
|
||||
* New Feature: PowerMonitor API Support (thanks [gustavo-lara-molina](https://github.com/gustavo-lara-molina)) [\#399](https://github.com/ElectronNET/Electron.NET/pull/399) [\#423](https://github.com/ElectronNET/Electron.NET/pull/423)
|
||||
* New Feature: NativeTheme API Support (thanks [konstantingross](https://github.com/konstantingross)) [\#402](https://github.com/ElectronNET/Electron.NET/pull/402)
|
||||
* New Feature: Cookie API Support (thanks [freosc](https://github.com/freosc)) [\#413](https://github.com/ElectronNET/Electron.NET/pull/413)
|
||||
* Changed Feature: Removed dock methods from App API and moved to Dock API (thanks [konstantingross](https://github.com/konstantingross)) [\#422](https://github.com/ElectronNET/Electron.NET/pull/422)
|
||||
* App-Api Enhancement: MenuItems with Submenus need an submenu type workaround [\#412](https://github.com/ElectronNET/Electron.NET/issues/412)
|
||||
* App-Api Enhancement: Added UserAgentFallback (thanks [Mandrakia](https://github.com/Mandrakia)) [\#406](https://github.com/ElectronNET/Electron.NET/pull/406)
|
||||
* App-Api Enhancement: Summaries rewritten, new App.IsReady / App.HasSingleInstanceLock property, App.Ready event, App.Focus with force parameter method, many parameters changes (thanks [konstantingross](https://github.com/konstantingross)) [\#415](https://github.com/ElectronNET/Electron.NET/pull/415) [\#422](https://github.com/ElectronNET/Electron.NET/pull/422)
|
||||
* App-Api Enhancement: New App.IsReady property and App.Ready event (thanks [konstantingross](https://github.com/konstantingross)) [\#415](https://github.com/ElectronNET/Electron.NET/pull/415)
|
||||
* Shell-Api Enhancement: API fixes for Electron 9.0.0 / Added missing parameters / Summaries rewritten (thanks [konstantingross](https://github.com/konstantingross)) [\#417](https://github.com/ElectronNET/Electron.NET/pull/417) [\#418](https://github.com/ElectronNET/Electron.NET/pull/418)
|
||||
* Notification-Api Enhancement: Added missing properties in Notifications (thanks [konstantingross](https://github.com/konstantingross)) [\#410](https://github.com/ElectronNET/Electron.NET/pull/410)
|
||||
* BrowserWindows-Api Enhancement: Add missing API call for SetProgressBar options (thanks [konstantingross](https://github.com/konstantingross)) [\#416](https://github.com/ElectronNET/Electron.NET/pull/416)
|
||||
* BrowserWindow Enhancement: Add BrowserWindow.GetNativeWindowHandle() (thanks [kdlslyv](https://github.com/kdlslyv)) [\#429](https://github.com/ElectronNET/Electron.NET/pull/429)
|
||||
* HostHook-Api Enhancement: HostHook.CallAsync should use TaskCompletionSource.SetException instead of throwing exception (thanks [Fre V](https://github.com/freosc)) [\#430](https://github.com/ElectronNET/Electron.NET/pull/430)
|
||||
* MacOS Enhancement: Application exit logic (thanks [dafergu2](https://github.com/dafergu2)) [\#405](https://github.com/ElectronNET/Electron.NET/pull/405)
|
||||
* Fixed bug: ElectronNET.API.Entities.WebPreferences.ContextIsolation [DefaultValue(true)] [\#411](https://github.com/ElectronNET/Electron.NET/issues/411)
|
||||
|
||||
ElectronNET.WebApp (internal use):
|
||||
* Improvement debugging and testing new API calls (without install ElectronNET.CLI) (thanks [konstantingross](https://github.com/konstantingross)) [\#425](https://github.com/ElectronNET/Electron.NET/pull/425)
|
||||
* Fixed bug: Cannot find modules in ElectronHostHook (thanks [konstantingross](https://github.com/konstantingross)) [\#425](https://github.com/ElectronNET/Electron.NET/pull/425)
|
||||
|
||||
Thank you for donation [Phil Seeman](https://github.com/mpnow) ❤
|
||||
|
||||
# 8.31.2
|
||||
|
||||
ElectronNET.CLI:
|
||||
* New Feature: Deactivate PublishReadyToRun for build or start [\#395](https://github.com/ElectronNET/Electron.NET/issues/395)
|
||||
|
||||
`electronize build /target win /PublishReadyToRun false`
|
||||
`electronize start /PublishReadyToRun false`
|
||||
* Fixed bug: Application window doesn't open after packaging [\#387](https://github.com/ElectronNET/Electron.NET/issues/387)
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* New Feature: NativeImage Support (thanks [ThrDev](https://github.com/ThrDev)) [\#394](https://github.com/ElectronNET/Electron.NET/pull/394)
|
||||
* New Feature: Update menu items for context menu and system tray on-the-fly. [\#270](https://github.com/ElectronNET/Electron.NET/pull/270)
|
||||
|
||||
|
||||
# 8.31.1
|
||||
|
||||
ElectronNET.CLI:
|
||||
* New Feature: Set a name and author of the app in `electron.manifest.json` [\#348](https://github.com/ElectronNET/Electron.NET/issues/348#issuecomment-615977950) [\#310](https://github.com/ElectronNET/Electron.NET/issues/310#issuecomment-617361086)
|
||||
* New Feature: Live reload (thanks [syedadeel2](https://github.com/syedadeel2)) [\#390](https://github.com/ElectronNET/Electron.NET/pull/390)
|
||||
`electronize start /watch`
|
||||
* New Feature: Every new window will created with an clear cache [\#273](https://github.com/ElectronNET/Electron.NET/issues/273)
|
||||
`electronize start /clear-cache`
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* New Feature: Native Electron 8.2.3 support, but not all new features (we search contributors)
|
||||
* New Feature: We incease the startup time for ~25-36% [\#356](https://github.com/ElectronNET/Electron.NET/issues/356)
|
||||
* New Feature: Added print capability (thanks [x-xx-o](https://github.com/x-xx-o)) [\#355](https://github.com/ElectronNET/Electron.NET/pull/355)
|
||||
* New Feature: BrowserView API [\#371](https://github.com/ElectronNET/Electron.NET/issues/371)
|
||||
* Changed App.GetNameAsync and App.SetNameAsync to the App.Name Property [\#350](https://github.com/ElectronNET/Electron.NET/issues/350)
|
||||
* Fixed bug: Splash Screen disappearing on click [\#357](https://github.com/ElectronNET/Electron.NET/issues/357)
|
||||
* Fixed bug: Start MenuRole enum at 1 (thanks [jjuback](https://github.com/jjuback)) [\#369](https://github.com/ElectronNET/Electron.NET/pull/369)
|
||||
* Fixed bug: BridgeConnector not connected (spam console) [\#347](https://github.com/ElectronNET/Electron.NET/issues/347)
|
||||
* Fixed bug: BrowserWindowOptions is not setting Width and Height properly [\#373](https://github.com/ElectronNET/Electron.NET/issues/373)
|
||||
* Fixed bug: IpcMain.Once(string) is not one time use, is not removing listener [\#366](https://github.com/ElectronNET/Electron.NET/issues/366)
|
||||
* Fixed bug: IpcMain.RemoveAllListeners(string) is not removing the listeners [\#365](https://github.com/ElectronNET/Electron.NET/issues/365)
|
||||
* Fixed bug: GetLoginItemSettingsAsync does not work [\#352](https://github.com/ElectronNET/Electron.NET/issues/352)
|
||||
* Fixed bug: Using OnReadyToShow to display the main window in Blazor does not seem to work with Show set to false [\#361](https://github.com/ElectronNET/Electron.NET/issues/361)
|
||||
* Fixed bug: Unable to disable WebSecurity along with NodeIntegration enabled [\#389](https://github.com/ElectronNET/Electron.NET/issues/389)
|
||||
|
||||
# 7.30.2
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* New Feature: Different manifest file support [\#340](https://github.com/ElectronNET/Electron.NET/issues/340)
|
||||
* Create a additional manifest file: `electronize init /manifest test`
|
||||
* Start the app with your additional manifest file: `electronize start /manifest electron.manifest.test.json`
|
||||
* Build the app with your additional manifest file: `electronize build /target win /manifest electron.manifest.test.json`.
|
||||
|
||||
* New Feature: Command Line support [\#337](https://github.com/ElectronNET/Electron.NET/issues/337)
|
||||
* You can start the app with: `electronize start /args --dog=woof --test=true`
|
||||
* Or as binary: `myapp.exe /args --dog=woof --test=true`
|
||||
* Fixed bug: Start process with listen port 8000 error. [\#308](https://github.com/ElectronNET/Electron.NET/issues/308) (thanks [thecodejedi](https://github.com/thecodejedi))
|
||||
* Fixed bug: `electronize build` with no arguments would throw a `KeyNotFoundException`. (thanks [jamiebrynes7](https://github.com/jamiebrynes7))
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* New Feature: Electron 7.1.2 support, but not all new features (we search contributors) [\#341](https://github.com/ElectronNET/Electron.NET/issues/341)
|
||||
* New Feature: Electron.App.CommandLine API [\#337](https://github.com/ElectronNET/Electron.NET/issues/337)
|
||||
* New Feature: Support of BrowserWindow.AddExtension, BrowserWindow.RemoveExtension, BrowserWindow.GetExtensions (thanks [Daddoon](https://github.com/Daddoon))
|
||||
|
||||
Thank you for donation [robertmclaws](https://github.com/robertmclaws) ❤
|
||||
|
||||
# 5.30.1
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* Move to .NET Core 3.0
|
||||
* Use npm npx instead of global installations (thanks [jimbuck](https://github.com/jimbuck))
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* Move to .NET Core 3.0
|
||||
* New Feature: Add BrowserWindow.RemoveMenu() (thanks [hack2root](https://github.com/hack2root))
|
||||
|
||||
Thanks to [MaherJendoubi](https://github.com/MaherJendoubi), [kant2002](https://github.com/kant2002), [raz-canva](https://github.com/raz-canva) and [Daddoon](https://github.com/Daddoon) to give .NET Core 3.0 feedback!
|
||||
# 5.22.14
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* Fixed bug: Build fails with latest electron-builder version [\#288](https://github.com/ElectronNET/Electron.NET/issues/288)
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* New Feature: Full support for Auto Updater [(Based on electron-updater - Version 4.0.6)](https://www.electron.build/auto-update)
|
||||
* New Feature: Support for set a custom static Port to ASP.NET Backend [\#155](https://github.com/ElectronNET/Electron.NET/issues/155)
|
||||
* Fixed bug: Electron tray icon TypeError ([Electron original issue](https://github.com/electron/electron/issues/7657)) (thanks [Tum4ik](https://github.com/Tum4ik))
|
||||
* Fixed bug: Wrong tray icon path in the application built via `electronize build` command (thanks [Tum4ik](https://github.com/Tum4ik))
|
||||
* Fixed bug: fix async issue where same port is considered open [\#261](https://github.com/ElectronNET/Electron.NET/issues/261) (thanks [netpoetica](https://github.com/netpoetica))
|
||||
|
||||
ElectronNET.WebApp:
|
||||
|
||||
* Fixed usage of the `Electron.Tray.Show` according fixed bugs in the ElectronNET.CLI (thanks [Tum4ik](https://github.com/Tum4ik))
|
||||
|
||||
# 5.22.13
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* Fixed bug: Menu Item visibility [\#257](https://github.com/ElectronNET/Electron.NET/issues/257)
|
||||
* Fixed bug: electron.manifest.json - singleInstance not working [\#258](https://github.com/ElectronNET/Electron.NET/issues/258)
|
||||
* Fixed security issue: ASP.NET Core process is now bound to 127.0.0.1 instead of the broader localhost [\#258](https://github.com/ElectronNET/Electron.NET/pull/266)
|
||||
|
||||
# 5.22.12
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* New Feature: Changed from **electron packager** to [**electron builder**](https://www.electron.build/)
|
||||
* New Feature: 'add hosthook' command for add a ElectronHostHook-Directory
|
||||
* Fixed bug: 'Unexpected firewall warnings' [\#181](https://github.com/ElectronNET/Electron.NET/issues/181)
|
||||
* Fixed bug: 'found 8 vulnerabilities (1 low, 5 moderate, 2 high)' [\#199](https://github.com/ElectronNET/Electron.NET/pull/199)
|
||||
* Merged pull request: Call electronize from the Path instead of via dotnet in launchSettings.json [\#243](https://github.com/ElectronNET/Electron.NET/pull/243) (thanks [grbd](https://github.com/grbd))
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* New Feature: Electron 5.0.1 support, but not all new features
|
||||
* New Feature: Auto Updater [(Based on electron-updater)](https://www.electron.build/auto-update)
|
||||
* New Feature: Splashscreen-Support
|
||||
* New Feature: HostHook-API for execute own TypeScript/JavaScript code on native Electron Main-Process
|
||||
* New Feature: Session-API functions
|
||||
* Fixed bug: Node process running after stopping app [\#96](https://github.com/ElectronNET/Electron.NET/issues/96)
|
||||
* Fixed bug: 'X and Y options to not work on Windows 10' [\#193](https://github.com/ElectronNET/Electron.NET/issues/193)
|
||||
* Fixed bug: Unable to clear cache [\#66](https://github.com/ElectronNET/Electron.NET/issues/66)
|
||||
* Merged pull request: Fix BrowserWindow::SetMenu [\#231](https://github.com/ElectronNET/Electron.NET/pull/231) thanks (thanks [CodeKenpachi](https://github.com/CodeKenpachi))
|
||||
* Merged pull request: FIX application hangs after socket reconnect [\#233](https://github.com/ElectronNET/Electron.NET/pull/233) (thanks [pedromrpinto](https://github.com/pedromrpinto))
|
||||
* Merged pull request: Reduce chance of detecting false positives when scanning subprocesses for errors. [\#236](https://github.com/ElectronNET/Electron.NET/pull/236) (thanks [BorisTheBrave](https://github.com/BorisTheBrave))
|
||||
* Merged pull request: Updates the C# API to accept floating point as in JS. [\#240](https://github.com/ElectronNET/Electron.NET/pull/240) (thanks [BorisTheBrave](https://github.com/BorisTheBrave))
|
||||
* Merged pull request: buildReleaseNuGetPackages should leave you in the same directory you … [\#241](https://github.com/ElectronNET/Electron.NET/pull/241) (thanks [BorisTheBrave](https://github.com/BorisTheBrave))
|
||||
|
||||
ElectronNET.WebApp:
|
||||
|
||||
* Implemented a sample for the new HostHook-API
|
||||
* Fixed bug: 'Electron.NET API Demo: unable to copy code?' [\#247](https://github.com/ElectronNET/Electron.NET/issues/247)
|
||||
|
||||
# 0.0.11
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* Invoke 'npm install' without --prod flag to install needed devDependencies as well.
|
||||
* Enable SourceLink
|
||||
* NuGet Package License Information updated (deprecation of licenseUrl)
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* Documentation added for WebContents.GetUrl()
|
||||
* Enable SourceLink
|
||||
* NuGet Package License Information updated (deprecation of licenseUrl)
|
||||
|
||||
# 0.0.10
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* manifestJsonFilePath fixed (thanks @smack0007)
|
||||
* Use Electron release 3.0.0 and updated packages (thanks @deinok)
|
||||
* fixes for Socket interaction (thanks @mojinxun)
|
||||
* Fixing SingleInstances (thanks @yaofeng)
|
||||
* Enhance WebContent.GetUrl (thanks @ru-sh)
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* Show Resultcode for better debugging when using Build/Start Command
|
||||
* ElectronNET.CLI is now a global dotnet tool
|
||||
|
||||
# 0.0.9
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* Better Async handling - thanks @danielmarbach
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* More options on the 'build' command, e.g. for a 32bit debug build with electron prune: build /target custom win7-x86;win32 /dotnet-configuration Debug /electron-arch ia32 /electron-params "--prune=true "
|
||||
* .NET Core project is now built with Release configuration but can be adjusted with the new params.
|
||||
* Be aware: "Breaking" (but because of the alpha status of this project, we won't use SemVer)
|
||||
|
||||
# 0.0.8
|
||||
|
||||
This version was skipped because we unfortunately released a pre-version of this on NuGet.
|
||||
|
||||
# 0.0.7
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* Fixed electronize start for macos/linux - thanks @yamachu
|
||||
* Skip NPM install on start when node_modules directory already exists
|
||||
|
||||
# 0.0.6
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* nuget packages are now release bits and have the correct assembly version
|
||||
* Version command
|
||||
* better devCleanup.cmd
|
||||
* Better Platform Support Issue - thanks to @Petermarcu
|
||||
* Start Command should now work on OSX/Linux - thanks to @r105m
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* Thread-Safe methods - thanks to @yeskunall
|
||||
|
||||
# 0.0.5
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* The last nuget package didn't contain the actual webpreferences settings with defaults - hopefully now.
|
||||
|
||||
# 0.0.4
|
||||
|
||||
ElectronNET.CLI:
|
||||
|
||||
* dotnet electronize start fixed
|
||||
|
||||
ElectronNET.API:
|
||||
|
||||
* WebPreferences settings with default values
|
||||
|
||||
# 0.0.3
|
||||
|
||||
ElectronNET.CLI:
|
||||
* Init with Debug profile
|
||||
* Build for all platforms (well... for newest OSX/Linux/Windows)
|
||||
|
||||
ElectronNET.API:
|
||||
* Moar XML documentation
|
||||
* Hybrid support (e.g. running as normal website and electron app)
|
||||
* Event bugfixing
|
||||
|
||||
# 0.0.2
|
||||
|
||||
ElectronNET.CLI:
|
||||
* Added Init to Help page
|
||||
* Added XML documentation to NuGet output
|
||||
* Maybe fixed for https://github.com/GregorBiswanger/Electron.NET/issues/2
|
||||
|
||||
ElectronNET.API:
|
||||
* Add XML documentation to NuGet output
|
||||
* Implemented Notification-, Dialog- & Tray-API
|
||||
|
||||
# 0.0.1
|
||||
|
||||
* init everything and basic functionality
|
||||
- Implemented unpackaged run-mode for development using regular .NET builds with unpackaged Electron configuration
|
||||
- Added support for building Linux packages on Windows via WSL integration
|
||||
- Enabled running and debugging Linux application outputs on Windows through WSL
|
||||
- Integrated TypeScript compilation with ASP.NET tooling for consistent builds
|
||||
- Added process orchestration supporting 8 different launch scenarios (packaged/unpackaged × console/ASP.NET × dotnet-first/electron-first)
|
||||
|
||||
### Debugging & Runtime
|
||||
|
||||
- Dramatically improved debugging experience with ASP.NET-first launch mode
|
||||
- Added Hot Reload support for ASP.NET code during development
|
||||
- Implemented proper process termination handling for all exit scenarios
|
||||
- Minimized startup times through optimized build and launch procedures
|
||||
|
||||
### Technical Improvements
|
||||
|
||||
- Enhanced splash screen handling with automatic path resolution
|
||||
- Improved ElectronHostHook integration as proper npm package dependency
|
||||
- Updated to latest TypeScript version with ESLint configuration
|
||||
- Added support for custom main.js files in projects
|
||||
- Implemented version management through common.props file
|
||||
- Added build-time Electron version compatibility validation
|
||||
|
||||
### Package & Distribution
|
||||
|
||||
- Integrated MSBuild publishing mechanisms for creating Electron packages
|
||||
- Added folder publishing support with improved parameter handling
|
||||
- Implemented automated package.json generation from MSBuild properties
|
||||
- Added GitHub release automation with proper versioning
|
||||
- Reduced package sizes by eliminating unnecessary TypeScript dependencies
|
||||
|
||||
### Migration & Compatibility
|
||||
|
||||
- Maintained backward compatibility for existing ElectronHostHook implementations
|
||||
- Removed ASP.NET requirement: Now works with simple console applications for file system or remote server HTML/JS scenarios
|
||||
- Added support for both console and ASP.NET Core application types
|
||||
- Preserved all existing Electron API functionality while modernizing architecture
|
||||
- Added migration path for existing projects through updated package structure
|
||||
|
||||
This represents a comprehensive modernization of Electron.NET, addressing the major pain points around debugging, build complexity, and platform limitations while maintaining full API compatibility.
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017-2023 Gregor Biswanger, Robert Mühsig
|
||||
Copyright (c) 2017-2025 Gregor Biswanger, Robert Mühsig, Florian Rappl
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<packageSources>
|
||||
<config>
|
||||
<add key="repositoryPath" value="artifacts" />
|
||||
</config>
|
||||
<packageSources>
|
||||
<clear />
|
||||
<add key="LocalDev" value="artifacts" />
|
||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||
</packageSources>
|
||||
</packageSources>
|
||||
</configuration>
|
||||
378
README.md
378
README.md
@@ -2,191 +2,186 @@
|
||||
|
||||
[](https://donorbox.org/electron-net) [](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [](https://github.com/ElectronNET/Electron.NET/actions/workflows/ci.yml)
|
||||
|
||||
Build cross platform desktop apps with .NET 6 and Blazor, ASP.NET Core (Razor Pages, MVC).
|
||||
# Electron.NET Core is here!
|
||||
|
||||
Electron.NET is a __wrapper__ around a native Electron application with an embedded ASP.NET Core application. Via our Electron.NET IPC bridge we can invoke Electron APIs from .NET.
|
||||
## A Complete Transformation
|
||||
|
||||
The CLI extensions hosts our toolset to build and start Electron.NET applications.
|
||||
`ElectronNET.Core` represents a fundamental modernization of Electron.NET, addressing years of accumulated pain points while preserving full API compatibility. This isn't just an update — it's a complete rethinking of how .NET developers build and debug cross-platform desktop applications with Electron.
|
||||
|
||||
## Wait - you host a .NET Core app inside Electron? Why?
|
||||
Read more: [**What's New in `ElectronNET.Core`**](https://github.com/ElectronNET/Electron.NET/wiki/What's-New)
|
||||
|
||||
Well... there are lots of different approaches how to get a X-plat desktop app running. We thought it would be nice for .NET devs to use the ASP.NET Core environment and just embed it inside a pretty robust X-plat enviroment called Electron. Porting Electron to .NET is not a goal of this project, at least we don't have any clue how to do it. We just combine ASP.NET Core & Electron.
|
||||
Build cross platform desktop applications with .NET 6/8/10 - from console apps to ASP.NET Core (Razor Pages, MVC) to Blazor.
|
||||
|
||||
## Wait - how does that work exactly?
|
||||
|
||||
Well... there are lots of different approaches how to get a X-plat desktop app running. Electron.NET provides a range of ways to build .NET-based solutions using Electron at the side of presentation.
|
||||
|
||||
While the classic Electron.NET setup (using an ASP.NET host run by the Electron side) is still the primary way, there's more flexibility now. Both .NET and Electron are now able to launch the other for better lifetime management, and when you don't need a local web server (like when running content from files or remote servers), you can drop the ASP.NET stack altogether and go with a lightweight console app instead.
|
||||
|
||||
## 📦 NuGet
|
||||
|
||||
[ ElectronNET.API ](https://www.nuget.org/packages/ElectronNET.API/) | [ ElectronNET.CLI](https://www.nuget.org/packages/ElectronNET.CLI/)
|
||||
* ElectronNET.Core: [](https://www.nuget.org/packages/ElectronNET.Core.API/)
|
||||
* ElectronNET.Core.API: [](https://www.nuget.org/packages/ElectronNET.Core.API/)
|
||||
* ElectronNET.Core.AspNet: [](https://www.nuget.org/packages/ElectronNET.Core.AspNet/)
|
||||
|
||||
## 🛠 Requirements to Run
|
||||
|
||||
The current Electron.NET CLI builds Windows/macOS/Linux binaries. Our API uses .NET 6, so our minimum base OS is the same as [.NET 6](https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md).
|
||||
You should have installed:
|
||||
|
||||
Also you should have installed:
|
||||
* .NET 6/8 or later.
|
||||
* The minimum base OS is the same as [.NET 6](https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md) / [.NET 8](https://github.com/dotnet/core/blob/main/release-notes/8.0/supported-os.md).
|
||||
* Node.JS using at least [Version 22.x](https://nodejs.org).
|
||||
|
||||
* npm [contained in nodejs (at least Version 16.17.1)](https://nodejs.org)
|
||||
## 👩🏫 Usage with ASP.NET
|
||||
|
||||
## 💬 Community
|
||||
|
||||
[](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||
|
||||
Besides the chat on Gitter and the issues [discussed here](https://github.com/ElectronNET/Electron.NET/issues) you can also use [StackOverflow](https://stackoverflow.com/questions/tagged/electron.net) with the tag `electron.net`.
|
||||
|
||||
If you want to sponsor the further maintenance and development of this project [see the donate section](#🙏-donate).
|
||||
|
||||
## 👩🏫 Usage
|
||||
|
||||
To activate and communicate with the "native" (sort of native...) Electron API include the [ElectronNET.API NuGet package](https://www.nuget.org/packages/ElectronNET.API/) in your ASP.NET Core app.
|
||||
- Create a new ASP.NET Core project
|
||||
- Install the following two NuGet packages:
|
||||
|
||||
```ps1
|
||||
PM> Install-Package ElectronNET.API
|
||||
dotnet add package ElectronNET.Core
|
||||
|
||||
dotnet add package ElectronNET.Core.AspNet
|
||||
```
|
||||
|
||||
## Setup Using Minimal-API
|
||||
### Classic ASP.NET Core
|
||||
|
||||
You start Electron.NET up with an `UseElectron` WebHostBuilder-Extension and open the Electron Window:
|
||||
#### Enable Electron.NET on Startup
|
||||
|
||||
### Program.cs
|
||||
To do so, use the `UseElectron` extension method on a `WebApplicationBuilder`, an `IWebHostBuilder` or any descendants.
|
||||
|
||||
> [!NOTE]
|
||||
> New in Electron.NET Core is that you provide a callback method as an argument to `UseElectron()`, which ensures that you get to know the right moment to set up your application UI.
|
||||
|
||||
#### Program.cs
|
||||
|
||||
```csharp
|
||||
using ElectronNET.API;
|
||||
using ElectronNET.API.Entities;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.WebHost.UseElectron(args);
|
||||
|
||||
// Is optional, but you can use the Electron.NET API-Classes directly with DI (relevant if you wont more encoupled code)
|
||||
builder.Services.AddElectron();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
...
|
||||
|
||||
await app.StartAsync();
|
||||
|
||||
// Open the Electron-Window here
|
||||
await Electron.WindowManager.CreateWindowAsync();
|
||||
|
||||
app.WaitForShutdown();
|
||||
```
|
||||
|
||||
## Setup using Normal-API
|
||||
|
||||
### Program.cs
|
||||
|
||||
You start Electron.NET up with an `UseElectron` WebHostBuilder-Extension.
|
||||
|
||||
```csharp
|
||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
||||
Host.CreateDefaultBuilder(args)
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder.UseElectron(args);
|
||||
webBuilder.UseStartup<Startup>();
|
||||
});
|
||||
```
|
||||
|
||||
### Startup.cs
|
||||
|
||||
Open the Electron Window in the *Startup.cs* file:
|
||||
|
||||
```csharp
|
||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
//...
|
||||
WebHost.CreateDefaultBuilder(args)
|
||||
.UseElectron(args, ElectronAppReady)
|
||||
.UseStartup<Startup>()
|
||||
.Build()
|
||||
.Run();
|
||||
}
|
||||
|
||||
Electron.WindowManager.CreateWindowAsync();
|
||||
public static async Task ElectronAppReady()
|
||||
{
|
||||
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
|
||||
new BrowserWindowOptions { Show = false });
|
||||
|
||||
browserWindow.OnReadyToShow += () => browserWindow.Show();
|
||||
}
|
||||
```
|
||||
|
||||
## 🚀 Starting the Application
|
||||
### Minimal API Example
|
||||
|
||||
To start the application make sure you have installed the "[ElectronNET.CLI](https://www.nuget.org/packages/ElectronNET.CLI/)" packages as global tool:
|
||||
For a minimal API you can use:
|
||||
|
||||
```sh
|
||||
dotnet tool install ElectronNET.CLI -g
|
||||
```csharp
|
||||
using ElectronNET;
|
||||
using ElectronNET.API;
|
||||
using ElectronNET.API.Entities;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddRazorPages();
|
||||
builder.Services.AddElectron(); // <- might be useful to set up DI
|
||||
|
||||
builder.UseElectron(args, async () =>
|
||||
{
|
||||
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
|
||||
new BrowserWindowOptions { Show = false, AutoHideMenuBar = true });
|
||||
|
||||
browserWindow.OnReadyToShow += () => browserWindow.Show();
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Error");
|
||||
}
|
||||
|
||||
app.UseStaticFiles();
|
||||
app.UseRouting();
|
||||
app.UseAuthorization();
|
||||
app.MapRazorPages();
|
||||
app.Run();
|
||||
```
|
||||
|
||||
At the first time, you need an Electron.NET project initialization. Type the following command in your ASP.NET Core folder:
|
||||
### Blazor
|
||||
|
||||
```sh
|
||||
electronize init
|
||||
For a project with Blazor you can use:
|
||||
|
||||
```cs
|
||||
using ElectronNET.API;
|
||||
using ElectronNET.API.Entities;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services
|
||||
.AddRazorComponents()
|
||||
.AddInteractiveWebAssemblyComponents();
|
||||
|
||||
builder.Services.AddElectron(); // <-- might be useful to set up DI
|
||||
|
||||
builder.UseElectron(args, async () =>
|
||||
{
|
||||
var options = new BrowserWindowOptions {
|
||||
Show = false,
|
||||
IsRunningBlazor = true, // <-- crucial
|
||||
};
|
||||
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux())
|
||||
options.AutoHideMenuBar = true;
|
||||
var browserWindow = await Electron.WindowManager.CreateWindowAsync(options);
|
||||
browserWindow.OnReadyToShow += () => browserWindow.Show();
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseWebAssemblyDebugging();
|
||||
}
|
||||
else
|
||||
{
|
||||
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
||||
}
|
||||
|
||||
app.UseStaticFiles();
|
||||
app.UseAntiforgery();
|
||||
|
||||
app.MapRazorComponents<BlazorApp.Components.App>()
|
||||
.AddInteractiveWebAssemblyRenderMode();
|
||||
|
||||
app.Run();
|
||||
```
|
||||
|
||||
* Now a electronnet.manifest.json should appear in your ASP.NET Core project
|
||||
* Now run the following:
|
||||
The `IsRunningBlazor` option makes sure to set up the renderer in a way that Blazor can just run without any interference. This includes things such as HMR for development.
|
||||
|
||||
```sh
|
||||
electronize start
|
||||
```
|
||||
## 🚀 Starting and Debugging the Application
|
||||
|
||||
### Note
|
||||
|
||||
> Only the first `electronize start` is slow. The next will go on faster.
|
||||
|
||||
## 🔭 Develop Electron.NET apps using a file watcher
|
||||
|
||||
The file watcher is included with version 8.31.1 of Electron.NET. For example, a file change can trigger compilation, test execution, or deployment. The Electron.NET window will automatically refresh and new code changes will be visible more quickly. The following Electron.NET CLI command is required:
|
||||
|
||||
```sh
|
||||
electronize start /watch
|
||||
```
|
||||
|
||||
### Note
|
||||
|
||||
> Only the first `electronize start` is slow. The next will go on faster.
|
||||
|
||||
## 🐞 Debugging the Application
|
||||
|
||||
Start your Electron.NET application with the Electron.NET CLI command. In Visual Studio attach to your running application instance. Go in the __Debug__ Menu and click on __Attach to Process...__. Sort by your projectname on the right and select it on the list.
|
||||
Just press `F5` in Visual Studio or use dotnet for debugging.
|
||||
|
||||
## 📔 Usage of the Electron API
|
||||
|
||||
A complete documentation will follow. Until then take a look in the source code of the sample application:
|
||||
[Electron.NET API Demos](https://github.com/ElectronNET/electron.net-api-demos)
|
||||
Complete documentation is available on the Wiki.
|
||||
|
||||
In this YouTube video, we show you how you can create a new project, use the Electron.NET API, debug a application and build an executable desktop app for Windows: [Electron.NET - Getting Started](https://www.youtube.com/watch?v=nuM6AojRFHk)
|
||||
|
||||
## ⛏ Building Release Artifacts
|
||||
|
||||
Here you need the Electron.NET CLI as well. Type the following command in your ASP.NET Core folder:
|
||||
|
||||
```sh
|
||||
electronize build /target win
|
||||
```
|
||||
|
||||
There are additional platforms available:
|
||||
|
||||
```sh
|
||||
electronize build /target win
|
||||
electronize build /target osx
|
||||
electronize build /target linux
|
||||
```
|
||||
|
||||
Those three "default" targets will produce x64 packages for those platforms.
|
||||
|
||||
For certain NuGet packages or certain scenarios you may want to build a pure x86 application. To support those things you can define the desired [.NET Core runtime](https://docs.microsoft.com/en-us/dotnet/core/rid-catalog), the [electron platform](https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#platform) and [electron architecture](https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#arch) like this:
|
||||
|
||||
```sh
|
||||
electronize build /target custom "win7-x86;win32" /electron-arch ia32
|
||||
```
|
||||
|
||||
The end result should be an electron app under your __/bin/desktop__ folder.
|
||||
|
||||
### Note
|
||||
|
||||
> macOS builds can't be created on Windows machines because they require symlinks that aren't supported on Windows (per [this Electron issue](https://github.com/electron-userland/electron-packager/issues/71)). macOS builds can be produced on either Linux or macOS machines.
|
||||
|
||||
## 🔄 Update
|
||||
|
||||
After an update to the latest Electron.API package, an update to the latest Electron.CLI is always required. In addition, always update the CLI via NuGet:
|
||||
|
||||
```sh
|
||||
dotnet tool update ElectronNET.CLI -g
|
||||
```
|
||||
> [!NOTE]
|
||||
> The video hasn't been updated for the changes in ElectronNET.Core, so it is partially outdated.
|
||||
|
||||
## 👨💻 Authors
|
||||
|
||||
* **[Gregor Biswanger](https://github.com/GregorBiswanger)** - (Microsoft MVP, Intel Black Belt and Intel Software Innovator) is a freelance lecturer, consultant, trainer, author and speaker. He is a consultant for large and medium-sized companies, organizations and agencies for software architecture, web- and cross-platform development. You can find Gregor often on the road attending or speaking at international conferences. - [Cross-Platform-Blog](http://www.cross-platform-blog.com) - Twitter [@BFreakout](https://www.twitter.com/BFreakout)
|
||||
* **[Dr. Florian Rappl](https://github.com/FlorianRappl)** - Software Developer - from Munich, Germany. Microsoft MVP & Web Geek. - [The Art of Micro Frontends](https://microfrontends.art) - [Homepage](https://florian-rappl.de) - Twitter [@florianrappl](https://twitter.com/florianrappl)
|
||||
* **[softworkz](https://github.com/softworkz)** - Full Range Developer - likes to start where others gave up. MS MVP alumni and Munich citizen as well.
|
||||
* **[Robert Muehsig](https://github.com/robertmuehsig)** - Software Developer - from Dresden, Germany, now living & working in Switzerland. Microsoft MVP & Web Geek. - [codeinside Blog](https://blog.codeinside.eu) - Twitter [@robert0muehsig](https://twitter.com/robert0muehsig)
|
||||
|
||||
See also the list of [contributors](https://github.com/ElectronNET/Electron.NET/graphs/contributors) who participated in this project.
|
||||
@@ -196,16 +191,6 @@ See also the list of [contributors](https://github.com/ElectronNET/Electron.NET/
|
||||
Feel free to submit a pull request if you find any bugs (to see a list of active issues, visit the [Issues section](https://github.com/ElectronNET/Electron.NET/issues).
|
||||
Please make sure all commits are properly documented.
|
||||
|
||||
## 🧪 Working with this Repo
|
||||
|
||||
This video provides an introduction to development for Electron.NET: [Electron.NET - Contributing Getting Started](https://youtu.be/Po-saU_Z6Ws)
|
||||
|
||||
This repository consists of the main parts (API & CLI) and it's own "playground" ASP.NET Core application. Both main parts produce local NuGet packages, that are versioned with 99.0.0. The first thing you will need is to run one of the build scripts (.cmd or .ps1 for Windows, the .sh for macOS/Linux).
|
||||
|
||||
If you look for pure __[demo projects](https://github.com/ElectronNET)__ checkout the other repositories.
|
||||
|
||||
The problem working with this repository is, that NuGet has a pretty aggressive cache, see [here for further information](https://github.com/ElectronNET/Electron.NET/wiki).
|
||||
|
||||
## 🙏 Donate
|
||||
|
||||
We do this open source work in our free time. If you'd like us to invest more time on it, please [donate](https://donorbox.org/electron-net). Donation can be used to increase some issue priority. Thank you!
|
||||
@@ -221,106 +206,7 @@ Any support appreciated! 🍻
|
||||
|
||||
## 🎉 License
|
||||
|
||||
MIT-licensed. See [LICENSE](./LICENSE) for details.
|
||||
MIT-licensed. See [LICENSE](https://github.com/ElectronNET/Electron.NET/blob/main/LICENSE) for details.
|
||||
|
||||
**Enjoy!**
|
||||
|
||||
## 📝 Important notes
|
||||
|
||||
### ElectronNET.API & ElectronNET.CLI Version 9.31.2
|
||||
|
||||
Make sure you also have the new Electron.NET API & CLI 9.31.2 version.
|
||||
|
||||
```sh
|
||||
dotnet tool update ElectronNET.CLI -g
|
||||
```
|
||||
|
||||
This now uses [electron-builder](https://www.electron.build/configuration/configuration) and the necessary configuration to build is made in the **electron.manifest.json** file (on the build part). In addition, own Electron.NET configurations are stored (on the root).
|
||||
|
||||
Please make sure that your **electron.manifest.json** file has the following new structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"executable": "{{executable}}",
|
||||
"splashscreen": {
|
||||
"imageFile": ""
|
||||
},
|
||||
"name": "{{executable}}",
|
||||
"author": "",
|
||||
"singleInstance": false,
|
||||
"build": {
|
||||
"appId": "com.{{executable}}.app",
|
||||
"productName": "{{executable}}",
|
||||
"copyright": "Copyright © 2020",
|
||||
"buildVersion": "1.0.0",
|
||||
"compression": "maximum",
|
||||
"directories": {
|
||||
"output": "../../../bin/Desktop"
|
||||
},
|
||||
"extraResources": [
|
||||
{
|
||||
"from": "./bin",
|
||||
"to": "bin",
|
||||
"filter": ["**/*"]
|
||||
}
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"from": "./ElectronHostHook/node_modules",
|
||||
"to": "ElectronHostHook/node_modules",
|
||||
"filter": ["**/*"]
|
||||
},
|
||||
"**/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### ElectronNET.CLI Version 0.0.9
|
||||
|
||||
In the Version 0.0.9 the CLI was not a global tool and needed to be registered like this in the *.csproj*:
|
||||
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<DotNetCliToolReference Include="ElectronNET.CLI" Version="0.0.9" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
After you edited the *.csproj* file, you need to restore your NuGet packages within your Project. Run the following command in your ASP.NET Core folder:
|
||||
|
||||
```sh
|
||||
dotnet restore
|
||||
```
|
||||
|
||||
If you still use this version you will need to invoke it like this:
|
||||
|
||||
```sh
|
||||
electronize ...
|
||||
```
|
||||
|
||||
### Node.js Integration
|
||||
|
||||
Electron.NET requires Node.js integration to be enabled for IPC to function. If you are not using the IPC functionality you can disable Node.js integration like so:
|
||||
|
||||
```csharp
|
||||
WebPreferences wp = new WebPreferences();
|
||||
wp.NodeIntegration = false;
|
||||
BrowserWindowOptions browserWindowOptions = new BrowserWindowOptions
|
||||
{
|
||||
WebPreferences = wp
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
### Dependency Injection
|
||||
|
||||
ElectronNET.API can be added to your DI container within the `Startup` class. All of the modules available in Electron will be added as Singletons.
|
||||
|
||||
```csharp
|
||||
using ElectronNET.API;
|
||||
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddElectron();
|
||||
}
|
||||
```
|
||||
|
||||
27
docs/.docproj/DocProj.props
Normal file
27
docs/.docproj/DocProj.props
Normal file
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetPlatformVersion>8.1</TargetPlatformVersion>
|
||||
<IsCodeSharingProject>true</IsCodeSharingProject>
|
||||
<DefineCommonItemSchemas>true</DefineCommonItemSchemas>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<MdIncludes>**/*.md;**/*.markdown</MdIncludes>
|
||||
<ImageIncludes>**/*.png;**/*.bmp;**/*.jpg;**/*.gif;**/*.mp4</ImageIncludes>
|
||||
<WebIncludes>**/*.css;**/*.js;**/*.json</WebIncludes>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="**/*" />
|
||||
<Content Remove="**/*" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(ImageIncludes)" />
|
||||
<None Include="$(WebIncludes)" />
|
||||
<None Include="$(MdIncludes)" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
23
docs/.docproj/DocProj.targets
Normal file
23
docs/.docproj/DocProj.targets
Normal file
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<ProjectCapability Include="SourceItemsFromImports;SharedImports;SharedAssetsProject"/>
|
||||
<ProjectCapability Include="HandlesOwnReload"/>
|
||||
<ProjectCapability Include="UserSourceItems"/>
|
||||
<ProjectCapability Include="OpenProjectFile"/>
|
||||
<ProjectCapability Include="UseFileGlobs"/>
|
||||
<ProjectCapability Include="SingleFileGenerators"/>
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="Compile">
|
||||
</Target>
|
||||
|
||||
<Target Name="Build">
|
||||
</Target>
|
||||
|
||||
<Target Name="Clean">
|
||||
</Target>
|
||||
|
||||
<Target Name="_CheckForInvalidConfigurationAndPlatform">
|
||||
</Target>
|
||||
</Project>
|
||||
489
docs/API/App.md
Normal file
489
docs/API/App.md
Normal file
@@ -0,0 +1,489 @@
|
||||
# Electron.App
|
||||
|
||||
Control your application's event lifecycle.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.App` API provides comprehensive control over your application's lifecycle, including startup, shutdown, window management, and system integration. It handles application-level events and provides methods for managing the overall application state.
|
||||
|
||||
## Properties
|
||||
|
||||
#### 📋 `CommandLine`
|
||||
A `CommandLine` object that allows you to read and manipulate the command line arguments that Chromium uses.
|
||||
|
||||
#### 📋 `IsReady`
|
||||
Application host fully started.
|
||||
|
||||
#### 📋 `Name`
|
||||
A string property that indicates the current application's name, which is the name in the application's package.json file.
|
||||
|
||||
Usually the name field of package.json is a short lowercase name, according to the npm modules spec. You should usually also specify a productName field, which is your application's full capitalized name, and which will be preferred over name by Electron.
|
||||
|
||||
#### 📋 `NameAsync`
|
||||
A `Task<string>` property that indicates the current application's name, which is the name in the application's package.json file.
|
||||
|
||||
Usually the name field of package.json is a short lowercase name, according to the npm modules spec. You should usually also specify a productName field, which is your application's full capitalized name, and which will be preferred over name by Electron.
|
||||
|
||||
#### 📋 `UserAgentFallback`
|
||||
A string which is the user agent string Electron will use as a global fallback.
|
||||
|
||||
This is the user agent that will be used when no user agent is set at the webContents or session level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used.
|
||||
|
||||
#### 📋 `UserAgentFallbackAsync`
|
||||
A `Task<string>` which is the user agent string Electron will use as a global fallback.
|
||||
|
||||
This is the user agent that will be used when no user agent is set at the webContents or session level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `void AddRecentDocument(string path)`
|
||||
Adds path to the recent documents list. This list is managed by the OS. On Windows you can visit the list from the task bar, and on macOS you can visit it from dock menu.
|
||||
|
||||
#### 🧊 `void ClearRecentDocuments()`
|
||||
Clears the recent documents list.
|
||||
|
||||
#### 🧊 `void Exit(int exitCode = 0)`
|
||||
All windows will be closed immediately without asking user and the BeforeQuit and WillQuit events will not be emitted.
|
||||
|
||||
**Parameters:**
|
||||
- `exitCode` - Exits immediately with exitCode. exitCode defaults to 0.
|
||||
|
||||
#### 🧊 `void Focus()`
|
||||
On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window.
|
||||
|
||||
#### 🧊 `void Focus(FocusOptions focusOptions)`
|
||||
On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window.
|
||||
|
||||
You should seek to use the `FocusOptions.Steal` option as sparingly as possible.
|
||||
|
||||
**Parameters:**
|
||||
- `focusOptions` - Focus options
|
||||
|
||||
#### 🧊 `Task<ProcessMetric[]> GetAppMetricsAsync(CancellationToken cancellationToken = default)`
|
||||
Memory and cpu usage statistics of all the processes associated with the app.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Array of ProcessMetric objects that correspond to memory and cpu usage statistics of all the processes associated with the app.
|
||||
|
||||
#### 🧊 `Task<string> GetAppPathAsync(CancellationToken cancellationToken = default)`
|
||||
The current application directory.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The current application directory.
|
||||
|
||||
#### 🧊 `Task<int> GetBadgeCountAsync(CancellationToken cancellationToken = default)`
|
||||
The current value displayed in the counter badge.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The current value displayed in the counter badge.
|
||||
|
||||
#### 🧊 `Task<string> GetCurrentActivityTypeAsync(CancellationToken cancellationToken = default)`
|
||||
The type of the currently running activity.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The type of the currently running activity.
|
||||
|
||||
#### 🧊 `Task<GPUFeatureStatus> GetGpuFeatureStatusAsync(CancellationToken cancellationToken = default)`
|
||||
The Graphics Feature Status from chrome://gpu/.
|
||||
|
||||
Note: This information is only usable after the gpu-info-update event is emitted.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The Graphics Feature Status from chrome://gpu/.
|
||||
|
||||
#### 🧊 `Task<JumpListSettings> GetJumpListSettingsAsync(CancellationToken cancellationToken = default)`
|
||||
Jump List settings for the application.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Jump List settings.
|
||||
|
||||
#### 🧊 `Task<string> GetLocaleAsync(CancellationToken cancellationToken = default)`
|
||||
The current application locale. Possible return values are documented [here](https://www.electronjs.org/docs/api/locales).
|
||||
|
||||
Note: When distributing your packaged app, you have to also ship the locales folder.
|
||||
|
||||
Note: On Windows, you have to call it after the Ready events gets emitted.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The current application locale.
|
||||
|
||||
#### 🧊 `Task<LoginItemSettings> GetLoginItemSettingsAsync(CancellationToken cancellationToken = default)`
|
||||
If you provided path and args options to SetLoginItemSettings then you need to pass the same arguments here for LoginItemSettings.OpenAtLogin to be set correctly.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Login item settings.
|
||||
|
||||
#### 🧊 `Task<string> GetPathAsync(PathName pathName, CancellationToken cancellationToken = default)`
|
||||
The path to a special directory. If GetPathAsync is called without called SetAppLogsPath being called first, a default directory will be created equivalent to calling SetAppLogsPath without a path parameter.
|
||||
|
||||
**Parameters:**
|
||||
- `pathName` - Special directory.
|
||||
|
||||
**Returns:**
|
||||
|
||||
A path to a special directory or file associated with name.
|
||||
|
||||
#### 🧊 `Task<string> GetVersionAsync(CancellationToken cancellationToken = default)`
|
||||
The version of the loaded application. If no version is found in the application's package.json file, the version of the current bundle or executable is returned.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The version of the loaded application.
|
||||
|
||||
#### 🧊 `Task<bool> HasSingleInstanceLockAsync(CancellationToken cancellationToken = default)`
|
||||
This method returns whether or not this instance of your app is currently holding the single instance lock. You can request the lock with RequestSingleInstanceLockAsync and release with ReleaseSingleInstanceLock.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether this instance of your app is currently holding the single instance lock.
|
||||
|
||||
#### 🧊 `void Hide()`
|
||||
Hides all application windows without minimizing them.
|
||||
|
||||
#### 🧊 `Task<int> ImportCertificateAsync(ImportCertificateOptions options, CancellationToken cancellationToken = default)`
|
||||
Imports the certificate in pkcs12 format into the platform certificate store. callback is called with the result of import operation, a value of 0 indicates success while any other value indicates failure according to chromium net_error_list.
|
||||
|
||||
**Parameters:**
|
||||
- `options` - Import certificate options
|
||||
- `cancellationToken` - The cancellation token
|
||||
|
||||
**Returns:**
|
||||
|
||||
Result of import. Value of 0 indicates success.
|
||||
|
||||
#### 🧊 `void InvalidateCurrentActivity()`
|
||||
Invalidates the current Handoff user activity.
|
||||
|
||||
#### 🧊 `Task<bool> IsAccessibilitySupportEnabledAsync(CancellationToken cancellationToken = default)`
|
||||
true if Chrome's accessibility support is enabled, false otherwise. This API will return true if the use of assistive technologies, such as screen readers, has been detected. See Chromium's accessibility docs for more details.
|
||||
|
||||
**Returns:**
|
||||
|
||||
true if Chrome's accessibility support is enabled, false otherwise.
|
||||
|
||||
#### 🧊 `Task<bool> IsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)`
|
||||
This method checks if the current executable is the default handler for a protocol (aka URI scheme).
|
||||
|
||||
Note: On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking ~/Library/Preferences/com.apple.LaunchServices.plist on the macOS machine. Please refer to Apple's documentation for details.
|
||||
|
||||
The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.
|
||||
|
||||
**Parameters:**
|
||||
- `protocol` - The name of your protocol, without ://
|
||||
- `cancellationToken` - The cancellation token
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the current executable is the default handler for a protocol (aka URI scheme).
|
||||
|
||||
#### 🧊 `Task<bool> IsUnityRunningAsync(CancellationToken cancellationToken = default)`
|
||||
Whether the current desktop environment is Unity launcher.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the current desktop environment is Unity launcher.
|
||||
|
||||
#### 🧊 `void Quit()`
|
||||
Try to close all windows. The BeforeQuit event will be emitted first. If all windows are successfully closed, the WillQuit event will be emitted and by default the application will terminate. This method guarantees that all beforeunload and unload event handlers are correctly executed. It is possible that a window cancels the quitting by returning false in the beforeunload event handler.
|
||||
|
||||
#### 🧊 `void ReleaseSingleInstanceLock()`
|
||||
Releases all locks that were created by makeSingleInstance. This will allow multiple instances of the application to once again run side by side.
|
||||
|
||||
#### 🧊 `void Relaunch()`
|
||||
Relaunches the app when current instance exits. By default the new instance will use the same working directory and command line arguments with current instance.
|
||||
|
||||
Note that this method does not quit the app when executed, you have to call Quit or Exit after calling Relaunch() to make the app restart.
|
||||
|
||||
When Relaunch() is called for multiple times, multiple instances will be started after current instance exited.
|
||||
|
||||
#### 🧊 `void Relaunch(RelaunchOptions relaunchOptions)`
|
||||
Relaunches the app when current instance exits. By default the new instance will use the same working directory and command line arguments with current instance. When RelaunchOptions.Args is specified, the RelaunchOptions.Args will be passed as command line arguments instead. When RelaunchOptions.ExecPath is specified, the RelaunchOptions.ExecPath will be executed for relaunch instead of current app.
|
||||
|
||||
Note that this method does not quit the app when executed, you have to call Quit or Exit after calling Relaunch() to make the app restart.
|
||||
|
||||
When Relaunch() is called for multiple times, multiple instances will be started after current instance exited.
|
||||
|
||||
**Parameters:**
|
||||
- `relaunchOptions` - Options for the relaunch
|
||||
|
||||
#### 🧊 `Task<bool> RemoveAsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)`
|
||||
This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler.
|
||||
|
||||
**Parameters:**
|
||||
- `protocol` - The name of your protocol, without ://
|
||||
- `cancellationToken` - The cancellation token
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the call succeeded.
|
||||
|
||||
#### 🧊 `Task<bool> RequestSingleInstanceLockAsync(Action<string[], string> newInstanceOpened, CancellationToken cancellationToken = default)`
|
||||
The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately.
|
||||
|
||||
I.e.This method returns true if your process is the primary instance of your application and your app should continue loading. It returns false if your process should immediately quit as it has sent its parameters to another instance that has already acquired the lock.
|
||||
|
||||
On macOS, the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the open-file and open-url events will be emitted for that.However when users start your app in command line, the system's single instance mechanism will be bypassed, and you have to use this method to ensure single instance.
|
||||
|
||||
**Parameters:**
|
||||
- `newInstanceOpened` - Lambda with an array of the second instance's command line arguments. The second parameter is the working directory path.
|
||||
- `cancellationToken` - The cancellation token
|
||||
|
||||
**Returns:**
|
||||
|
||||
This method returns false if your process is the primary instance of the application and your app should continue loading. And returns true if your process has sent its parameters to another instance, and you should immediately quit.
|
||||
|
||||
#### 🧊 `void ResignCurrentActivity()`
|
||||
Marks the current Handoff user activity as inactive without invalidating it.
|
||||
|
||||
#### 🧊 `void SetAccessibilitySupportEnabled(bool enabled)`
|
||||
Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See Chromium's accessibility docs for more details. Disabled (false) by default.
|
||||
|
||||
This API must be called after the Ready event is emitted.
|
||||
|
||||
Note: Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
|
||||
|
||||
**Parameters:**
|
||||
- `enabled` - Enable or disable accessibility tree rendering
|
||||
|
||||
#### 🧊 `void SetAppLogsPath(string path)`
|
||||
Sets or creates a directory your app's logs which can then be manipulated with GetPathAsync or SetPath.
|
||||
|
||||
Calling SetAppLogsPath without a path parameter will result in this directory being set to ~/Library/Logs/YourAppName on macOS, and inside the userData directory on Linux and Windows.
|
||||
|
||||
**Parameters:**
|
||||
- `path` - A custom path for your logs. Must be absolute
|
||||
|
||||
#### 🧊 `void SetAppUserModelId(string id)`
|
||||
Changes the Application User Model ID to id.
|
||||
|
||||
**Parameters:**
|
||||
- `id` - Model Id
|
||||
|
||||
#### 🧊 `Task<bool> SetAsDefaultProtocolClientAsync(string protocol, CancellationToken cancellationToken = default)`
|
||||
Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with your-protocol:// will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter.
|
||||
|
||||
Note: On macOS, you can only register protocols that have been added to your app's info.plist, which cannot be modified at runtime. However, you can change the file during build time via Electron Forge, Electron Packager, or by editing info.plist with a text editor. Please refer to Apple's documentation for details.
|
||||
|
||||
Note: In a Windows Store environment (when packaged as an appx) this API will return true for all calls but the registry key it sets won't be accessible by other applications. In order to register your Windows Store application as a default protocol handler you must declare the protocol in your manifest.
|
||||
|
||||
The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.
|
||||
|
||||
**Parameters:**
|
||||
- `protocol` - The name of your protocol, without ://. For example, if you want your app to handle electron:// links, call this method with electron as the parameter.
|
||||
- `cancellationToken` - The cancellation token
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the call succeeded.
|
||||
|
||||
#### 🧊 `Task<bool> SetBadgeCountAsync(int count, CancellationToken cancellationToken = default)`
|
||||
Sets the counter badge for current app. Setting the count to 0 will hide the badge. On macOS it shows on the dock icon. On Linux it only works for Unity launcher.
|
||||
|
||||
Note: Unity launcher requires the existence of a .desktop file to work, for more information please read Desktop Environment Integration.
|
||||
|
||||
**Parameters:**
|
||||
- `count` - Counter badge
|
||||
- `cancellationToken` - The cancellation token
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the call succeeded.
|
||||
|
||||
#### 🧊 `void SetJumpList(JumpListCategory[] categories)`
|
||||
Sets or removes a custom Jump List for the application. If categories is null the previously set custom Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows).
|
||||
|
||||
Note: If a JumpListCategory object has neither the Type nor the Name property set then its Type is assumed to be tasks. If the Name property is set but the Type property is omitted then the Type is assumed to be custom.
|
||||
|
||||
Note: Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until after the next successful call to SetJumpList. Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. The list of removed items can be obtained using GetJumpListSettingsAsync.
|
||||
|
||||
**Parameters:**
|
||||
- `categories` - Array of JumpListCategory objects
|
||||
|
||||
#### 🧊 `void SetLoginItemSettings(LoginSettings loginSettings)`
|
||||
Set the app's login item settings.
|
||||
|
||||
To work with Electron's autoUpdater on Windows, which uses Squirrel, you'll want to set the launch path to Update.exe, and pass arguments that specify your application name.
|
||||
|
||||
**Parameters:**
|
||||
- `loginSettings` - Login settings
|
||||
|
||||
#### 🧊 `void SetPath(PathName name, string path)`
|
||||
Overrides the path to a special directory or file associated with name. If the path specifies a directory that does not exist, an Error is thrown. In that case, the directory should be created with fs.mkdirSync or similar.
|
||||
|
||||
You can only override paths of a name defined in GetPathAsync.
|
||||
|
||||
By default, web pages' cookies and caches will be stored under the PathName.UserData directory. If you want to change this location, you have to override the PathName.UserData path before the Ready event of the App module is emitted.
|
||||
|
||||
**Parameters:**
|
||||
- `name` - Special directory name
|
||||
- `path` - New path to a special directory
|
||||
|
||||
#### 🧊 `void SetUserActivity(string type, object userInfo)`
|
||||
Creates an NSUserActivity and sets it as the current activity. The activity is eligible for Handoff to another device afterward.
|
||||
|
||||
**Parameters:**
|
||||
- `type` - Uniquely identifies the activity. Maps to NSUserActivity.activityType.
|
||||
- `userInfo` - App-specific state to store for use by another device
|
||||
|
||||
#### 🧊 `Task<bool> SetUserTasksAsync(UserTask[] userTasks, CancellationToken cancellationToken = default)`
|
||||
Adds tasks to the UserTask category of the JumpList on Windows.
|
||||
|
||||
Note: If you'd like to customize the Jump List even more use SetJumpList instead.
|
||||
|
||||
**Parameters:**
|
||||
- `userTasks` - Array of UserTask objects
|
||||
- `cancellationToken` - The cancellation token
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the call succeeded.
|
||||
|
||||
#### 🧊 `void Show()`
|
||||
Shows application windows after they were hidden. Does not automatically focus them.
|
||||
|
||||
#### 🧊 `void ShowAboutPanel()`
|
||||
Show the app's about panel options. These options can be overridden with SetAboutPanelOptions.
|
||||
|
||||
## Events
|
||||
|
||||
#### ⚡ `AccessibilitySupportChanged`
|
||||
Emitted when Chrome's accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details.
|
||||
|
||||
#### ⚡ `BrowserWindowBlur`
|
||||
Emitted when a BrowserWindow blurred.
|
||||
|
||||
#### ⚡ `BrowserWindowCreated`
|
||||
Emitted when a new BrowserWindow is created.
|
||||
|
||||
#### ⚡ `BrowserWindowFocus`
|
||||
Emitted when a BrowserWindow gets focused.
|
||||
|
||||
#### ⚡ `OpenFile`
|
||||
Emitted when a macOS user wants to open a file with the application. The open-file event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. open-file is also emitted when a file is dropped onto the dock and the application is not yet running.
|
||||
|
||||
On Windows, you have to parse the arguments using App.CommandLine to get the filepath.
|
||||
|
||||
#### ⚡ `OpenUrl`
|
||||
Emitted when a macOS user wants to open a URL with the application. Your application's Info.plist file must define the URL scheme within the CFBundleURLTypes key, and set NSPrincipalClass to AtomApplication.
|
||||
|
||||
#### ⚡ `Quitting`
|
||||
Emitted when the application is quitting.
|
||||
|
||||
Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
|
||||
|
||||
#### ⚡ `Ready`
|
||||
Emitted when the application has finished basic startup.
|
||||
|
||||
#### ⚡ `WebContentsCreated`
|
||||
Emitted when a new WebContents is created.
|
||||
|
||||
#### ⚡ `WillQuit`
|
||||
Emitted when all windows have been closed and the application will quit.
|
||||
|
||||
See the description of the WindowAllClosed event for the differences between the WillQuit and WindowAllClosed events.
|
||||
|
||||
Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
|
||||
|
||||
#### ⚡ `WindowAllClosed`
|
||||
Emitted when all windows have been closed.
|
||||
|
||||
If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not.If the user pressed Cmd + Q, or the developer called Quit, Electron will first try to close all the windows and then emit the WillQuit event, and in this case the WindowAllClosed event would not be emitted.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Application Lifecycle
|
||||
|
||||
```csharp
|
||||
// Handle app startup
|
||||
Electron.App.Ready += () =>
|
||||
{
|
||||
Console.WriteLine("App is ready!");
|
||||
};
|
||||
|
||||
// Handle window management
|
||||
Electron.App.WindowAllClosed += () =>
|
||||
{
|
||||
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
Electron.App.Quit();
|
||||
}
|
||||
};
|
||||
|
||||
// Prevent quit
|
||||
Electron.App.BeforeQuit += async (args) =>
|
||||
{
|
||||
var result = await Electron.Dialog.ShowMessageBoxAsync("Do you want to quit?");
|
||||
if (result.Response == 1) // Cancel
|
||||
{
|
||||
args.PreventDefault = true;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Protocol Handling
|
||||
|
||||
```csharp
|
||||
// Register custom protocol
|
||||
var success = await Electron.App.SetAsDefaultProtocolClientAsync("myapp");
|
||||
|
||||
// Check if registered
|
||||
var isDefault = await Electron.App.IsDefaultProtocolClientAsync("myapp");
|
||||
```
|
||||
|
||||
### Jump List (Windows)
|
||||
|
||||
```csharp
|
||||
// Set user tasks
|
||||
await Electron.App.SetUserTasksAsync(new[]
|
||||
{
|
||||
new UserTask
|
||||
{
|
||||
Program = "myapp.exe",
|
||||
Arguments = "--new-document",
|
||||
Title = "New Document",
|
||||
Description = "Create a new document"
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Application Information
|
||||
|
||||
```csharp
|
||||
// Get app information
|
||||
var appPath = await Electron.App.GetAppPathAsync();
|
||||
var version = await Electron.App.GetVersionAsync();
|
||||
var locale = await Electron.App.GetLocaleAsync();
|
||||
|
||||
// Set app name
|
||||
await Electron.App.NameAsync; // Get current name
|
||||
Electron.App.Name = "My Custom App Name";
|
||||
```
|
||||
|
||||
### Badge Count (macOS/Linux)
|
||||
|
||||
```csharp
|
||||
// Set badge count
|
||||
await Electron.App.SetBadgeCountAsync(5);
|
||||
|
||||
// Get current badge count
|
||||
var count = await Electron.App.GetBadgeCountAsync();
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.WindowManager](WindowManager.md) - Window creation and management
|
||||
- [Electron.Dialog](Dialog.md) - User interaction dialogs
|
||||
- [Electron.Menu](Menu.md) - Application menus
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron App Documentation](https://electronjs.org/docs/api/app) - Official Electron app API
|
||||
- [Startup Methods](../Using/Startup-Methods.md) - Different application startup modes
|
||||
243
docs/API/AutoUpdater.md
Normal file
243
docs/API/AutoUpdater.md
Normal file
@@ -0,0 +1,243 @@
|
||||
# Electron.AutoUpdater
|
||||
|
||||
Handle application updates and installation processes.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.AutoUpdater` API provides comprehensive functionality for handling application updates, including checking for updates, downloading, and installation. It supports multiple update providers and platforms with automatic update capabilities.
|
||||
|
||||
## Properties
|
||||
|
||||
#### 📋 `bool AllowDowngrade`
|
||||
Whether to allow version downgrade. Default is false.
|
||||
|
||||
#### 📋 `bool AllowPrerelease`
|
||||
GitHub provider only. Whether to allow update to pre-release versions. Defaults to true if application version contains prerelease components.
|
||||
|
||||
#### 📋 `bool AutoDownload`
|
||||
Whether to automatically download an update when it is found. Default is true.
|
||||
|
||||
#### 📋 `bool AutoInstallOnAppQuit`
|
||||
Whether to automatically install a downloaded update on app quit. Applicable only on Windows and Linux.
|
||||
|
||||
#### 📋 `string Channel`
|
||||
Get the update channel. Not applicable for GitHub. Doesn't return channel from the update configuration, only if was previously set.
|
||||
|
||||
#### 📋 `Task<string> ChannelAsync`
|
||||
Get the update channel. Not applicable for GitHub. Doesn't return channel from the update configuration, only if was previously set.
|
||||
|
||||
#### 📋 `Task<SemVer> CurrentVersionAsync`
|
||||
Get the current application version.
|
||||
|
||||
#### 📋 `bool FullChangelog`
|
||||
GitHub provider only. Get all release notes (from current version to latest), not just the latest. Default is false.
|
||||
|
||||
#### 📋 `Dictionary<string, string> RequestHeaders`
|
||||
The request headers.
|
||||
|
||||
#### 📋 `Task<Dictionary<string, string>> RequestHeadersAsync`
|
||||
Get the current request headers.
|
||||
|
||||
#### 📋 `string UpdateConfigPath`
|
||||
For test only. Configuration path for updates.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<UpdateCheckResult> CheckForUpdatesAndNotifyAsync()`
|
||||
Asks the server whether there is an update and notifies the user if an update is available.
|
||||
|
||||
#### 🧊 `Task<UpdateCheckResult> CheckForUpdatesAsync()`
|
||||
Asks the server whether there is an update.
|
||||
|
||||
#### 🧊 `Task<string> DownloadUpdateAsync()`
|
||||
Start downloading update manually. Use this method if AutoDownload option is set to false.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Path to downloaded file.
|
||||
|
||||
#### 🧊 `Task<string> GetFeedURLAsync()`
|
||||
Get the current feed URL.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Feed URL.
|
||||
|
||||
#### 🧊 `void QuitAndInstall(bool isSilent = false, bool isForceRunAfter = false)`
|
||||
Restarts the app and installs the update after it has been downloaded. Should only be called after update-downloaded has been emitted.
|
||||
|
||||
Note: QuitAndInstall() will close all application windows first and only emit before-quit event on app after that. This is different from the normal quit event sequence.
|
||||
|
||||
**Parameters:**
|
||||
- `isSilent` - Windows-only: Runs the installer in silent mode. Defaults to false
|
||||
- `isForceRunAfter` - Run the app after finish even on silent install. Not applicable for macOS
|
||||
|
||||
## Events
|
||||
|
||||
#### ⚡ `OnCheckingForUpdate`
|
||||
Emitted when checking if an update has started.
|
||||
|
||||
#### ⚡ `OnDownloadProgress`
|
||||
Emitted on download progress.
|
||||
|
||||
#### ⚡ `OnError`
|
||||
Emitted when there is an error while updating.
|
||||
|
||||
#### ⚡ `OnUpdateAvailable`
|
||||
Emitted when there is an available update. The update is downloaded automatically if AutoDownload is true.
|
||||
|
||||
#### ⚡ `OnUpdateDownloaded`
|
||||
Emitted on download complete.
|
||||
|
||||
#### ⚡ `OnUpdateNotAvailable`
|
||||
Emitted when there is no available update.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Auto-Update Setup
|
||||
|
||||
```csharp
|
||||
// Configure auto-updater
|
||||
Electron.AutoUpdater.AutoDownload = true;
|
||||
Electron.AutoUpdater.AutoInstallOnAppQuit = true;
|
||||
|
||||
// Check for updates
|
||||
var updateCheck = await Electron.AutoUpdater.CheckForUpdatesAsync();
|
||||
if (updateCheck.UpdateInfo != null)
|
||||
{
|
||||
Console.WriteLine($"Update available: {updateCheck.UpdateInfo.Version}");
|
||||
}
|
||||
```
|
||||
|
||||
### Manual Update Management
|
||||
|
||||
```csharp
|
||||
// Disable auto-download for manual control
|
||||
Electron.AutoUpdater.AutoDownload = false;
|
||||
|
||||
// Check for updates
|
||||
var result = await Electron.AutoUpdater.CheckForUpdatesAsync();
|
||||
if (result.UpdateInfo != null)
|
||||
{
|
||||
Console.WriteLine($"Update found: {result.UpdateInfo.Version}");
|
||||
|
||||
// Ask user confirmation
|
||||
var confirmResult = await Electron.Dialog.ShowMessageBoxAsync(
|
||||
"Update Available",
|
||||
$"Version {result.UpdateInfo.Version} is available. Download now?");
|
||||
|
||||
if (confirmResult.Response == 1) // Yes
|
||||
{
|
||||
// Download update manually
|
||||
var downloadPath = await Electron.AutoUpdater.DownloadUpdateAsync();
|
||||
Console.WriteLine($"Downloaded to: {downloadPath}");
|
||||
|
||||
// Install update
|
||||
Electron.AutoUpdater.QuitAndInstall();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Update Event Handling
|
||||
|
||||
```csharp
|
||||
// Handle update events
|
||||
Electron.AutoUpdater.OnCheckingForUpdate += () =>
|
||||
{
|
||||
Console.WriteLine("Checking for updates...");
|
||||
};
|
||||
|
||||
Electron.AutoUpdater.OnUpdateAvailable += (updateInfo) =>
|
||||
{
|
||||
Console.WriteLine($"Update available: {updateInfo.Version}");
|
||||
};
|
||||
|
||||
Electron.AutoUpdater.OnUpdateNotAvailable += (updateInfo) =>
|
||||
{
|
||||
Console.WriteLine("No updates available");
|
||||
};
|
||||
|
||||
Electron.AutoUpdater.OnDownloadProgress += (progressInfo) =>
|
||||
{
|
||||
Console.WriteLine($"Download progress: {progressInfo.Percent}%");
|
||||
};
|
||||
|
||||
Electron.AutoUpdater.OnUpdateDownloaded += (updateInfo) =>
|
||||
{
|
||||
Console.WriteLine($"Update downloaded: {updateInfo.Version}");
|
||||
|
||||
// Show notification to user
|
||||
Electron.Notification.Show(new NotificationOptions
|
||||
{
|
||||
Title = "Update Downloaded",
|
||||
Body = $"Version {updateInfo.Version} is ready to install.",
|
||||
Actions = new[]
|
||||
{
|
||||
new NotificationAction { Text = "Install Now", Type = NotificationActionType.Button },
|
||||
new NotificationAction { Text = "Later", Type = NotificationActionType.Button }
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
Electron.AutoUpdater.OnError += (error) =>
|
||||
{
|
||||
Console.WriteLine($"Update error: {error}");
|
||||
Electron.Dialog.ShowErrorBox("Update Error", $"Failed to update: {error}");
|
||||
};
|
||||
```
|
||||
|
||||
### GitHub Provider Configuration
|
||||
|
||||
```csharp
|
||||
// Configure for GitHub releases
|
||||
Electron.AutoUpdater.AllowPrerelease = true; // Allow pre-release versions
|
||||
Electron.AutoUpdater.FullChangelog = true; // Get full changelog
|
||||
Electron.AutoUpdater.AllowDowngrade = false; // Prevent downgrades
|
||||
|
||||
// Set request headers if needed
|
||||
Electron.AutoUpdater.RequestHeaders = new Dictionary<string, string>
|
||||
{
|
||||
["Authorization"] = "token your-github-token",
|
||||
["User-Agent"] = "MyApp-Updater"
|
||||
};
|
||||
```
|
||||
|
||||
### Update Installation
|
||||
|
||||
```csharp
|
||||
// Install update immediately
|
||||
if (updateDownloaded)
|
||||
{
|
||||
Electron.AutoUpdater.QuitAndInstall();
|
||||
}
|
||||
|
||||
// Silent install (Windows only)
|
||||
Electron.AutoUpdater.QuitAndInstall(isSilent: true, isForceRunAfter: true);
|
||||
```
|
||||
|
||||
### Version Management
|
||||
|
||||
```csharp
|
||||
// Get current version
|
||||
var currentVersion = await Electron.AutoUpdater.CurrentVersionAsync;
|
||||
Console.WriteLine($"Current version: {currentVersion}");
|
||||
|
||||
// Get update channel
|
||||
var channel = await Electron.AutoUpdater.ChannelAsync;
|
||||
Console.WriteLine($"Update channel: {channel}");
|
||||
|
||||
// Set custom feed URL
|
||||
// Note: This would typically be configured in electron-builder.json
|
||||
var feedUrl = await Electron.AutoUpdater.GetFeedURLAsync();
|
||||
Console.WriteLine($"Feed URL: {feedUrl}");
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.App](App.md) - Application lifecycle events during updates
|
||||
- [Electron.Notification](Notification.md) - Notify users about update status
|
||||
- [Electron.Dialog](Dialog.md) - Show update confirmation dialogs
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron AutoUpdater Documentation](https://electronjs.org/docs/api/auto-updater) - Official Electron auto-updater API
|
||||
231
docs/API/Clipboard.md
Normal file
231
docs/API/Clipboard.md
Normal file
@@ -0,0 +1,231 @@
|
||||
# Electron.Clipboard
|
||||
|
||||
Perform copy and paste operations on the system clipboard.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.Clipboard` API provides comprehensive access to the system clipboard, supporting multiple data formats including text, HTML, RTF, images, and custom data. It enables reading from and writing to the clipboard with platform-specific behavior.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<string[]> AvailableFormatsAsync(string type = "")`
|
||||
Get an array of supported formats for the clipboard type.
|
||||
|
||||
**Parameters:**
|
||||
- `type` - Clipboard type
|
||||
|
||||
**Returns:**
|
||||
|
||||
An array of supported formats for the clipboard type.
|
||||
|
||||
#### 🧊 `void Clear(string type = "")`
|
||||
Clears the clipboard content.
|
||||
|
||||
**Parameters:**
|
||||
- `type` - Clipboard type
|
||||
|
||||
#### 🧊 `Task<ReadBookmark> ReadBookmarkAsync()`
|
||||
Returns an Object containing title and url keys representing the bookmark in the clipboard. The title and url values will be empty strings when the bookmark is unavailable.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Object containing title and url keys representing the bookmark in the clipboard.
|
||||
|
||||
#### 🧊 `Task<string> ReadFindTextAsync()`
|
||||
macOS: The text on the find pasteboard. This method uses synchronous IPC when called from the renderer process. The cached value is reread from the find pasteboard whenever the application is activated.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The text on the find pasteboard.
|
||||
|
||||
#### 🧊 `Task<string> ReadHTMLAsync(string type = "")`
|
||||
Read the content in the clipboard as HTML markup.
|
||||
|
||||
**Parameters:**
|
||||
- `type` - Clipboard type
|
||||
|
||||
**Returns:**
|
||||
|
||||
The content in the clipboard as markup.
|
||||
|
||||
#### 🧊 `Task<NativeImage> ReadImageAsync(string type = "")`
|
||||
Read an image from the clipboard.
|
||||
|
||||
**Parameters:**
|
||||
- `type` - Clipboard type
|
||||
|
||||
**Returns:**
|
||||
|
||||
An image from the clipboard.
|
||||
|
||||
#### 🧊 `Task<string> ReadRTFAsync(string type = "")`
|
||||
Read the content in the clipboard as RTF.
|
||||
|
||||
**Parameters:**
|
||||
- `type` - Clipboard type
|
||||
|
||||
**Returns:**
|
||||
|
||||
The content in the clipboard as RTF.
|
||||
|
||||
#### 🧊 `Task<string> ReadTextAsync(string type = "")`
|
||||
Read the content in the clipboard as plain text.
|
||||
|
||||
**Parameters:**
|
||||
- `type` - Clipboard type
|
||||
|
||||
**Returns:**
|
||||
|
||||
The content in the clipboard as plain text.
|
||||
|
||||
#### 🧊 `void Write(Data data, string type = "")`
|
||||
Writes data to the clipboard.
|
||||
|
||||
**Parameters:**
|
||||
- `data` - Data object to write
|
||||
- `type` - Clipboard type
|
||||
|
||||
#### 🧊 `void WriteBookmark(string title, string url, string type = "")`
|
||||
Writes the title and url into the clipboard as a bookmark.
|
||||
|
||||
Note: Most apps on Windows don't support pasting bookmarks into them so you can use clipboard.write to write both a bookmark and fallback text to the clipboard.
|
||||
|
||||
**Parameters:**
|
||||
- `title` - Bookmark title
|
||||
- `url` - Bookmark URL
|
||||
- `type` - Clipboard type
|
||||
|
||||
#### 🧊 `void WriteFindText(string text)`
|
||||
macOS: Writes the text into the find pasteboard as plain text. This method uses synchronous IPC when called from the renderer process.
|
||||
|
||||
**Parameters:**
|
||||
- `text` - Text to write to find pasteboard
|
||||
|
||||
#### 🧊 `void WriteHTML(string markup, string type = "")`
|
||||
Writes markup to the clipboard.
|
||||
|
||||
**Parameters:**
|
||||
- `markup` - HTML markup to write
|
||||
- `type` - Clipboard type
|
||||
|
||||
#### 🧊 `void WriteImage(NativeImage image, string type = "")`
|
||||
Writes an image to the clipboard.
|
||||
|
||||
**Parameters:**
|
||||
- `image` - Image to write to clipboard
|
||||
- `type` - Clipboard type
|
||||
|
||||
#### 🧊 `void WriteRTF(string text, string type = "")`
|
||||
Writes the text into the clipboard in RTF.
|
||||
|
||||
**Parameters:**
|
||||
- `text` - RTF content to write
|
||||
- `type` - Clipboard type
|
||||
|
||||
#### 🧊 `void WriteText(string text, string type = "")`
|
||||
Writes the text into the clipboard as plain text.
|
||||
|
||||
**Parameters:**
|
||||
- `text` - Text content to write
|
||||
- `type` - Clipboard type
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Text Operations
|
||||
|
||||
```csharp
|
||||
// Read text from clipboard
|
||||
var text = await Electron.Clipboard.ReadTextAsync();
|
||||
Console.WriteLine($"Clipboard text: {text}");
|
||||
|
||||
// Write text to clipboard
|
||||
Electron.Clipboard.WriteText("Hello, Electron.NET!");
|
||||
|
||||
// Read with specific type
|
||||
var html = await Electron.Clipboard.ReadHTMLAsync("public.main");
|
||||
```
|
||||
|
||||
### Rich Content Handling
|
||||
|
||||
```csharp
|
||||
// Copy formatted text
|
||||
var htmlContent = "<h1>Title</h1><p>Some <strong>bold</strong> text</p>";
|
||||
Electron.Clipboard.WriteHTML(htmlContent);
|
||||
|
||||
// Read RTF content
|
||||
var rtf = await Electron.Clipboard.ReadRTFAsync();
|
||||
Console.WriteLine($"RTF content: {rtf}");
|
||||
```
|
||||
|
||||
### Image Operations
|
||||
|
||||
```csharp
|
||||
// Read image from clipboard
|
||||
var image = await Electron.Clipboard.ReadImageAsync();
|
||||
if (image != null)
|
||||
{
|
||||
Console.WriteLine($"Image size: {image.Size.Width}x{image.Size.Height}");
|
||||
}
|
||||
|
||||
// Write image to clipboard
|
||||
var nativeImage = NativeImage.CreateFromPath("screenshot.png");
|
||||
Electron.Clipboard.WriteImage(nativeImage);
|
||||
```
|
||||
|
||||
### Bookmark Management
|
||||
|
||||
```csharp
|
||||
// Read bookmark from clipboard
|
||||
var bookmark = await Electron.Clipboard.ReadBookmarkAsync();
|
||||
if (!string.IsNullOrEmpty(bookmark.Title))
|
||||
{
|
||||
Console.WriteLine($"Bookmark: {bookmark.Title} -> {bookmark.Url}");
|
||||
}
|
||||
|
||||
// Write bookmark to clipboard
|
||||
Electron.Clipboard.WriteBookmark("Electron.NET", "https://github.com/ElectronNET/Electron.NET");
|
||||
```
|
||||
|
||||
### Advanced Clipboard Operations
|
||||
|
||||
```csharp
|
||||
// Check available formats
|
||||
var formats = await Electron.Clipboard.AvailableFormatsAsync();
|
||||
Console.WriteLine($"Available formats: {string.Join(", ", formats)}");
|
||||
|
||||
// Clear clipboard
|
||||
Electron.Clipboard.Clear();
|
||||
|
||||
// Write custom data
|
||||
var data = new Data
|
||||
{
|
||||
Text = "Custom data",
|
||||
Html = "<p>Custom HTML</p>",
|
||||
Image = nativeImage
|
||||
};
|
||||
Electron.Clipboard.Write(data);
|
||||
```
|
||||
|
||||
### macOS Find Pasteboard
|
||||
|
||||
```csharp
|
||||
// macOS specific find pasteboard operations
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
// Read find text
|
||||
var findText = await Electron.Clipboard.ReadFindTextAsync();
|
||||
Console.WriteLine($"Find text: {findText}");
|
||||
|
||||
// Write find text
|
||||
Electron.Clipboard.WriteFindText("search term");
|
||||
}
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.Shell](Shell.md) - Work with file paths from clipboard
|
||||
- [Electron.Notification](Notification.md) - Show clipboard operation results
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Clipboard Documentation](https://electronjs.org/docs/api/clipboard) - Official Electron clipboard API
|
||||
160
docs/API/Dialog.md
Normal file
160
docs/API/Dialog.md
Normal file
@@ -0,0 +1,160 @@
|
||||
# Electron.Dialog
|
||||
|
||||
Display native system dialogs for opening and saving files, alerting, etc.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.Dialog` API provides access to native system dialogs for file operations, message boxes, and certificate trust dialogs. These dialogs are modal and provide a consistent user experience across different platforms.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, MessageBoxOptions messageBoxOptions)`
|
||||
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. If a callback is passed, the dialog will not block the process.
|
||||
|
||||
**Parameters:**
|
||||
- `browserWindow` - The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
- `messageBoxOptions` - Message content and configuration
|
||||
|
||||
**Returns:**
|
||||
|
||||
The API call will be asynchronous and the result will be passed via MessageBoxResult.
|
||||
|
||||
#### 🧊 `Task<MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, string message)`
|
||||
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. If a callback is passed, the dialog will not block the process.
|
||||
|
||||
**Parameters:**
|
||||
- `browserWindow` - The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
- `message` - Message content
|
||||
|
||||
**Returns:**
|
||||
|
||||
The API call will be asynchronous and the result will be passed via MessageBoxResult.
|
||||
|
||||
#### 🧊 `Task<MessageBoxResult> ShowMessageBoxAsync(MessageBoxOptions messageBoxOptions)`
|
||||
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. If a callback is passed, the dialog will not block the process.
|
||||
|
||||
**Parameters:**
|
||||
- `messageBoxOptions` - Message content and configuration
|
||||
|
||||
**Returns:**
|
||||
|
||||
The API call will be asynchronous and the result will be passed via MessageBoxResult.
|
||||
|
||||
#### 🧊 `Task<MessageBoxResult> ShowMessageBoxAsync(string message)`
|
||||
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. If a callback is passed, the dialog will not block the process.
|
||||
|
||||
**Parameters:**
|
||||
- `message` - Message content
|
||||
|
||||
**Returns:**
|
||||
|
||||
The API call will be asynchronous and the result will be passed via MessageBoxResult.
|
||||
|
||||
#### 🧊 `Task<string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options)`
|
||||
Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown.
|
||||
|
||||
**Parameters:**
|
||||
- `browserWindow` - The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
- `options` - Dialog configuration options
|
||||
|
||||
**Returns:**
|
||||
|
||||
An array of file paths chosen by the user
|
||||
|
||||
#### 🧊 `Task<string> ShowSaveDialogAsync(BrowserWindow browserWindow, SaveDialogOptions options)`
|
||||
Dialog for save files.
|
||||
|
||||
**Parameters:**
|
||||
- `browserWindow` - The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
- `options` - Dialog configuration options
|
||||
|
||||
**Returns:**
|
||||
|
||||
Returns String, the path of the file chosen by the user, if a callback is provided it returns an empty string.
|
||||
|
||||
#### 🧊 `void ShowErrorBox(string title, string content)`
|
||||
Displays a modal dialog that shows an error message.
|
||||
|
||||
This API can be called safely before the ready event the app module emits, it is usually used to report errors in early stage of startup.If called before the app readyevent on Linux, the message will be emitted to stderr, and no GUI dialog will appear.
|
||||
|
||||
**Parameters:**
|
||||
- `title` - The title to display in the error box.
|
||||
- `content` - The text content to display in the error box.
|
||||
|
||||
#### 🧊 `Task ShowCertificateTrustDialogAsync(BrowserWindow browserWindow, CertificateTrustDialogOptions options)`
|
||||
On macOS, this displays a modal dialog that shows a message and certificate information, and gives the user the option of trusting/importing the certificate. If you provide a browserWindow argument the dialog will be attached to the parent window, making it modal.
|
||||
|
||||
**Parameters:**
|
||||
- `browserWindow` - Parent window for modal behavior
|
||||
- `options` - Certificate trust dialog options
|
||||
|
||||
#### 🧊 `Task ShowCertificateTrustDialogAsync(CertificateTrustDialogOptions options)`
|
||||
On macOS, this displays a modal dialog that shows a message and certificate information, and gives the user the option of trusting/importing the certificate. If you provide a browserWindow argument the dialog will be attached to the parent window, making it modal.
|
||||
|
||||
**Parameters:**
|
||||
- `options` - Certificate trust dialog options
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### File Operations
|
||||
|
||||
```csharp
|
||||
// Open multiple files
|
||||
var files = await Electron.Dialog.ShowOpenDialogAsync(window, new OpenDialogOptions
|
||||
{
|
||||
Properties = new[] { OpenDialogProperty.OpenFile, OpenDialogProperty.MultiSelections }
|
||||
});
|
||||
|
||||
// Save with custom extension
|
||||
var path = await Electron.Dialog.ShowSaveDialogAsync(window, new SaveDialogOptions
|
||||
{
|
||||
DefaultPath = "backup.json",
|
||||
Filters = new[] { new FileFilter { Name = "JSON", Extensions = new[] { "json" } } }
|
||||
});
|
||||
```
|
||||
|
||||
### User Confirmation
|
||||
|
||||
```csharp
|
||||
// Confirmation dialog
|
||||
var result = await Electron.Dialog.ShowMessageBoxAsync(window, new MessageBoxOptions
|
||||
{
|
||||
Type = MessageBoxType.Question,
|
||||
Title = "Confirm Delete",
|
||||
Message = $"Delete {filename}?",
|
||||
Buttons = new[] { "Cancel", "Delete" },
|
||||
DefaultId = 0,
|
||||
CancelId = 0
|
||||
});
|
||||
|
||||
if (result.Response == 1)
|
||||
{
|
||||
// Delete file
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```csharp
|
||||
// Error dialog
|
||||
Electron.Dialog.ShowErrorBox("Save Failed", "Could not save file. Please check permissions and try again.");
|
||||
|
||||
// Warning dialog
|
||||
await Electron.Dialog.ShowMessageBoxAsync(new MessageBoxOptions
|
||||
{
|
||||
Type = MessageBoxType.Warning,
|
||||
Title = "Warning",
|
||||
Message = "This operation may take several minutes.",
|
||||
Buttons = new[] { "Continue", "Cancel" }
|
||||
});
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.WindowManager](WindowManager.md) - Parent windows for modal dialogs
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.Shell](Shell.md) - File operations with selected paths
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Dialog Documentation](https://electronjs.org/docs/api/dialog) - Official Electron dialog API
|
||||
209
docs/API/Dock.md
Normal file
209
docs/API/Dock.md
Normal file
@@ -0,0 +1,209 @@
|
||||
# Electron.Dock
|
||||
|
||||
Control your app in the macOS dock.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.Dock` API provides control over your application's appearance and behavior in the macOS dock. This includes bouncing the dock icon, setting badges, managing menus, and controlling visibility.
|
||||
|
||||
## Properties
|
||||
|
||||
#### 📋 `IReadOnlyCollection<MenuItem> MenuItems`
|
||||
Gets a read-only collection of all current dock menu items.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<int> BounceAsync(DockBounceType type, CancellationToken cancellationToken = default)`
|
||||
When `DockBounceType.Critical` is passed, the dock icon will bounce until either the application becomes active or the request is canceled. When `DockBounceType.Informational` is passed, the dock icon will bounce for one second. However, the request remains active until either the application becomes active or the request is canceled.
|
||||
|
||||
Note: This method can only be used while the app is not focused; when the app is focused it will return -1.
|
||||
|
||||
**Parameters:**
|
||||
- `type` - Can be critical or informational. The default is informational.
|
||||
- `cancellationToken` - The cancellation token
|
||||
|
||||
**Returns:**
|
||||
|
||||
An ID representing the request.
|
||||
|
||||
#### 🧊 `void CancelBounce(int id)`
|
||||
Cancel the bounce of id.
|
||||
|
||||
**Parameters:**
|
||||
- `id` - Id of the request
|
||||
|
||||
#### 🧊 `void DownloadFinished(string filePath)`
|
||||
Bounces the Downloads stack if the filePath is inside the Downloads folder.
|
||||
|
||||
**Parameters:**
|
||||
- `filePath` - Path to the downloaded file
|
||||
|
||||
#### 🧊 `Task<string> GetBadgeAsync(CancellationToken cancellationToken = default)`
|
||||
Gets the string to be displayed in the dock's badging area.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The badge string of the dock.
|
||||
|
||||
#### 🧊 `Task<Menu> GetMenu(CancellationToken cancellationToken = default)`
|
||||
Gets the application's dock menu.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The application's dock menu.
|
||||
|
||||
#### 🧊 `void Hide()`
|
||||
Hides the dock icon.
|
||||
|
||||
#### 🧊 `Task<bool> IsVisibleAsync(CancellationToken cancellationToken = default)`
|
||||
Whether the dock icon is visible. The app.dock.show() call is asynchronous so this method might not return true immediately after that call.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the dock icon is visible.
|
||||
|
||||
#### 🧊 `void SetBadge(string text)`
|
||||
Sets the string to be displayed in the dock's badging area.
|
||||
|
||||
**Parameters:**
|
||||
- `text` - Badge text to display
|
||||
|
||||
#### 🧊 `void SetIcon(string image)`
|
||||
Sets the image associated with this dock icon.
|
||||
|
||||
**Parameters:**
|
||||
- `image` - Icon image path
|
||||
|
||||
#### 🧊 `void SetMenu(MenuItem[] menuItems)`
|
||||
Sets the application's dock menu.
|
||||
|
||||
**Parameters:**
|
||||
- `menuItems` - Array of menu items for the dock menu
|
||||
|
||||
#### 🧊 `void Show()`
|
||||
Shows the dock icon.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Dock Operations
|
||||
|
||||
```csharp
|
||||
// Hide/Show dock icon
|
||||
Electron.Dock.Hide();
|
||||
await Task.Delay(2000);
|
||||
Electron.Dock.Show();
|
||||
|
||||
// Check visibility
|
||||
var isVisible = await Electron.Dock.IsVisibleAsync();
|
||||
Console.WriteLine($"Dock visible: {isVisible}");
|
||||
```
|
||||
|
||||
### Badge Notifications
|
||||
|
||||
```csharp
|
||||
// Set badge count
|
||||
Electron.Dock.SetBadge("5");
|
||||
|
||||
// Get current badge
|
||||
var badge = await Electron.Dock.GetBadgeAsync();
|
||||
Console.WriteLine($"Current badge: {badge}");
|
||||
|
||||
// Clear badge
|
||||
Electron.Dock.SetBadge("");
|
||||
```
|
||||
|
||||
### Dock Icon Animation
|
||||
|
||||
```csharp
|
||||
// Bounce for attention
|
||||
var bounceId = await Electron.Dock.BounceAsync(DockBounceType.Critical);
|
||||
Console.WriteLine($"Bounce ID: {bounceId}");
|
||||
|
||||
// Cancel bounce after 3 seconds
|
||||
await Task.Delay(3000);
|
||||
Electron.Dock.CancelBounce(bounceId);
|
||||
|
||||
// Informational bounce
|
||||
await Electron.Dock.BounceAsync(DockBounceType.Informational);
|
||||
```
|
||||
|
||||
### Dock Menu
|
||||
|
||||
```csharp
|
||||
// Create dock menu
|
||||
var dockMenuItems = new[]
|
||||
{
|
||||
new MenuItem { Label = "Show Window", Click = () => ShowMainWindow() },
|
||||
new MenuItem { Label = "Settings", Click = () => OpenSettings() },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Label = "Exit", Click = () => Electron.App.Quit() }
|
||||
};
|
||||
|
||||
// Set dock menu
|
||||
Electron.Dock.SetMenu(dockMenuItems);
|
||||
|
||||
// Get current menu
|
||||
var currentMenu = await Electron.Dock.GetMenu();
|
||||
Console.WriteLine($"Menu items: {Electron.Dock.MenuItems.Count}");
|
||||
```
|
||||
|
||||
### Download Notifications
|
||||
|
||||
```csharp
|
||||
// Notify about completed download
|
||||
var downloadPath = "/Users/username/Downloads/document.pdf";
|
||||
Electron.Dock.DownloadFinished(downloadPath);
|
||||
```
|
||||
|
||||
### Custom Dock Icon
|
||||
|
||||
```csharp
|
||||
// Set custom dock icon
|
||||
Electron.Dock.SetIcon("assets/custom-dock-icon.png");
|
||||
|
||||
// Set icon based on status
|
||||
if (isConnected)
|
||||
{
|
||||
Electron.Dock.SetIcon("assets/connected-icon.png");
|
||||
}
|
||||
else
|
||||
{
|
||||
Electron.Dock.SetIcon("assets/disconnected-icon.png");
|
||||
}
|
||||
```
|
||||
|
||||
### Application Integration
|
||||
|
||||
```csharp
|
||||
// Update dock badge based on unread count
|
||||
UpdateDockBadge(unreadMessageCount);
|
||||
|
||||
void UpdateDockBadge(int count)
|
||||
{
|
||||
if (count > 0)
|
||||
{
|
||||
Electron.Dock.SetBadge(count.ToString());
|
||||
}
|
||||
else
|
||||
{
|
||||
Electron.Dock.SetBadge("");
|
||||
}
|
||||
}
|
||||
|
||||
// Animate dock when receiving message
|
||||
private async void OnMessageReceived()
|
||||
{
|
||||
await Electron.Dock.BounceAsync(DockBounceType.Informational);
|
||||
Electron.Dock.SetBadge((unreadCount + 1).ToString());
|
||||
}
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.Notification](Notification.md) - Desktop notifications
|
||||
- [Electron.Menu](Menu.md) - Menu items for dock menu
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Dock Documentation](https://electronjs.org/docs/api/dock) - Official Electron dock API
|
||||
189
docs/API/GlobalShortcut.md
Normal file
189
docs/API/GlobalShortcut.md
Normal file
@@ -0,0 +1,189 @@
|
||||
# Electron.GlobalShortcut
|
||||
|
||||
Register global keyboard shortcuts that work even when the application is not focused.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.GlobalShortcut` API provides the ability to register global keyboard shortcuts that can be triggered even when the application does not have keyboard focus. This is useful for creating system-wide hotkeys and shortcuts.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<bool> IsRegisteredAsync(string accelerator)`
|
||||
Check if the accelerator is registered.
|
||||
|
||||
**Parameters:**
|
||||
- `accelerator` - Keyboard shortcut to check
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether this application has registered the accelerator.
|
||||
|
||||
#### 🧊 `void Register(string accelerator, Action function)`
|
||||
Registers a global shortcut of accelerator. The callback is called when the registered shortcut is pressed by the user.
|
||||
|
||||
**Parameters:**
|
||||
- `accelerator` - Keyboard shortcut combination
|
||||
- `function` - Callback function to execute when shortcut is pressed
|
||||
|
||||
#### 🧊 `void Unregister(string accelerator)`
|
||||
Unregisters the global shortcut of accelerator.
|
||||
|
||||
**Parameters:**
|
||||
- `accelerator` - Keyboard shortcut to unregister
|
||||
|
||||
#### 🧊 `void UnregisterAll()`
|
||||
Unregisters all of the global shortcuts.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Global Shortcuts
|
||||
|
||||
```csharp
|
||||
// Register global shortcuts
|
||||
Electron.GlobalShortcut.Register("CommandOrControl+N", () =>
|
||||
{
|
||||
CreateNewDocument();
|
||||
});
|
||||
|
||||
Electron.GlobalShortcut.Register("CommandOrControl+O", () =>
|
||||
{
|
||||
OpenDocument();
|
||||
});
|
||||
|
||||
Electron.GlobalShortcut.Register("CommandOrControl+S", () =>
|
||||
{
|
||||
SaveDocument();
|
||||
});
|
||||
```
|
||||
|
||||
### Media Control Shortcuts
|
||||
|
||||
```csharp
|
||||
// Media playback shortcuts
|
||||
Electron.GlobalShortcut.Register("MediaPlayPause", () =>
|
||||
{
|
||||
TogglePlayback();
|
||||
});
|
||||
|
||||
Electron.GlobalShortcut.Register("MediaNextTrack", () =>
|
||||
{
|
||||
NextTrack();
|
||||
});
|
||||
|
||||
Electron.GlobalShortcut.Register("MediaPreviousTrack", () =>
|
||||
{
|
||||
PreviousTrack();
|
||||
});
|
||||
```
|
||||
|
||||
### Application Control Shortcuts
|
||||
|
||||
```csharp
|
||||
// Application control shortcuts
|
||||
Electron.GlobalShortcut.Register("CommandOrControl+Shift+Q", async () =>
|
||||
{
|
||||
var result = await Electron.Dialog.ShowMessageBoxAsync("Quit Application?", "Are you sure you want to quit?");
|
||||
if (result.Response == 1) // Yes
|
||||
{
|
||||
Electron.App.Quit();
|
||||
}
|
||||
});
|
||||
|
||||
Electron.GlobalShortcut.Register("CommandOrControl+Shift+H", () =>
|
||||
{
|
||||
ToggleMainWindow();
|
||||
});
|
||||
```
|
||||
|
||||
### Dynamic Shortcut Management
|
||||
|
||||
```csharp
|
||||
// Register shortcuts based on user preferences
|
||||
public void RegisterUserShortcuts(Dictionary<string, Action> shortcuts)
|
||||
{
|
||||
foreach (var shortcut in shortcuts)
|
||||
{
|
||||
Electron.GlobalShortcut.Register(shortcut.Key, shortcut.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if shortcut is available
|
||||
public async Task<bool> IsShortcutAvailable(string accelerator)
|
||||
{
|
||||
return await Electron.GlobalShortcut.IsRegisteredAsync(accelerator);
|
||||
}
|
||||
|
||||
// Unregister specific shortcut
|
||||
public void UnregisterShortcut(string accelerator)
|
||||
{
|
||||
Electron.GlobalShortcut.Unregister(accelerator);
|
||||
}
|
||||
```
|
||||
|
||||
### Platform-Specific Shortcuts
|
||||
|
||||
```csharp
|
||||
// macOS specific shortcuts
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
Electron.GlobalShortcut.Register("Command+Comma", () =>
|
||||
{
|
||||
OpenPreferences();
|
||||
});
|
||||
|
||||
Electron.GlobalShortcut.Register("Command+H", () =>
|
||||
{
|
||||
Electron.App.Hide();
|
||||
});
|
||||
}
|
||||
|
||||
// Windows/Linux shortcuts
|
||||
else
|
||||
{
|
||||
Electron.GlobalShortcut.Register("Ctrl+Shift+P", () =>
|
||||
{
|
||||
OpenPreferences();
|
||||
});
|
||||
|
||||
Electron.GlobalShortcut.Register("Alt+F4", () =>
|
||||
{
|
||||
Electron.App.Quit();
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Shortcut Validation
|
||||
|
||||
```csharp
|
||||
// Validate shortcuts before registration
|
||||
public async Task<bool> TryRegisterShortcut(string accelerator, Action callback)
|
||||
{
|
||||
if (await Electron.GlobalShortcut.IsRegisteredAsync(accelerator))
|
||||
{
|
||||
Console.WriteLine($"Shortcut {accelerator} is already registered");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Electron.GlobalShortcut.Register(accelerator, callback);
|
||||
Console.WriteLine($"Successfully registered shortcut: {accelerator}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Failed to register shortcut {accelerator}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.Menu](Menu.md) - Menu-based shortcuts
|
||||
- [Electron.WindowManager](WindowManager.md) - Window focus management
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron GlobalShortcut Documentation](https://electronjs.org/docs/api/global-shortcut) - Official Electron global shortcut API
|
||||
152
docs/API/HostHook.md
Normal file
152
docs/API/HostHook.md
Normal file
@@ -0,0 +1,152 @@
|
||||
# Electron.HostHook
|
||||
|
||||
Execute native JavaScript/TypeScript code from the host process.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.HostHook` API allows you to execute native JavaScript/TypeScript code from the host process. This enables advanced integration scenarios where you need to run custom JavaScript code or access Node.js APIs directly.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `void Call(string socketEventName, params dynamic[] arguments)`
|
||||
Execute native JavaScript/TypeScript code synchronously.
|
||||
|
||||
**Parameters:**
|
||||
- `socketEventName` - Socket name registered on the host
|
||||
- `arguments` - Optional parameters
|
||||
|
||||
#### 🧊 `Task<T> CallAsync<T>(string socketEventName, params dynamic[] arguments)`
|
||||
Execute native JavaScript/TypeScript code asynchronously with type-safe return values.
|
||||
|
||||
**Parameters:**
|
||||
- `T` - Expected return type
|
||||
- `socketEventName` - Socket name registered on the host
|
||||
- `arguments` - Optional parameters
|
||||
|
||||
**Returns:**
|
||||
|
||||
Task<T> with the result from the executed host code.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Host Hook Execution
|
||||
|
||||
```csharp
|
||||
// Execute simple JavaScript function
|
||||
Electron.HostHook.Call("myFunction", "parameter1", 42);
|
||||
|
||||
// Execute with callback-style result
|
||||
var result = await Electron.HostHook.CallAsync<string>("getUserName", userId);
|
||||
Console.WriteLine($"User name: {result}");
|
||||
```
|
||||
|
||||
### Advanced Integration
|
||||
|
||||
```csharp
|
||||
// Call custom Electron API
|
||||
var fileContent = await Electron.HostHook.CallAsync<string>("readFile", "config.json");
|
||||
Console.WriteLine($"Config: {fileContent}");
|
||||
|
||||
// Execute with multiple parameters
|
||||
var processedData = await Electron.HostHook.CallAsync<object[]>("processData", rawData, options);
|
||||
|
||||
// Call with complex objects
|
||||
var settings = new { theme = "dark", language = "en" };
|
||||
var updatedSettings = await Electron.HostHook.CallAsync<object>("updateSettings", settings);
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```csharp
|
||||
try
|
||||
{
|
||||
// Execute host function with error handling
|
||||
var result = await Electron.HostHook.CallAsync<string>("riskyOperation", inputData);
|
||||
Console.WriteLine($"Success: {result}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Handle execution errors
|
||||
Console.WriteLine($"Host hook error: {ex.Message}");
|
||||
Electron.Dialog.ShowErrorBox("Operation Failed", "Could not execute host function.");
|
||||
}
|
||||
```
|
||||
|
||||
### Type-Safe Operations
|
||||
|
||||
```csharp
|
||||
// Strongly typed return values
|
||||
var userInfo = await Electron.HostHook.CallAsync<UserInfo>("getUserInfo", userId);
|
||||
Console.WriteLine($"User: {userInfo.Name}, Email: {userInfo.Email}");
|
||||
|
||||
// Array results
|
||||
var fileList = await Electron.HostHook.CallAsync<string[]>("listFiles", directoryPath);
|
||||
foreach (var file in fileList)
|
||||
{
|
||||
Console.WriteLine($"File: {file}");
|
||||
}
|
||||
|
||||
// Complex object results
|
||||
var systemStats = await Electron.HostHook.CallAsync<SystemStatistics>("getSystemStats");
|
||||
Console.WriteLine($"CPU: {systemStats.CpuUsage}%, Memory: {systemStats.MemoryUsage}%");
|
||||
```
|
||||
|
||||
### Custom ElectronHostHook Setup
|
||||
|
||||
```csharp
|
||||
// In your ElectronHostHook/index.ts
|
||||
import { app } from 'electron';
|
||||
|
||||
export function getAppVersion(): string {
|
||||
return app.getVersion();
|
||||
}
|
||||
|
||||
export async function readConfigFile(): Promise<string> {
|
||||
const fs = require('fs').promises;
|
||||
return await fs.readFile('config.json', 'utf8');
|
||||
}
|
||||
|
||||
export function customNotification(message: string): void {
|
||||
// Custom notification logic
|
||||
console.log(`Custom notification: ${message}`);
|
||||
}
|
||||
```
|
||||
|
||||
### Integration with .NET Code
|
||||
|
||||
```csharp
|
||||
// Use host hook in your application logic
|
||||
public async Task<string> GetApplicationVersion()
|
||||
{
|
||||
return await Electron.HostHook.CallAsync<string>("getAppVersion");
|
||||
}
|
||||
|
||||
public async Task LoadConfiguration()
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = await Electron.HostHook.CallAsync<ConfigObject>("readConfigFile");
|
||||
ApplyConfiguration(config);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Failed to load config: {ex.Message}");
|
||||
UseDefaultConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
public void ShowCustomNotification(string message)
|
||||
{
|
||||
Electron.HostHook.Call("customNotification", message);
|
||||
}
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.IpcMain](IpcMain.md) - Inter-process communication
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.WebContents](WebContents.md) - Web content integration
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Host Hook Documentation](../Core/Advanced-Migration-Topics.md) - Setting up custom host hooks
|
||||
167
docs/API/IpcMain.md
Normal file
167
docs/API/IpcMain.md
Normal file
@@ -0,0 +1,167 @@
|
||||
# Electron.IpcMain
|
||||
|
||||
Communicate asynchronously from the main process to renderer processes.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.IpcMain` API provides inter-process communication between the main process and renderer processes. It allows you to send messages, listen for events, and handle communication between different parts of your Electron application.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task On(string channel, Action<object> listener)`
|
||||
Listens to channel, when a new message arrives listener would be called with listener(event, args...).
|
||||
|
||||
**Parameters:**
|
||||
- `channel` - Channel name to listen on
|
||||
- `listener` - Callback method to handle incoming messages
|
||||
|
||||
#### 🧊 `void OnSync(string channel, Func<object, object> listener)`
|
||||
Send a message to the renderer process synchronously via channel. Note: Sending a synchronous message will block the whole renderer process.
|
||||
|
||||
**Parameters:**
|
||||
- `channel` - Channel name to listen on
|
||||
- `listener` - Synchronous callback method
|
||||
|
||||
#### 🧊 `void Once(string channel, Action<object> listener)`
|
||||
Adds a one time listener method for the event. This listener is invoked only the next time a message is sent to channel, after which it is removed.
|
||||
|
||||
**Parameters:**
|
||||
- `channel` - Channel name to listen on
|
||||
- `listener` - Callback method to handle the message once
|
||||
|
||||
#### 🧊 `void RemoveAllListeners(string channel)`
|
||||
Removes all listeners of the specified channel.
|
||||
|
||||
**Parameters:**
|
||||
- `channel` - Channel name to remove listeners from
|
||||
|
||||
#### 🧊 `void Send(BrowserView browserView, string channel, params object[] data)`
|
||||
Send a message to the BrowserView renderer process asynchronously via channel.
|
||||
|
||||
**Parameters:**
|
||||
- `browserView` - Target browser view
|
||||
- `channel` - Channel name to send on
|
||||
- `data` - Arguments to send
|
||||
|
||||
#### 🧊 `void Send(BrowserWindow browserWindow, string channel, params object[] data)`
|
||||
Send a message to the renderer process asynchronously via channel.
|
||||
|
||||
**Parameters:**
|
||||
- `browserWindow` - Target browser window
|
||||
- `channel` - Channel name to send on
|
||||
- `data` - Arguments to send
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Message Handling
|
||||
|
||||
```csharp
|
||||
// Listen for messages from renderer
|
||||
await Electron.IpcMain.On("request-data", (args) =>
|
||||
{
|
||||
Console.WriteLine($"Received request: {args}");
|
||||
// Process the request and send response
|
||||
});
|
||||
|
||||
// Send response back to renderer
|
||||
Electron.IpcMain.Send(mainWindow, "data-response", processedData);
|
||||
```
|
||||
|
||||
### Synchronous Communication
|
||||
|
||||
```csharp
|
||||
// Handle synchronous requests
|
||||
Electron.IpcMain.OnSync("get-user-info", (request) =>
|
||||
{
|
||||
var userId = request.ToString();
|
||||
var userInfo = GetUserInfo(userId);
|
||||
return userInfo;
|
||||
});
|
||||
```
|
||||
|
||||
### One-time Event Handling
|
||||
|
||||
```csharp
|
||||
// Handle initialization request once
|
||||
Electron.IpcMain.Once("app-initialized", (args) =>
|
||||
{
|
||||
Console.WriteLine("App initialized, setting up...");
|
||||
InitializeApplication();
|
||||
});
|
||||
```
|
||||
|
||||
### Complex Data Exchange
|
||||
|
||||
```csharp
|
||||
// Send complex data to renderer
|
||||
var appData = new
|
||||
{
|
||||
Version = "1.0.0",
|
||||
Features = new[] { "feature1", "feature2" },
|
||||
Settings = new { Theme = "dark", Language = "en" }
|
||||
};
|
||||
|
||||
Electron.IpcMain.Send(mainWindow, "app-config", appData);
|
||||
|
||||
// Listen for settings updates
|
||||
await Electron.IpcMain.On("update-settings", (settings) =>
|
||||
{
|
||||
var config = JsonConvert.DeserializeObject<AppSettings>(settings.ToString());
|
||||
ApplySettings(config);
|
||||
});
|
||||
```
|
||||
|
||||
### Multi-Window Communication
|
||||
|
||||
```csharp
|
||||
// Send message to specific window
|
||||
var settingsWindow = await Electron.WindowManager.CreateWindowAsync();
|
||||
Electron.IpcMain.Send(settingsWindow, "show-settings", currentSettings);
|
||||
|
||||
// Broadcast to all windows
|
||||
foreach (var window in Electron.WindowManager.BrowserWindows)
|
||||
{
|
||||
Electron.IpcMain.Send(window, "notification", message);
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```csharp
|
||||
// Handle IPC errors gracefully
|
||||
await Electron.IpcMain.On("risky-operation", async (args) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await PerformRiskyOperation(args);
|
||||
Electron.IpcMain.Send(mainWindow, "operation-success", result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Electron.IpcMain.Send(mainWindow, "operation-error", ex.Message);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Integration with Host Hooks
|
||||
|
||||
```csharp
|
||||
// Use with custom host functionality
|
||||
await Electron.IpcMain.On("execute-host-function", async (args) =>
|
||||
{
|
||||
var functionName = args.ToString();
|
||||
var result = await Electron.HostHook.CallAsync<string>(functionName);
|
||||
|
||||
Electron.IpcMain.Send(mainWindow, "function-result", result);
|
||||
});
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.HostHook](HostHook.md) - Execute custom JavaScript functions
|
||||
- [Electron.WindowManager](WindowManager.md) - Target specific windows for communication
|
||||
- [Electron.WebContents](WebContents.md) - Send messages to web content
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron IPC Documentation](https://electronjs.org/docs/api/ipc-main) - Official Electron IPC API
|
||||
210
docs/API/Menu.md
Normal file
210
docs/API/Menu.md
Normal file
@@ -0,0 +1,210 @@
|
||||
# Electron.Menu
|
||||
|
||||
Create application menus, context menus, and menu items with full keyboard shortcut support.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.Menu` API provides comprehensive control over application menus and context menus. It supports native platform menus with custom menu items, submenus, keyboard shortcuts, and role-based menu items.
|
||||
|
||||
## Properties
|
||||
|
||||
#### 📋 `IReadOnlyDictionary<int, ReadOnlyCollection<MenuItem>> ContextMenuItems`
|
||||
Gets a read-only dictionary of all current context menu items, keyed by browser window ID.
|
||||
|
||||
#### 📋 `IReadOnlyCollection<MenuItem> MenuItems`
|
||||
Gets a read-only collection of all current application menu items.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `void ContextMenuPopup(BrowserWindow browserWindow)`
|
||||
Shows the context menu for the specified browser window.
|
||||
|
||||
**Parameters:**
|
||||
- `browserWindow` - The browser window to show the context menu for
|
||||
|
||||
#### 🧊 `void SetApplicationMenu(MenuItem[] menuItems)`
|
||||
Sets the application menu for the entire application.
|
||||
|
||||
**Parameters:**
|
||||
- `menuItems` - Array of MenuItem objects defining the application menu
|
||||
|
||||
#### 🧊 `void SetContextMenu(BrowserWindow browserWindow, MenuItem[] menuItems)`
|
||||
Sets a context menu for a specific browser window.
|
||||
|
||||
**Parameters:**
|
||||
- `browserWindow` - The browser window to attach the context menu to
|
||||
- `menuItems` - Array of MenuItem objects defining the context menu
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Application Menu
|
||||
|
||||
```csharp
|
||||
// Create application menu
|
||||
var menuItems = new[]
|
||||
{
|
||||
new MenuItem
|
||||
{
|
||||
Label = "File",
|
||||
Submenu = new[]
|
||||
{
|
||||
new MenuItem { Label = "New", Click = () => CreateNewDocument() },
|
||||
new MenuItem { Label = "Open", Click = () => OpenDocument() },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Label = "Exit", Click = () => Electron.App.Quit() }
|
||||
}
|
||||
},
|
||||
new MenuItem
|
||||
{
|
||||
Label = "Edit",
|
||||
Submenu = new[]
|
||||
{
|
||||
new MenuItem { Role = MenuRole.Undo },
|
||||
new MenuItem { Role = MenuRole.Redo },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Role = MenuRole.Cut },
|
||||
new MenuItem { Role = MenuRole.Copy },
|
||||
new MenuItem { Role = MenuRole.Paste }
|
||||
}
|
||||
},
|
||||
new MenuItem
|
||||
{
|
||||
Label = "View",
|
||||
Submenu = new[]
|
||||
{
|
||||
new MenuItem { Role = MenuRole.Reload },
|
||||
new MenuItem { Role = MenuRole.ForceReload },
|
||||
new MenuItem { Role = MenuRole.ToggleDevTools },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Role = MenuRole.ResetZoom },
|
||||
new MenuItem { Role = MenuRole.ZoomIn },
|
||||
new MenuItem { Role = MenuRole.ZoomOut }
|
||||
}
|
||||
},
|
||||
new MenuItem
|
||||
{
|
||||
Label = "Window",
|
||||
Submenu = new[]
|
||||
{
|
||||
new MenuItem { Role = MenuRole.Minimize },
|
||||
new MenuItem { Role = MenuRole.Close }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Set application menu
|
||||
Electron.Menu.SetApplicationMenu(menuItems);
|
||||
```
|
||||
|
||||
### Context Menu
|
||||
|
||||
```csharp
|
||||
// Create context menu for specific window
|
||||
var contextMenuItems = new[]
|
||||
{
|
||||
new MenuItem { Label = "Copy", Click = () => CopySelectedText() },
|
||||
new MenuItem { Label = "Paste", Click = () => PasteText() },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Label = "Inspect Element", Click = () => InspectElement() }
|
||||
};
|
||||
|
||||
// Set context menu for window
|
||||
Electron.Menu.SetContextMenu(mainWindow, contextMenuItems);
|
||||
|
||||
// Show context menu programmatically
|
||||
Electron.Menu.ContextMenuPopup(mainWindow);
|
||||
```
|
||||
|
||||
### Menu with Keyboard Shortcuts
|
||||
|
||||
```csharp
|
||||
// Create menu with keyboard shortcuts
|
||||
var menuItems = new[]
|
||||
{
|
||||
new MenuItem
|
||||
{
|
||||
Label = "File",
|
||||
Submenu = new[]
|
||||
{
|
||||
new MenuItem
|
||||
{
|
||||
Label = "New",
|
||||
Accelerator = "CmdOrCtrl+N",
|
||||
Click = () => CreateNewDocument()
|
||||
},
|
||||
new MenuItem
|
||||
{
|
||||
Label = "Open",
|
||||
Accelerator = "CmdOrCtrl+O",
|
||||
Click = () => OpenDocument()
|
||||
},
|
||||
new MenuItem
|
||||
{
|
||||
Label = "Save",
|
||||
Accelerator = "CmdOrCtrl+S",
|
||||
Click = () => SaveDocument()
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Electron.Menu.SetApplicationMenu(menuItems);
|
||||
```
|
||||
|
||||
### Dynamic Menu Updates
|
||||
|
||||
```csharp
|
||||
// Update menu items dynamically
|
||||
var fileMenu = Electron.Menu.MenuItems.FirstOrDefault(m => m.Label == "File");
|
||||
if (fileMenu?.Submenu != null)
|
||||
{
|
||||
var saveItem = fileMenu.Submenu.FirstOrDefault(m => m.Label == "Save");
|
||||
if (saveItem != null)
|
||||
{
|
||||
saveItem.Enabled = HasUnsavedChanges;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Platform-Specific Menus
|
||||
|
||||
```csharp
|
||||
// macOS specific menu items
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
var macMenuItems = new[]
|
||||
{
|
||||
new MenuItem
|
||||
{
|
||||
Label = "MyApp",
|
||||
Submenu = new[]
|
||||
{
|
||||
new MenuItem { Role = MenuRole.About },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Role = MenuRole.Services },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Role = MenuRole.Hide },
|
||||
new MenuItem { Role = MenuRole.HideOthers },
|
||||
new MenuItem { Role = MenuRole.Unhide },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Role = MenuRole.Quit }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Insert before File menu
|
||||
var allMenus = new List<MenuItem>(macMenuItems);
|
||||
allMenus.AddRange(menuItems);
|
||||
Electron.Menu.SetApplicationMenu(allMenus.ToArray());
|
||||
}
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.WindowManager](WindowManager.md) - Windows for context menus
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.GlobalShortcut](GlobalShortcut.md) - Global keyboard shortcuts
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Menu Documentation](https://electronjs.org/docs/api/menu) - Official Electron menu API
|
||||
189
docs/API/NativeTheme.md
Normal file
189
docs/API/NativeTheme.md
Normal file
@@ -0,0 +1,189 @@
|
||||
# Electron.NativeTheme
|
||||
|
||||
Detect and respond to changes in Chromium's native color theme.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.NativeTheme` API provides access to Chromium's native color theme information and allows you to detect and respond to changes in the system's dark/light mode settings. This enables your application to automatically adapt to the user's theme preferences.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<ThemeSourceMode> GetThemeSourceAsync()`
|
||||
Get the current theme source setting.
|
||||
|
||||
**Returns:**
|
||||
|
||||
A `ThemeSourceMode` property that can be `ThemeSourceMode.System`, `ThemeSourceMode.Light` or `ThemeSourceMode.Dark`.
|
||||
|
||||
#### 🧊 `void SetThemeSource(ThemeSourceMode themeSourceMode)`
|
||||
Setting this property to `ThemeSourceMode.System` will remove the override and everything will be reset to the OS default. By default 'ThemeSource' is `ThemeSourceMode.System`.
|
||||
|
||||
**Parameters:**
|
||||
- `themeSourceMode` - The new ThemeSource
|
||||
|
||||
#### 🧊 `Task<bool> ShouldUseDarkColorsAsync()`
|
||||
Check if the system is currently using dark colors.
|
||||
|
||||
**Returns:**
|
||||
|
||||
A bool for if the OS / Chromium currently has a dark mode enabled or is being instructed to show a dark-style UI.
|
||||
|
||||
#### 🧊 `Task<bool> ShouldUseHighContrastColorsAsync()`
|
||||
Check if the system is currently using high contrast colors.
|
||||
|
||||
**Returns:**
|
||||
|
||||
A bool for if the OS / Chromium currently has high-contrast mode enabled or is being instructed to show a high-contrast UI.
|
||||
|
||||
#### 🧊 `Task<bool> ShouldUseInvertedColorSchemeAsync()`
|
||||
Check if the system is currently using an inverted color scheme.
|
||||
|
||||
**Returns:**
|
||||
|
||||
A bool for if the OS / Chromium currently has an inverted color scheme or is being instructed to use an inverted color scheme.
|
||||
|
||||
## Events
|
||||
|
||||
#### ⚡ `Updated`
|
||||
Emitted when something in the underlying NativeTheme has changed. This normally means that either the value of ShouldUseDarkColorsAsync, ShouldUseHighContrastColorsAsync or ShouldUseInvertedColorSchemeAsync has changed.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Theme Detection
|
||||
|
||||
```csharp
|
||||
// Check current theme
|
||||
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
|
||||
Console.WriteLine($"Dark mode: {isDarkMode}");
|
||||
|
||||
// Get current theme source
|
||||
var themeSource = await Electron.NativeTheme.GetThemeSourceAsync();
|
||||
Console.WriteLine($"Theme source: {themeSource}");
|
||||
```
|
||||
|
||||
### Theme Change Monitoring
|
||||
|
||||
```csharp
|
||||
// Monitor theme changes
|
||||
Electron.NativeTheme.Updated += () =>
|
||||
{
|
||||
Console.WriteLine("Theme updated");
|
||||
UpdateApplicationTheme();
|
||||
};
|
||||
|
||||
async void UpdateApplicationTheme()
|
||||
{
|
||||
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
|
||||
var isHighContrast = await Electron.NativeTheme.ShouldUseHighContrastColorsAsync();
|
||||
|
||||
// Update application appearance
|
||||
ApplyTheme(isDarkMode, isHighContrast);
|
||||
}
|
||||
```
|
||||
|
||||
### Manual Theme Control
|
||||
|
||||
```csharp
|
||||
// Force dark theme
|
||||
Electron.NativeTheme.SetThemeSource(ThemeSourceMode.Dark);
|
||||
|
||||
// Force light theme
|
||||
Electron.NativeTheme.SetThemeSource(ThemeSourceMode.Light);
|
||||
|
||||
// Follow system theme
|
||||
Electron.NativeTheme.SetThemeSource(ThemeSourceMode.System);
|
||||
```
|
||||
|
||||
### Application Theme Integration
|
||||
|
||||
```csharp
|
||||
public async Task InitializeThemeSupport()
|
||||
{
|
||||
// Set initial theme based on system preference
|
||||
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
|
||||
ApplyTheme(isDarkMode);
|
||||
|
||||
// Monitor theme changes
|
||||
Electron.NativeTheme.Updated += async () =>
|
||||
{
|
||||
var darkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
|
||||
ApplyTheme(darkMode);
|
||||
};
|
||||
}
|
||||
|
||||
private void ApplyTheme(bool isDarkMode)
|
||||
{
|
||||
if (isDarkMode)
|
||||
{
|
||||
// Apply dark theme
|
||||
SetDarkThemeColors();
|
||||
UpdateWindowTheme("dark");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Apply light theme
|
||||
SetLightThemeColors();
|
||||
UpdateWindowTheme("light");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Theme Management
|
||||
|
||||
```csharp
|
||||
// Check all theme properties
|
||||
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
|
||||
var isHighContrast = await Electron.NativeTheme.ShouldUseHighContrastColorsAsync();
|
||||
var isInverted = await Electron.NativeTheme.ShouldUseInvertedColorSchemeAsync();
|
||||
|
||||
Console.WriteLine($"Dark mode: {isDarkMode}");
|
||||
Console.WriteLine($"High contrast: {isHighContrast}");
|
||||
Console.WriteLine($"Inverted: {isInverted}");
|
||||
|
||||
// Apply appropriate theme
|
||||
if (isHighContrast)
|
||||
{
|
||||
ApplyHighContrastTheme();
|
||||
}
|
||||
else if (isDarkMode)
|
||||
{
|
||||
ApplyDarkTheme();
|
||||
}
|
||||
else
|
||||
{
|
||||
ApplyLightTheme();
|
||||
}
|
||||
```
|
||||
|
||||
### Theme-Aware Window Creation
|
||||
|
||||
```csharp
|
||||
// Create window with theme-appropriate settings
|
||||
var isDarkMode = await Electron.NativeTheme.ShouldUseDarkColorsAsync();
|
||||
|
||||
var windowOptions = new BrowserWindowOptions
|
||||
{
|
||||
Width = 1200,
|
||||
Height = 800,
|
||||
Title = "My Application",
|
||||
BackgroundColor = isDarkMode ? "#1a1a1a" : "#ffffff",
|
||||
WebPreferences = new WebPreferences
|
||||
{
|
||||
// Additional web preferences based on theme
|
||||
}
|
||||
};
|
||||
|
||||
var window = await Electron.WindowManager.CreateWindowAsync(windowOptions);
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.WindowManager](WindowManager.md) - Apply theme to windows
|
||||
- [Electron.Screen](Screen.md) - Screen-related theme considerations
|
||||
- [Electron.App](App.md) - Application-level theme events
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron NativeTheme Documentation](https://electronjs.org/docs/api/native-theme) - Official Electron native theme API
|
||||
- [Theme Support](../Core/What's-New.md) - Understanding theme functionality
|
||||
- [User Experience](../Using/Configuration.md) - Design theme-aware applications
|
||||
164
docs/API/Notification.md
Normal file
164
docs/API/Notification.md
Normal file
@@ -0,0 +1,164 @@
|
||||
# Electron.Notification
|
||||
|
||||
Show native desktop notifications with custom content and actions.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.Notification` API provides the ability to show native desktop notifications with custom titles, bodies, icons, and actions. Notifications work across Windows, macOS, and Linux with platform-specific behavior.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<bool> IsSupportedAsync()`
|
||||
Check if desktop notifications are supported on the current platform.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether or not desktop notifications are supported on the current system.
|
||||
|
||||
#### 🧊 `void Show(NotificationOptions notificationOptions)`
|
||||
Create OS desktop notifications with the specified options.
|
||||
|
||||
**Parameters:**
|
||||
- `notificationOptions` - Notification configuration options
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Notification
|
||||
|
||||
```csharp
|
||||
// Simple notification
|
||||
Electron.Notification.Show(new NotificationOptions
|
||||
{
|
||||
Title = "My Application",
|
||||
Body = "This is a notification message",
|
||||
Icon = "assets/notification-icon.png"
|
||||
});
|
||||
```
|
||||
|
||||
### Notification with Actions
|
||||
|
||||
```csharp
|
||||
// Notification with reply action
|
||||
Electron.Notification.Show(new NotificationOptions
|
||||
{
|
||||
Title = "New Message",
|
||||
Body = "You have a new message from John",
|
||||
Icon = "assets/message-icon.png",
|
||||
Actions = new[]
|
||||
{
|
||||
new NotificationAction { Text = "Reply", Type = NotificationActionType.Button },
|
||||
new NotificationAction { Text = "View", Type = NotificationActionType.Button }
|
||||
},
|
||||
OnClick = () => OpenMessageWindow(),
|
||||
OnAction = (action) =>
|
||||
{
|
||||
if (action == "Reply")
|
||||
{
|
||||
ShowReplyDialog();
|
||||
}
|
||||
else if (action == "View")
|
||||
{
|
||||
OpenMessageWindow();
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Rich Notifications
|
||||
|
||||
```csharp
|
||||
// Rich notification with all options
|
||||
Electron.Notification.Show(new NotificationOptions
|
||||
{
|
||||
Title = "Download Complete",
|
||||
Subtitle = "Your file has finished downloading",
|
||||
Body = "document.pdf has been downloaded to your Downloads folder.",
|
||||
Icon = "assets/download-icon.png",
|
||||
ImageUrl = "file://" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets/preview.png"),
|
||||
Sound = NotificationSound.Default,
|
||||
Urgency = NotificationUrgency.Normal,
|
||||
Category = "transfer.complete",
|
||||
Tag = "download-123",
|
||||
Actions = new[]
|
||||
{
|
||||
new NotificationAction { Text = "Open", Type = NotificationActionType.Button },
|
||||
new NotificationAction { Text = "Show in Folder", Type = NotificationActionType.Button }
|
||||
},
|
||||
OnShow = () => Console.WriteLine("Notification shown"),
|
||||
OnClick = () => OpenDownloadedFile(),
|
||||
OnClose = () => Console.WriteLine("Notification closed"),
|
||||
OnAction = (action) =>
|
||||
{
|
||||
if (action == "Open")
|
||||
{
|
||||
OpenDownloadedFile();
|
||||
}
|
||||
else if (action == "Show in Folder")
|
||||
{
|
||||
ShowInFolder();
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Platform-Specific Notifications
|
||||
|
||||
```csharp
|
||||
// Windows toast notification
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
Electron.Notification.Show(new NotificationOptions
|
||||
{
|
||||
Title = "Background Task",
|
||||
Body = "Your backup is complete",
|
||||
Icon = "assets/app-icon.ico",
|
||||
Tag = "backup-complete",
|
||||
RequireInteraction = true
|
||||
});
|
||||
}
|
||||
|
||||
// macOS notification with sound
|
||||
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
Electron.Notification.Show(new NotificationOptions
|
||||
{
|
||||
Title = "Alert",
|
||||
Body = "Something needs your attention",
|
||||
Sound = NotificationSound.Default,
|
||||
Actions = new[]
|
||||
{
|
||||
new NotificationAction { Text = "View", Type = NotificationActionType.Button }
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Notification Management
|
||||
|
||||
```csharp
|
||||
// Check notification support
|
||||
var isSupported = await Electron.Notification.IsSupportedAsync();
|
||||
Console.WriteLine($"Notifications supported: {isSupported}");
|
||||
|
||||
// Create notification with events
|
||||
var notification = new NotificationOptions
|
||||
{
|
||||
Title = "Task Complete",
|
||||
Body = "Your long-running task has finished",
|
||||
OnShow = () => Console.WriteLine("Notification displayed"),
|
||||
OnClick = () => OpenTaskResults(),
|
||||
OnClose = () => Console.WriteLine("Notification dismissed")
|
||||
};
|
||||
|
||||
Electron.Notification.Show(notification);
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.Tray](Tray.md) - System tray integration with notifications
|
||||
- [Electron.Screen](Screen.md) - Position notifications based on screen layout
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Notification Documentation](https://electronjs.org/docs/api/notification) - Official Electron notification API
|
||||
62
docs/API/Overview.md
Normal file
62
docs/API/Overview.md
Normal file
@@ -0,0 +1,62 @@
|
||||
# API Reference Overview
|
||||
|
||||
The ElectronNET.Core API provides comprehensive access to Electron's native desktop functionality through a .NET interface. This section documents all the available API classes and their methods, events, and usage patterns.
|
||||
|
||||
## API Classes
|
||||
|
||||
### Core Application Management
|
||||
- **[Electron.App](App.md)** - Control your application's event lifecycle, manage app metadata, and handle system-level operations
|
||||
- **[Electron.WindowManager](WindowManager.md)** - Create and manage browser windows, control window behavior and appearance
|
||||
- **[Electron.Menu](Menu.md)** - Create application menus, context menus, and menu items with full keyboard shortcut support
|
||||
|
||||
### User Interface & Interaction
|
||||
- **[Electron.Dialog](Dialog.md)** - Display native system dialogs for opening/saving files, showing messages and alerts
|
||||
- **[Electron.Notification](Notification.md)** - Show native desktop notifications with custom content and actions
|
||||
- **[Electron.Tray](Tray.md)** - Create system tray icons with context menus and tooltip support
|
||||
- **[Electron.Dock](Dock.md)** - macOS dock integration for bounce effects and badge counts
|
||||
|
||||
### System Integration
|
||||
- **[Electron.Shell](Shell.md)** - Desktop integration for opening files, URLs, and accessing system paths
|
||||
- **[Electron.Clipboard](Clipboard.md)** - Read from and write to the system clipboard with multiple data formats
|
||||
- **[Electron.Screen](Screen.md)** - Access display and screen information for responsive layouts
|
||||
- **[Electron.NativeTheme](NativeTheme.md)** - Detect and respond to system theme changes (light/dark mode)
|
||||
|
||||
### Communication & Automation
|
||||
- **[Electron.IpcMain](IpcMain.md)** - Inter-process communication between main process and renderer processes
|
||||
- **[Electron.HostHook](HostHook.md)** - Custom host hook functionality for advanced integration scenarios
|
||||
- **[Electron.GlobalShortcut](GlobalShortcut.md)** - Register global keyboard shortcuts that work even when app is not focused
|
||||
- **[Electron.AutoUpdater](AutoUpdater.md)** - Handle application updates and installation processes
|
||||
|
||||
### System Monitoring
|
||||
- **[Electron.PowerMonitor](PowerMonitor.md)** - Monitor system power events like sleep, wake, and battery status
|
||||
|
||||
|
||||
## API Relationships
|
||||
|
||||
### Window and Dialog Integration
|
||||
- Use `BrowserWindow` instances as parent windows for dialogs
|
||||
- Dialogs automatically become modal when parent window is provided
|
||||
- Window events coordinate with application lifecycle events
|
||||
|
||||
### IPC Communication
|
||||
- `IpcMain` handles communication from renderer processes
|
||||
- Use with `Electron.WindowManager` for window-specific messaging
|
||||
- Coordinate with `Electron.App` events for application-wide communication
|
||||
|
||||
### System Integration
|
||||
- `Shell` operations work with file paths from `Dialog` operations
|
||||
- `Screen` information helps create properly sized windows
|
||||
- `Notification` and `Tray` provide complementary user interaction methods
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Electron.App](App.md)** - Start with application lifecycle management
|
||||
- **[Electron.WindowManager](WindowManager.md)** - Learn window creation and management
|
||||
- **[Electron.Dialog](Dialog.md)** - Add file operations and user interactions
|
||||
- **[Electron.Menu](Menu.md)** - Implement application menus and shortcuts
|
||||
|
||||
## 📚 Additional Resources
|
||||
|
||||
- **[Electron Documentation](https://electronjs.org/docs)** - Official Electron API reference
|
||||
- **[Getting Started](../GettingStarted/ASP.Net.md)** - Development setup guides
|
||||
- **[Migration Guide](../Core/Migration-Guide.md)** - Moving from previous versions
|
||||
188
docs/API/PowerMonitor.md
Normal file
188
docs/API/PowerMonitor.md
Normal file
@@ -0,0 +1,188 @@
|
||||
# Electron.PowerMonitor
|
||||
|
||||
Monitor system power events like sleep, wake, and battery status.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.PowerMonitor` API provides access to system power events and state changes. This includes monitoring when the system is going to sleep, waking up, or changing power sources.
|
||||
|
||||
## Events
|
||||
|
||||
#### ⚡ `OnAC`
|
||||
Emitted when the system changes to AC power.
|
||||
|
||||
#### ⚡ `OnBattery`
|
||||
Emitted when system changes to battery power.
|
||||
|
||||
#### ⚡ `OnLockScreen`
|
||||
Emitted when the system is about to lock the screen.
|
||||
|
||||
#### ⚡ `OnResume`
|
||||
Emitted when system is resuming.
|
||||
|
||||
#### ⚡ `OnShutdown`
|
||||
Emitted when the system is about to reboot or shut down.
|
||||
|
||||
#### ⚡ `OnSuspend`
|
||||
Emitted when the system is suspending.
|
||||
|
||||
#### ⚡ `OnUnLockScreen`
|
||||
Emitted when the system is about to unlock the screen.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Power Event Monitoring
|
||||
|
||||
```csharp
|
||||
// Monitor system sleep/wake
|
||||
Electron.PowerMonitor.OnSuspend += () =>
|
||||
{
|
||||
Console.WriteLine("System going to sleep");
|
||||
// Save application state
|
||||
SaveApplicationState();
|
||||
};
|
||||
|
||||
Electron.PowerMonitor.OnResume += () =>
|
||||
{
|
||||
Console.WriteLine("System waking up");
|
||||
// Restore application state
|
||||
RestoreApplicationState();
|
||||
};
|
||||
```
|
||||
|
||||
### Screen Lock/Unlock Monitoring
|
||||
|
||||
```csharp
|
||||
// Handle screen lock events
|
||||
Electron.PowerMonitor.OnLockScreen += () =>
|
||||
{
|
||||
Console.WriteLine("Screen locking");
|
||||
// Pause real-time operations
|
||||
PauseRealTimeOperations();
|
||||
};
|
||||
|
||||
Electron.PowerMonitor.OnUnLockScreen += () =>
|
||||
{
|
||||
Console.WriteLine("Screen unlocking");
|
||||
// Resume real-time operations
|
||||
ResumeRealTimeOperations();
|
||||
};
|
||||
```
|
||||
|
||||
### Power Source Changes
|
||||
|
||||
```csharp
|
||||
// Monitor power source changes
|
||||
Electron.PowerMonitor.OnAC += () =>
|
||||
{
|
||||
Console.WriteLine("Switched to AC power");
|
||||
// Adjust power-intensive operations
|
||||
EnablePowerIntensiveFeatures();
|
||||
};
|
||||
|
||||
Electron.PowerMonitor.OnBattery += () =>
|
||||
{
|
||||
Console.WriteLine("Switched to battery power");
|
||||
// Reduce power consumption
|
||||
EnablePowerSavingMode();
|
||||
};
|
||||
```
|
||||
|
||||
### System Shutdown Handling
|
||||
|
||||
```csharp
|
||||
// Handle system shutdown
|
||||
Electron.PowerMonitor.OnShutdown += () =>
|
||||
{
|
||||
Console.WriteLine("System shutting down");
|
||||
// Save critical data and exit gracefully
|
||||
SaveAndExit();
|
||||
};
|
||||
```
|
||||
|
||||
### Application State Management
|
||||
|
||||
```csharp
|
||||
private bool isSuspended = false;
|
||||
|
||||
public void InitializePowerMonitoring()
|
||||
{
|
||||
// Track suspension state
|
||||
Electron.PowerMonitor.OnSuspend += () =>
|
||||
{
|
||||
isSuspended = true;
|
||||
OnSystemSleep();
|
||||
};
|
||||
|
||||
Electron.PowerMonitor.OnResume += () =>
|
||||
{
|
||||
isSuspended = false;
|
||||
OnSystemWake();
|
||||
};
|
||||
|
||||
// Handle screen lock for security
|
||||
Electron.PowerMonitor.OnLockScreen += () =>
|
||||
{
|
||||
OnScreenLocked();
|
||||
};
|
||||
}
|
||||
|
||||
private void OnSystemSleep()
|
||||
{
|
||||
// Pause network operations
|
||||
PauseNetworkOperations();
|
||||
|
||||
// Save unsaved work
|
||||
AutoSaveDocuments();
|
||||
|
||||
// Reduce resource usage
|
||||
MinimizeResourceUsage();
|
||||
}
|
||||
|
||||
private void OnSystemWake()
|
||||
{
|
||||
// Resume network operations
|
||||
ResumeNetworkOperations();
|
||||
|
||||
// Check for updates
|
||||
CheckForUpdates();
|
||||
|
||||
// Restore full functionality
|
||||
RestoreFullFunctionality();
|
||||
}
|
||||
|
||||
private void OnScreenLocked()
|
||||
{
|
||||
// Hide sensitive information
|
||||
HideSensitiveData();
|
||||
|
||||
// Pause real-time features
|
||||
PauseRealTimeFeatures();
|
||||
}
|
||||
```
|
||||
|
||||
### Battery Status Monitoring
|
||||
|
||||
```csharp
|
||||
// Monitor battery status changes
|
||||
Electron.PowerMonitor.OnAC += () =>
|
||||
{
|
||||
Console.WriteLine("Plugged in - full performance mode");
|
||||
EnableFullPerformanceMode();
|
||||
};
|
||||
|
||||
Electron.PowerMonitor.OnBattery += () =>
|
||||
{
|
||||
Console.WriteLine("On battery - power saving mode");
|
||||
EnablePowerSavingMode();
|
||||
};
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.Notification](Notification.md) - Notify users about power events
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron PowerMonitor Documentation](https://electronjs.org/docs/api/power-monitor) - Official Electron power monitor API
|
||||
174
docs/API/Screen.md
Normal file
174
docs/API/Screen.md
Normal file
@@ -0,0 +1,174 @@
|
||||
# Electron.Screen
|
||||
|
||||
Access display and screen information for responsive layouts.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.Screen` API provides access to screen and display information, including screen size, display metrics, cursor position, and multi-monitor configurations. This is essential for creating responsive applications that adapt to different screen configurations.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<Display[]> GetAllDisplaysAsync()`
|
||||
Gets information about all available displays.
|
||||
|
||||
**Returns:**
|
||||
|
||||
An array of displays that are currently available.
|
||||
|
||||
#### 🧊 `Task<Point> GetCursorScreenPointAsync()`
|
||||
Gets the current position of the mouse cursor on screen.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The current absolute position of the mouse pointer.
|
||||
|
||||
#### 🧊 `Task<Display> GetDisplayMatchingAsync(Rectangle rectangle)`
|
||||
Gets the display that most closely intersects the provided bounds.
|
||||
|
||||
**Parameters:**
|
||||
- `rectangle` - The rectangle to find the matching display for
|
||||
|
||||
**Returns:**
|
||||
|
||||
The display that most closely intersects the provided bounds.
|
||||
|
||||
#### 🧊 `Task<Display> GetDisplayNearestPointAsync(Point point)`
|
||||
Gets the display that is closest to the specified point.
|
||||
|
||||
**Parameters:**
|
||||
- `point` - The point to find the nearest display for
|
||||
|
||||
**Returns:**
|
||||
|
||||
The display nearest the specified point.
|
||||
|
||||
#### 🧊 `Task<int> GetMenuBarHeightAsync()`
|
||||
macOS: The height of the menu bar in pixels.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The height of the menu bar in pixels.
|
||||
|
||||
#### 🧊 `Task<Display> GetPrimaryDisplayAsync()`
|
||||
Gets information about the primary display (main screen).
|
||||
|
||||
**Returns:**
|
||||
|
||||
The primary display.
|
||||
|
||||
## Events
|
||||
|
||||
#### ⚡ `OnDisplayAdded`
|
||||
Emitted when a new Display has been added.
|
||||
|
||||
#### ⚡ `OnDisplayMetricsChanged`
|
||||
Emitted when one or more metrics change in a display. The changedMetrics is an array of strings that describe the changes. Possible changes are bounds, workArea, scaleFactor and rotation.
|
||||
|
||||
#### ⚡ `OnDisplayRemoved`
|
||||
Emitted when oldDisplay has been removed.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Display Information
|
||||
|
||||
```csharp
|
||||
// Get primary display
|
||||
var primaryDisplay = await Electron.Screen.GetPrimaryDisplayAsync();
|
||||
Console.WriteLine($"Primary display: {primaryDisplay.Size.Width}x{primaryDisplay.Size.Height}");
|
||||
|
||||
// Get all displays
|
||||
var displays = await Electron.Screen.GetAllDisplaysAsync();
|
||||
Console.WriteLine($"Available displays: {displays.Length}");
|
||||
|
||||
// Get display near cursor
|
||||
var cursorPoint = await Electron.Screen.GetCursorScreenPointAsync();
|
||||
var nearestDisplay = await Electron.Screen.GetDisplayNearestPointAsync(cursorPoint);
|
||||
Console.WriteLine($"Nearest display scale factor: {nearestDisplay.ScaleFactor}");
|
||||
```
|
||||
|
||||
### Multi-Monitor Setup
|
||||
|
||||
```csharp
|
||||
// Get all displays for multi-monitor setup
|
||||
var displays = await Electron.Screen.GetAllDisplaysAsync();
|
||||
|
||||
foreach (var display in displays)
|
||||
{
|
||||
Console.WriteLine($"Display {display.Id}:");
|
||||
Console.WriteLine($" Size: {display.Size.Width}x{display.Size.Height}");
|
||||
Console.WriteLine($" Position: {display.Bounds.X},{display.Bounds.Y}");
|
||||
Console.WriteLine($" Scale Factor: {display.ScaleFactor}");
|
||||
Console.WriteLine($" Work Area: {display.WorkArea.Width}x{display.WorkArea.Height}");
|
||||
}
|
||||
```
|
||||
|
||||
### Responsive Window Placement
|
||||
|
||||
```csharp
|
||||
// Create window on appropriate display
|
||||
var displays = await Electron.Screen.GetAllDisplaysAsync();
|
||||
var targetDisplay = displays.FirstOrDefault(d => d.Bounds.X > 0) ?? displays.First();
|
||||
|
||||
var windowOptions = new BrowserWindowOptions
|
||||
{
|
||||
Width = Math.Min(1200, targetDisplay.WorkArea.Width),
|
||||
Height = Math.Min(800, targetDisplay.WorkArea.Height),
|
||||
X = targetDisplay.WorkArea.X + (targetDisplay.WorkArea.Width - 1200) / 2,
|
||||
Y = targetDisplay.WorkArea.Y + (targetDisplay.WorkArea.Height - 800) / 2
|
||||
};
|
||||
|
||||
var window = await Electron.WindowManager.CreateWindowAsync(windowOptions);
|
||||
```
|
||||
|
||||
### Display Change Monitoring
|
||||
|
||||
```csharp
|
||||
// Monitor display changes
|
||||
Electron.Screen.OnDisplayAdded += (display) =>
|
||||
{
|
||||
Console.WriteLine($"Display added: {display.Id}");
|
||||
UpdateWindowPositions();
|
||||
};
|
||||
|
||||
Electron.Screen.OnDisplayRemoved += (display) =>
|
||||
{
|
||||
Console.WriteLine($"Display removed: {display.Id}");
|
||||
UpdateWindowPositions();
|
||||
};
|
||||
|
||||
Electron.Screen.OnDisplayMetricsChanged += (display, metrics) =>
|
||||
{
|
||||
Console.WriteLine($"Display {display.Id} metrics changed: {string.Join(", ", metrics)}");
|
||||
UpdateWindowPositions();
|
||||
};
|
||||
|
||||
void UpdateWindowPositions()
|
||||
{
|
||||
// Recalculate window positions based on current displays
|
||||
}
|
||||
```
|
||||
|
||||
### macOS Menu Bar Height
|
||||
|
||||
```csharp
|
||||
// Account for menu bar height on macOS
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
var menuBarHeight = await Electron.Screen.GetMenuBarHeightAsync();
|
||||
|
||||
var windowOptions = new BrowserWindowOptions
|
||||
{
|
||||
Y = menuBarHeight, // Position below menu bar
|
||||
TitleBarStyle = TitleBarStyle.Hidden // Hide title bar for custom look
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.WindowManager](WindowManager.md) - Position windows based on screen information
|
||||
- [Electron.App](App.md) - Handle display-related application events
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Screen Documentation](https://electronjs.org/docs/api/screen) - Official Electron screen API
|
||||
175
docs/API/Shell.md
Normal file
175
docs/API/Shell.md
Normal file
@@ -0,0 +1,175 @@
|
||||
# Electron.Shell
|
||||
|
||||
Desktop integration for opening files, URLs, and accessing system paths.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.Shell` API provides system integration functionality for opening files and URLs with their default applications, managing trash/recycle bin, and creating/reading shortcut links.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `void Beep()`
|
||||
Play the beep sound.
|
||||
|
||||
#### 🧊 `Task<string> OpenExternalAsync(string url)`
|
||||
Open the given external protocol URL in the desktop's default manner (e.g., mailto: URLs in the user's default mail agent).
|
||||
|
||||
**Parameters:**
|
||||
- `url` - Max 2081 characters on windows
|
||||
|
||||
**Returns:**
|
||||
|
||||
The error message corresponding to the failure if a failure occurred, otherwise empty string.
|
||||
|
||||
#### 🧊 `Task<string> OpenExternalAsync(string url, OpenExternalOptions options)`
|
||||
Open the given external protocol URL with additional options.
|
||||
|
||||
**Parameters:**
|
||||
- `url` - Max 2081 characters on windows
|
||||
- `options` - Controls the behavior of OpenExternal
|
||||
|
||||
**Returns:**
|
||||
|
||||
The error message corresponding to the failure if a failure occurred, otherwise empty string.
|
||||
|
||||
#### 🧊 `Task<string> OpenPathAsync(string path)`
|
||||
Open the given file in the desktop's default manner.
|
||||
|
||||
**Parameters:**
|
||||
- `path` - The path to the directory or file
|
||||
|
||||
**Returns:**
|
||||
|
||||
The error message corresponding to the failure if a failure occurred, otherwise empty string.
|
||||
|
||||
#### 🧊 `Task<ShortcutDetails> ReadShortcutLinkAsync(string shortcutPath)`
|
||||
Resolves the shortcut link at shortcutPath. An exception will be thrown when any error happens.
|
||||
|
||||
**Parameters:**
|
||||
- `shortcutPath` - The path to the shortcut
|
||||
|
||||
**Returns:**
|
||||
|
||||
ShortcutDetails of the shortcut.
|
||||
|
||||
#### 🧊 `Task ShowItemInFolderAsync(string fullPath)`
|
||||
Show the given file in a file manager. If possible, select the file.
|
||||
|
||||
**Parameters:**
|
||||
- `fullPath` - The full path to the directory or file
|
||||
|
||||
#### 🧊 `Task<bool> TrashItemAsync(string fullPath)`
|
||||
Move the given file to trash and returns a bool status for the operation.
|
||||
|
||||
**Parameters:**
|
||||
- `fullPath` - The full path to the directory or file
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the item was successfully moved to the trash.
|
||||
|
||||
#### 🧊 `Task<bool> WriteShortcutLinkAsync(string shortcutPath, ShortcutLinkOperation operation, ShortcutDetails options)`
|
||||
Creates or updates a shortcut link at shortcutPath.
|
||||
|
||||
**Parameters:**
|
||||
- `shortcutPath` - The path to the shortcut
|
||||
- `operation` - Default is ShortcutLinkOperation.Create
|
||||
- `options` - Structure of a shortcut
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the shortcut was created successfully.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### File Operations
|
||||
|
||||
```csharp
|
||||
// Open file with default application
|
||||
var error = await Electron.Shell.OpenPathAsync(filePath);
|
||||
if (string.IsNullOrEmpty(error))
|
||||
{
|
||||
Console.WriteLine("File opened successfully");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"Failed to open file: {error}");
|
||||
}
|
||||
|
||||
// Show file in file manager
|
||||
await Electron.Shell.ShowItemInFolderAsync(filePath);
|
||||
|
||||
// Move file to trash
|
||||
var trashed = await Electron.Shell.TrashItemAsync(filePath);
|
||||
Console.WriteLine($"File trashed: {trashed}");
|
||||
```
|
||||
|
||||
### URL Operations
|
||||
|
||||
```csharp
|
||||
// Open URL in default browser
|
||||
var error = await Electron.Shell.OpenExternalAsync("https://electron.net");
|
||||
if (!string.IsNullOrEmpty(error))
|
||||
{
|
||||
Console.WriteLine($"Failed to open URL: {error}");
|
||||
}
|
||||
|
||||
// Open email client
|
||||
await Electron.Shell.OpenExternalAsync("mailto:user@example.com");
|
||||
|
||||
// Open with options
|
||||
var error = await Electron.Shell.OpenExternalAsync("https://example.com", new OpenExternalOptions
|
||||
{
|
||||
Activate = true
|
||||
});
|
||||
```
|
||||
|
||||
### System Integration
|
||||
|
||||
```csharp
|
||||
// Play system beep
|
||||
Electron.Shell.Beep();
|
||||
|
||||
// Create desktop shortcut
|
||||
var success = await Electron.Shell.WriteShortcutLinkAsync(
|
||||
@"C:\Users\Public\Desktop\MyApp.lnk",
|
||||
ShortcutLinkOperation.Create,
|
||||
new ShortcutDetails
|
||||
{
|
||||
Target = "C:\\Program Files\\MyApp\\MyApp.exe",
|
||||
Description = "My Application",
|
||||
WorkingDirectory = "C:\\Program Files\\MyApp"
|
||||
}
|
||||
);
|
||||
|
||||
// Read shortcut information
|
||||
var details = await Electron.Shell.ReadShortcutLinkAsync(@"C:\Users\Public\Desktop\MyApp.lnk");
|
||||
Console.WriteLine($"Target: {details.Target}");
|
||||
```
|
||||
|
||||
### Integration with Dialog API
|
||||
|
||||
```csharp
|
||||
// Use with file dialog results
|
||||
var files = await Electron.Dialog.ShowOpenDialogAsync(window, options);
|
||||
if (files.Length > 0)
|
||||
{
|
||||
var selectedFile = files[0];
|
||||
|
||||
// Open the selected file
|
||||
await Electron.Shell.OpenPathAsync(selectedFile);
|
||||
|
||||
// Show in file manager
|
||||
await Electron.Shell.ShowItemInFolderAsync(selectedFile);
|
||||
}
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.Dialog](Dialog.md) - Select files to open with Shell
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.Clipboard](Clipboard.md) - Copy file paths for Shell operations
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Shell Documentation](https://electronjs.org/docs/api/shell) - Official Electron shell API
|
||||
232
docs/API/Tray.md
Normal file
232
docs/API/Tray.md
Normal file
@@ -0,0 +1,232 @@
|
||||
# Electron.Tray
|
||||
|
||||
Add icons and context menus to the system's notification area.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.Tray` API provides the ability to add icons and context menus to the system's notification area (system tray). This allows applications to provide quick access to common functions and maintain a presence in the system even when windows are closed.
|
||||
|
||||
## Properties
|
||||
|
||||
#### 📋 `IReadOnlyCollection<MenuItem> MenuItems`
|
||||
Gets a read-only collection of all current tray menu items.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `void Destroy()`
|
||||
Destroys the tray icon immediately.
|
||||
|
||||
#### 🧊 `void DisplayBalloon(DisplayBalloonOptions options)`
|
||||
Windows: Displays a tray balloon notification.
|
||||
|
||||
**Parameters:**
|
||||
- `options` - Balloon notification options
|
||||
|
||||
#### 🧊 `Task<bool> IsDestroyedAsync()`
|
||||
Check if the tray icon has been destroyed.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the tray icon is destroyed.
|
||||
|
||||
#### 🧊 `void SetImage(string image)`
|
||||
Sets the image associated with this tray icon.
|
||||
|
||||
**Parameters:**
|
||||
- `image` - New image for the tray icon
|
||||
|
||||
#### 🧊 `void SetPressedImage(string image)`
|
||||
Sets the image associated with this tray icon when pressed on macOS.
|
||||
|
||||
**Parameters:**
|
||||
- `image` - Image for pressed state
|
||||
|
||||
#### 🧊 `void SetTitle(string title)`
|
||||
macOS: Sets the title displayed aside of the tray icon in the status bar.
|
||||
|
||||
**Parameters:**
|
||||
- `title` - Title text
|
||||
|
||||
#### 🧊 `void SetToolTip(string toolTip)`
|
||||
Sets the hover text for this tray icon.
|
||||
|
||||
**Parameters:**
|
||||
- `toolTip` - Tooltip text
|
||||
|
||||
#### 🧊 `void Show(string image)`
|
||||
Shows the tray icon without a context menu.
|
||||
|
||||
**Parameters:**
|
||||
- `image` - The image to use for the tray icon
|
||||
|
||||
#### 🧊 `void Show(string image, MenuItem menuItem)`
|
||||
Shows the tray icon with a single menu item.
|
||||
|
||||
**Parameters:**
|
||||
- `image` - The image to use for the tray icon
|
||||
- `menuItem` - Single menu item for the tray context menu
|
||||
|
||||
#### 🧊 `void Show(string image, MenuItem[] menuItems)`
|
||||
Shows the tray icon with multiple menu items.
|
||||
|
||||
**Parameters:**
|
||||
- `image` - The image to use for the tray icon
|
||||
- `menuItems` - Array of menu items for the tray context menu
|
||||
|
||||
## Events
|
||||
|
||||
#### ⚡ `OnBalloonClick`
|
||||
Windows: Emitted when the tray balloon is clicked.
|
||||
|
||||
#### ⚡ `OnBalloonClosed`
|
||||
Windows: Emitted when the tray balloon is closed because of timeout or user manually closes it.
|
||||
|
||||
#### ⚡ `OnBalloonShow`
|
||||
Windows: Emitted when the tray balloon shows.
|
||||
|
||||
#### ⚡ `OnClick`
|
||||
Emitted when the tray icon is clicked.
|
||||
|
||||
#### ⚡ `OnDoubleClick`
|
||||
macOS, Windows: Emitted when the tray icon is double clicked.
|
||||
|
||||
#### ⚡ `OnRightClick`
|
||||
macOS, Windows: Emitted when the tray icon is right clicked.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Tray Icon
|
||||
|
||||
```csharp
|
||||
// Simple tray icon
|
||||
await Electron.Tray.Show("assets/tray-icon.png");
|
||||
|
||||
// Tray icon with single menu item
|
||||
await Electron.Tray.Show("assets/tray-icon.png", new MenuItem
|
||||
{
|
||||
Label = "Show Window",
|
||||
Click = () => ShowMainWindow()
|
||||
});
|
||||
```
|
||||
|
||||
### Tray with Context Menu
|
||||
|
||||
```csharp
|
||||
// Tray with multiple menu items
|
||||
var trayMenuItems = new[]
|
||||
{
|
||||
new MenuItem { Label = "Show Window", Click = () => ShowMainWindow() },
|
||||
new MenuItem { Label = "Settings", Click = () => OpenSettings() },
|
||||
new MenuItem { Type = MenuType.Separator },
|
||||
new MenuItem { Label = "Exit", Click = () => Electron.App.Quit() }
|
||||
};
|
||||
|
||||
await Electron.Tray.Show("assets/tray-icon.png", trayMenuItems);
|
||||
```
|
||||
|
||||
### Dynamic Tray Updates
|
||||
|
||||
```csharp
|
||||
// Update tray tooltip based on status
|
||||
await Electron.Tray.SetToolTip("MyApp - Connected");
|
||||
|
||||
// Change tray icon based on state
|
||||
if (isConnected)
|
||||
{
|
||||
await Electron.Tray.SetImage("assets/connected.png");
|
||||
}
|
||||
else
|
||||
{
|
||||
await Electron.Tray.SetImage("assets/disconnected.png");
|
||||
}
|
||||
```
|
||||
|
||||
### Tray Event Handling
|
||||
|
||||
```csharp
|
||||
// Handle tray clicks
|
||||
Electron.Tray.OnClick += (clickArgs, bounds) =>
|
||||
{
|
||||
if (clickArgs.AltKey || clickArgs.ShiftKey)
|
||||
{
|
||||
// Alt+Click or Shift+Click - show context menu
|
||||
Electron.Menu.ContextMenuPopup(Electron.WindowManager.BrowserWindows.First());
|
||||
}
|
||||
else
|
||||
{
|
||||
// Regular click - toggle main window
|
||||
ToggleMainWindow();
|
||||
}
|
||||
};
|
||||
|
||||
Electron.Tray.OnRightClick += (clickArgs, bounds) =>
|
||||
{
|
||||
// Show context menu on right click
|
||||
Electron.Menu.ContextMenuPopup(Electron.WindowManager.BrowserWindows.First());
|
||||
};
|
||||
```
|
||||
|
||||
### Windows Balloon Notifications
|
||||
|
||||
```csharp
|
||||
// Show Windows balloon notification
|
||||
await Electron.Tray.DisplayBalloon(new DisplayBalloonOptions
|
||||
{
|
||||
Title = "Background Task Complete",
|
||||
Content = "Your file has been processed successfully.",
|
||||
Icon = "assets/notification-icon.ico"
|
||||
});
|
||||
|
||||
// Handle balloon events
|
||||
Electron.Tray.OnBalloonClick += () =>
|
||||
{
|
||||
ShowMainWindow();
|
||||
Electron.WindowManager.BrowserWindows.First().Focus();
|
||||
};
|
||||
```
|
||||
|
||||
### macOS Tray Features
|
||||
|
||||
```csharp
|
||||
// macOS specific tray features
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
await Electron.Tray.SetTitle("MyApp");
|
||||
|
||||
// Use template image for dark mode support
|
||||
await Electron.Tray.SetImage("assets/tray-template.png");
|
||||
await Electron.Tray.SetPressedImage("assets/tray-pressed-template.png");
|
||||
}
|
||||
```
|
||||
|
||||
### Application Integration
|
||||
|
||||
```csharp
|
||||
// Integrate with application lifecycle
|
||||
Electron.App.WindowAllClosed += () =>
|
||||
{
|
||||
// Keep app running in tray when windows are closed
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
|
||||
{
|
||||
Electron.App.Hide();
|
||||
}
|
||||
};
|
||||
|
||||
// Handle tray double-click
|
||||
Electron.Tray.OnDoubleClick += (clickArgs, bounds) =>
|
||||
{
|
||||
ShowMainWindow();
|
||||
Electron.WindowManager.BrowserWindows.First().Focus();
|
||||
};
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.Menu](Menu.md) - Context menus for tray icons
|
||||
- [Electron.Notification](Notification.md) - Desktop notifications
|
||||
- [Electron.App](App.md) - Application lifecycle events
|
||||
- [Electron.WindowManager](WindowManager.md) - Windows to show/hide from tray
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Tray Documentation](https://electronjs.org/docs/api/tray) - Official Electron tray API
|
||||
292
docs/API/WebContents.md
Normal file
292
docs/API/WebContents.md
Normal file
@@ -0,0 +1,292 @@
|
||||
# Electron.WebContents
|
||||
|
||||
Render and control web pages.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.WebContents` API provides control over web page content within Electron windows. It handles page loading, navigation, JavaScript execution, and web page lifecycle events.
|
||||
|
||||
## Properties
|
||||
|
||||
#### 📋 `int Id`
|
||||
Gets the unique identifier for this web contents.
|
||||
|
||||
#### 📋 `Session Session`
|
||||
Manage browser sessions, cookies, cache, proxy settings, etc.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `void ExecuteJavaScriptAsync(string code, bool userGesture = false)`
|
||||
Evaluates script code in page.
|
||||
|
||||
In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation.
|
||||
|
||||
Code execution will be suspended until web page stop loading.
|
||||
|
||||
**Parameters:**
|
||||
- `code` - The code to execute
|
||||
- `userGesture` - if set to `true` simulate a user gesture
|
||||
|
||||
**Returns:**
|
||||
|
||||
The result of the executed code.
|
||||
|
||||
#### 🧊 `Task<PrinterInfo[]> GetPrintersAsync()`
|
||||
Get system printers.
|
||||
|
||||
**Returns:**
|
||||
|
||||
Array of available printers.
|
||||
|
||||
#### 🧊 `Task<string> GetUrl()`
|
||||
Get the URL of the loaded page.
|
||||
|
||||
It's useful if a web-server redirects you and you need to know where it redirects. For instance, It's useful in case of Implicit Authorization.
|
||||
|
||||
**Returns:**
|
||||
|
||||
URL of the loaded page.
|
||||
|
||||
#### 🧊 `void InsertCSS(bool isBrowserWindow, string path)`
|
||||
Inserts CSS into the web page.
|
||||
|
||||
See: https://www.electronjs.org/docs/api/web-contents#contentsinsertcsscss-options
|
||||
|
||||
Works for both BrowserWindows and BrowserViews.
|
||||
|
||||
**Parameters:**
|
||||
- `isBrowserWindow` - Whether the webContents belong to a BrowserWindow or not (the other option is a BrowserView)
|
||||
- `path` - Absolute path to the CSS file location
|
||||
|
||||
#### 🧊 `Task LoadURLAsync(string url)`
|
||||
Loads the url in the window. The url must contain the protocol prefix.
|
||||
|
||||
The async method will resolve when the page has finished loading, and rejects if the page fails to load.
|
||||
|
||||
A noop rejection handler is already attached, which avoids unhandled rejection errors.
|
||||
|
||||
Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it.
|
||||
|
||||
**Parameters:**
|
||||
- `url` - URL to load
|
||||
|
||||
#### 🧊 `Task LoadURLAsync(string url, LoadURLOptions options)`
|
||||
Loads the url with additional options.
|
||||
|
||||
The async method will resolve when the page has finished loading, and rejects if the page fails to load.
|
||||
|
||||
A noop rejection handler is already attached, which avoids unhandled rejection errors.
|
||||
|
||||
Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it.
|
||||
|
||||
**Parameters:**
|
||||
- `url` - URL to load
|
||||
- `options` - Loading options
|
||||
|
||||
#### 🧊 `void OpenDevTools()`
|
||||
Opens the devtools.
|
||||
|
||||
#### 🧊 `void OpenDevTools(OpenDevToolsOptions openDevToolsOptions)`
|
||||
Opens the devtools with options.
|
||||
|
||||
**Parameters:**
|
||||
- `openDevToolsOptions` - Developer tools options
|
||||
|
||||
#### 🧊 `Task<bool> PrintAsync(PrintOptions options = null)`
|
||||
Prints window's web page.
|
||||
|
||||
**Parameters:**
|
||||
- `options` - Print options
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the print operation succeeded.
|
||||
|
||||
#### 🧊 `Task<bool> PrintToPDFAsync(string path, PrintToPDFOptions options = null)`
|
||||
Prints window's web page as PDF with Chromium's preview printing custom settings.The landscape will be ignored if @page CSS at-rule is used in the web page. By default, an empty options will be regarded as: Use page-break-before: always; CSS style to force to print to a new page.
|
||||
|
||||
**Parameters:**
|
||||
- `path` - Output file path
|
||||
- `options` - PDF generation options
|
||||
|
||||
**Returns:**
|
||||
|
||||
Whether the PDF generation succeeded.
|
||||
|
||||
## Events
|
||||
|
||||
#### ⚡ `InputEvent`
|
||||
Emitted when an input event is sent to the WebContents.
|
||||
|
||||
#### ⚡ `OnCrashed`
|
||||
Emitted when the renderer process crashes or is killed.
|
||||
|
||||
#### ⚡ `OnDidFailLoad`
|
||||
Emitted when the load failed.
|
||||
|
||||
#### ⚡ `OnDidFinishLoad`
|
||||
Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the onload event was dispatched.
|
||||
|
||||
#### ⚡ `OnDidNavigate`
|
||||
Emitted when a main frame navigation is done.
|
||||
|
||||
#### ⚡ `OnDidRedirectNavigation`
|
||||
Emitted after a server side redirect occurs during navigation.
|
||||
|
||||
#### ⚡ `OnDidStartNavigation`
|
||||
Emitted when any frame (including main) starts navigating.
|
||||
|
||||
#### ⚡ `OnDomReady`
|
||||
Emitted when the document in the top-level frame is loaded.
|
||||
|
||||
#### ⚡ `OnWillRedirect`
|
||||
Emitted when a server side redirect occurs during navigation.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Page Loading
|
||||
|
||||
```csharp
|
||||
// Load URL with options
|
||||
await webContents.LoadURLAsync("https://example.com", new LoadURLOptions
|
||||
{
|
||||
UserAgent = "MyApp/1.0",
|
||||
ExtraHeaders = "Authorization: Bearer token123"
|
||||
});
|
||||
|
||||
// Load local file
|
||||
await webContents.LoadURLAsync("file://" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app/index.html"));
|
||||
|
||||
// Get current URL
|
||||
var currentUrl = await webContents.GetUrl();
|
||||
Console.WriteLine($"Current URL: {currentUrl}");
|
||||
```
|
||||
|
||||
### JavaScript Execution
|
||||
|
||||
```csharp
|
||||
// Execute simple JavaScript
|
||||
var result = await webContents.ExecuteJavaScriptAsync("document.title");
|
||||
Console.WriteLine($"Page title: {result}");
|
||||
|
||||
// Execute with user gesture simulation
|
||||
await webContents.ExecuteJavaScriptAsync("document.requestFullscreen()", true);
|
||||
|
||||
// Execute complex code
|
||||
var userAgent = await webContents.ExecuteJavaScriptAsync("navigator.userAgent");
|
||||
Console.WriteLine($"User agent: {userAgent}");
|
||||
```
|
||||
|
||||
### Developer Tools
|
||||
|
||||
```csharp
|
||||
// Open dev tools
|
||||
webContents.OpenDevTools();
|
||||
|
||||
// Open with specific options
|
||||
webContents.OpenDevTools(new OpenDevToolsOptions
|
||||
{
|
||||
Mode = DevToolsMode.Detached,
|
||||
Activate = true
|
||||
});
|
||||
```
|
||||
|
||||
### CSS Injection
|
||||
|
||||
```csharp
|
||||
// Inject CSS file
|
||||
webContents.InsertCSS(true, "styles/custom-theme.css");
|
||||
|
||||
// Inject CSS for BrowserView
|
||||
webContents.InsertCSS(false, "styles/browser-view.css");
|
||||
```
|
||||
|
||||
### Printing Operations
|
||||
|
||||
```csharp
|
||||
// Print web page
|
||||
var printSuccess = await webContents.PrintAsync(new PrintOptions
|
||||
{
|
||||
Silent = false,
|
||||
PrintBackground = true,
|
||||
DeviceName = "My Printer"
|
||||
});
|
||||
|
||||
if (printSuccess)
|
||||
{
|
||||
Console.WriteLine("Print job sent successfully");
|
||||
}
|
||||
```
|
||||
|
||||
### PDF Generation
|
||||
|
||||
```csharp
|
||||
// Generate PDF
|
||||
var pdfSuccess = await webContents.PrintToPDFAsync("document.pdf", new PrintToPDFOptions
|
||||
{
|
||||
MarginsType = PrintToPDFMarginsType.None,
|
||||
PageSize = PrintToPDFPageSize.A4,
|
||||
PrintBackground = true,
|
||||
Landscape = false
|
||||
});
|
||||
|
||||
if (pdfSuccess)
|
||||
{
|
||||
Console.WriteLine("PDF generated successfully");
|
||||
}
|
||||
```
|
||||
|
||||
### Navigation Monitoring
|
||||
|
||||
```csharp
|
||||
// Monitor navigation events
|
||||
webContents.OnDidStartNavigation += (url) =>
|
||||
{
|
||||
Console.WriteLine($"Starting navigation to: {url}");
|
||||
};
|
||||
|
||||
webContents.OnDidNavigate += (navInfo) =>
|
||||
{
|
||||
Console.WriteLine($"Navigated to: {navInfo.Url}");
|
||||
};
|
||||
|
||||
webContents.OnDidFinishLoad += () =>
|
||||
{
|
||||
Console.WriteLine("Page finished loading");
|
||||
};
|
||||
|
||||
webContents.OnDidFailLoad += (failInfo) =>
|
||||
{
|
||||
Console.WriteLine($"Page failed to load: {failInfo.ErrorCode} - {failInfo.ErrorDescription}");
|
||||
};
|
||||
```
|
||||
|
||||
### Content Interaction
|
||||
|
||||
```csharp
|
||||
// Wait for DOM ready
|
||||
webContents.OnDomReady += () =>
|
||||
{
|
||||
Console.WriteLine("DOM is ready");
|
||||
// Safe to execute DOM-related JavaScript now
|
||||
};
|
||||
|
||||
// Handle page crashes
|
||||
webContents.OnCrashed += (killed) =>
|
||||
{
|
||||
Console.WriteLine($"Renderer crashed, killed: {killed}");
|
||||
// Optionally reload the page
|
||||
};
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.WindowManager](WindowManager.md) - Windows containing web contents
|
||||
- [Electron.Session](Session.md) - Session management for web contents
|
||||
- [Electron.IpcMain](IpcMain.md) - Communication with web contents
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron WebContents Documentation](https://electronjs.org/docs/api/web-contents) - Official Electron web contents API
|
||||
- [Web Content Management](../Core/What's-New.md) - Understanding web content handling
|
||||
- [Security Considerations](../Using/Configuration.md) - Secure web content integration
|
||||
208
docs/API/WindowManager.md
Normal file
208
docs/API/WindowManager.md
Normal file
@@ -0,0 +1,208 @@
|
||||
# Electron.WindowManager
|
||||
|
||||
Create and manage browser windows, control window behavior and appearance.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Electron.WindowManager` API provides comprehensive control over browser windows in your Electron application. It handles window creation, management, and coordination with the application lifecycle.
|
||||
|
||||
## Properties
|
||||
|
||||
#### 📋 `IReadOnlyCollection<BrowserView> BrowserViews`
|
||||
Gets a read-only collection of all currently open browser views.
|
||||
|
||||
#### 📋 `IReadOnlyCollection<BrowserWindow> BrowserWindows`
|
||||
Gets a read-only collection of all currently open browser windows.
|
||||
|
||||
#### 📋 `bool IsQuitOnWindowAllClosed`
|
||||
Controls whether the application quits when all windows are closed. Default is true.
|
||||
|
||||
## Methods
|
||||
|
||||
#### 🧊 `Task<BrowserView> CreateBrowserViewAsync()`
|
||||
Creates a new browser view with default options.
|
||||
|
||||
**Returns:**
|
||||
|
||||
The created BrowserView instance.
|
||||
|
||||
#### 🧊 `Task<BrowserView> CreateBrowserViewAsync(BrowserViewConstructorOptions options)`
|
||||
Creates a new browser view with custom options.
|
||||
|
||||
**Parameters:**
|
||||
- `options` - Browser view configuration options
|
||||
|
||||
**Returns:**
|
||||
|
||||
The created BrowserView instance.
|
||||
|
||||
#### 🧊 `Task<BrowserWindow> CreateWindowAsync(string loadUrl = "http://localhost")`
|
||||
Creates a new browser window with default options.
|
||||
|
||||
**Parameters:**
|
||||
- `loadUrl` - URL to load in the window. Defaults to "http://localhost"
|
||||
|
||||
**Returns:**
|
||||
|
||||
The created BrowserWindow instance.
|
||||
|
||||
#### 🧊 `Task<BrowserWindow> CreateWindowAsync(BrowserWindowOptions options, string loadUrl = "http://localhost")`
|
||||
Creates a new browser window with custom options.
|
||||
|
||||
**Parameters:**
|
||||
- `options` - Window configuration options
|
||||
- `loadUrl` - URL to load in the window. Defaults to "http://localhost"
|
||||
|
||||
**Returns:**
|
||||
|
||||
The created BrowserWindow instance.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Window Creation
|
||||
|
||||
```csharp
|
||||
// Create window with default options
|
||||
var mainWindow = await Electron.WindowManager.CreateWindowAsync();
|
||||
|
||||
// Create window with custom options
|
||||
var settingsWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions
|
||||
{
|
||||
Width = 800,
|
||||
Height = 600,
|
||||
Show = false,
|
||||
Title = "Settings",
|
||||
WebPreferences = new WebPreferences
|
||||
{
|
||||
NodeIntegration = false,
|
||||
ContextIsolation = true
|
||||
}
|
||||
}, "https://localhost:5001/settings");
|
||||
```
|
||||
|
||||
### Window Management
|
||||
|
||||
```csharp
|
||||
// Get all windows
|
||||
var windows = Electron.WindowManager.BrowserWindows;
|
||||
Console.WriteLine($"Open windows: {windows.Count}");
|
||||
|
||||
// Configure quit behavior
|
||||
Electron.WindowManager.IsQuitOnWindowAllClosed = false; // Keep app running when windows close
|
||||
|
||||
// Handle window lifecycle
|
||||
Electron.App.WindowAllClosed += () =>
|
||||
{
|
||||
Console.WriteLine("All windows closed");
|
||||
if (Electron.WindowManager.IsQuitOnWindowAllClosed)
|
||||
{
|
||||
Electron.App.Quit();
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Browser View Integration
|
||||
|
||||
```csharp
|
||||
// Create browser view
|
||||
var browserView = await Electron.WindowManager.CreateBrowserViewAsync(new BrowserViewConstructorOptions
|
||||
{
|
||||
WebPreferences = new WebPreferences
|
||||
{
|
||||
NodeIntegration = false,
|
||||
ContextIsolation = true
|
||||
}
|
||||
});
|
||||
|
||||
// Add to window
|
||||
await mainWindow.SetBrowserViewAsync(browserView);
|
||||
await browserView.WebContents.LoadURLAsync("https://example.com");
|
||||
|
||||
// Set view bounds
|
||||
await mainWindow.SetBoundsAsync(browserView, new Rectangle
|
||||
{
|
||||
X = 0,
|
||||
Y = 100,
|
||||
Width = 800,
|
||||
Height = 400
|
||||
});
|
||||
```
|
||||
|
||||
### Window Options Configuration
|
||||
|
||||
```csharp
|
||||
// Comprehensive window options
|
||||
var options = new BrowserWindowOptions
|
||||
{
|
||||
Width = 1200,
|
||||
Height = 800,
|
||||
MinWidth = 600,
|
||||
MinHeight = 400,
|
||||
MaxWidth = 1920,
|
||||
MaxHeight = 1080,
|
||||
X = 100,
|
||||
Y = 100,
|
||||
Center = true,
|
||||
Frame = true,
|
||||
Title = "My Application",
|
||||
Icon = "assets/app-icon.png",
|
||||
Show = false,
|
||||
AlwaysOnTop = false,
|
||||
SkipTaskbar = false,
|
||||
Kiosk = false,
|
||||
TitleBarStyle = TitleBarStyle.Default,
|
||||
BackgroundColor = "#FFFFFF",
|
||||
DarkTheme = false,
|
||||
Transparent = false,
|
||||
WebPreferences = new WebPreferences
|
||||
{
|
||||
NodeIntegration = false,
|
||||
ContextIsolation = true,
|
||||
EnableWebSQL = false,
|
||||
Partition = "persist:electron",
|
||||
ZoomFactor = 1.0f,
|
||||
DevTools = true
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Multi-Window Applications
|
||||
|
||||
```csharp
|
||||
// Create main window
|
||||
var mainWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions
|
||||
{
|
||||
Width = 1200,
|
||||
Height = 800,
|
||||
Show = false
|
||||
});
|
||||
|
||||
// Create secondary window
|
||||
var secondaryWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions
|
||||
{
|
||||
Width = 600,
|
||||
Height = 400,
|
||||
Parent = mainWindow,
|
||||
Modal = true,
|
||||
Show = false
|
||||
});
|
||||
|
||||
// Load different content
|
||||
await mainWindow.WebContents.LoadURLAsync("https://localhost:5001");
|
||||
await secondaryWindow.WebContents.LoadURLAsync("https://localhost:5001/settings");
|
||||
|
||||
// Show windows when ready
|
||||
mainWindow.OnReadyToShow += () => mainWindow.Show();
|
||||
secondaryWindow.OnReadyToShow += () => secondaryWindow.Show();
|
||||
```
|
||||
|
||||
## Related APIs
|
||||
|
||||
- [Electron.App](App.md) - Application lifecycle and window events
|
||||
- [Electron.Dialog](Dialog.md) - Parent windows for modal dialogs
|
||||
- [Electron.Menu](Menu.md) - Window-specific menus
|
||||
- [Electron.WebContents](WebContents.md) - Window content management
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Window Management Documentation](https://electronjs.org/docs/api/browser-window) - Official Electron window API
|
||||
51
docs/About.md
Normal file
51
docs/About.md
Normal file
@@ -0,0 +1,51 @@
|
||||
|
||||
|
||||
# About this Project
|
||||
|
||||
Electron.NET has been developed by a small number of people in the hope that it may be useful for others.
|
||||
|
||||
Support for this project in all forms is very welcome, no matter whether in form of code contributions or donations.
|
||||
|
||||
## 💬 Community
|
||||
|
||||
[](https://gitter.im/ElectronNET/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||
|
||||
Besides the chat on Gitter and the issues [discussed here](https://github.com/ElectronNET/Electron.NET/issues) you can also use [StackOverflow](https://stackoverflow.com/questions/tagged/electron.net) with the tag `electron.net`.
|
||||
|
||||
|
||||
## 🙋♀️🙋♂ Contributing
|
||||
|
||||
Feel free to submit a pull request if you find any bugs (to see a list of active issues, visit the [Issues section](https://github.com/ElectronNET/Electron.NET/issues).
|
||||
Please make sure all commits are properly documented.
|
||||
|
||||
|
||||
## 🙏 Donate
|
||||
|
||||
We do this open source work in our free time. If you'd like us to invest more time on it, please [donate](https://donorbox.org/electron-net). Donation can be used to increase some issue priority. Thank you!
|
||||
|
||||
[](https://donorbox.org/electron-net)
|
||||
|
||||
Alternatively, consider using a GitHub sponsorship for the core maintainers:
|
||||
|
||||
- [Gregor Biswanger](https://github.com/sponsors/GregorBiswanger)
|
||||
- [Florian Rappl](https://github.com/sponsors/FlorianRappl)
|
||||
|
||||
Any support appreciated! 🍻
|
||||
|
||||
|
||||
## 👨💻 Authors
|
||||
|
||||
* **[Gregor Biswanger](https://github.com/GregorBiswanger)** - (Microsoft MVP, Intel Black Belt and Intel Software Innovator) is a freelance lecturer, consultant, trainer, author and speaker. He is a consultant for large and medium-sized companies, organizations and agencies for software architecture, web- and cross-platform development. You can find Gregor often on the road attending or speaking at international conferences. - [Cross-Platform-Blog](http://www.cross-platform-blog.com) - Twitter [@BFreakout](https://www.twitter.com/BFreakout)
|
||||
|
||||
* **[Dr. Florian Rappl](https://github.com/FlorianRappl)** - Software Developer - from Munich, Germany. Microsoft MVP & Web Geek. - [The Art of Micro Frontends](https://microfrontends.art) - [Homepage](https://florian-rappl.de) - Twitter [@florianrappl](https://twitter.com/florianrappl)
|
||||
|
||||
* [**softworkz**](https://github.com/softworkz) - full range developer - likes to start where others gave up - MS MVP alumni and Munich citizen as well. Has not been involved in the evolution of Electron.NET but rather dropped off the update and overhaul for ElectronNET.Core in a kind-of drive-by action.
|
||||
|
||||
* **[Robert Muehsig](https://github.com/robertmuehsig)** - Software Developer - from Dresden, Germany, now living & working in Switzerland. Microsoft MVP & Web Geek. - [codeinside Blog](https://blog.codeinside.eu) - Twitter [@robert0muehsig](https://twitter.com/robert0muehsig)
|
||||
|
||||
See also the list of [contributors](https://github.com/ElectronNET/Electron.NET/graphs/contributors) who participated in this project.
|
||||
|
||||
|
||||
## 🎉 License
|
||||
|
||||
MIT-licensed. See [LICENSE](https://github.com/ElectronNET/Electron.NET?tab=MIT-1-ov-file#readme) for details.
|
||||
90
docs/Core/Advanced-Migration-Topics.md
Normal file
90
docs/Core/Advanced-Migration-Topics.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Advanced Migration Topics
|
||||
|
||||
This guide covers advanced scenarios and edge cases that may require additional configuration when migrating to ElectronNET.Core.
|
||||
|
||||
## Custom ASP.NET Port Configuration
|
||||
|
||||
### Port Configuration Changes
|
||||
|
||||
**Previous Approach:**
|
||||
Specifying the WebPort in `electron.manifest.json` is no longer supported because the ASP.NET-first launch mode makes this timing-dependent.
|
||||
|
||||
**New Approach:**
|
||||
Configure custom ASP.NET ports through MSBuild metadata:
|
||||
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<AssemblyMetadata Include="AspNetHttpPort" Value="4000" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
## Custom ElectronHostHook Configuration
|
||||
|
||||
> [!NOTE]
|
||||
> These changes are only required in case you are using a custom ElectronHostHook implementation!
|
||||
> If you have an ElectronHostHook folder in your project but you did not customize that code and aren't using its demo features (Excel and ZIP), you can also just remove that folder from your project.
|
||||
|
||||
|
||||
### TypeScript and Node.js Updates
|
||||
|
||||
**Update package.json:**
|
||||
|
||||
This shows the relevant changes only: All shown versions are the new required minimum versions.
|
||||
|
||||
```json
|
||||
{
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.18",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"socket.io": "^4.8.1",
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Update Project File:**
|
||||
|
||||
The below modifications will allow you to use the latest TypeScript compiler in your ASP.Net project.
|
||||
|
||||
```xml
|
||||
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="5.9.3" />
|
||||
|
||||
<PropertyGroup>
|
||||
<TypeScriptModuleKind>commonjs</TypeScriptModuleKind>
|
||||
<TypeScriptUseNodeJS>true</TypeScriptUseNodeJS>
|
||||
<TypeScriptTSConfig>ElectronHostHook/tsconfig.json</TypeScriptTSConfig>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="publish\**" />
|
||||
<Content Remove="publish\**" />
|
||||
<EmbeddedResource Remove="publish\**" />
|
||||
<None Remove="publish\**" />
|
||||
<TypeScriptCompile Remove="**\node_modules\**" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
### Integration Benefits
|
||||
|
||||
- **Modern TypeScript** - Latest language features and better type checking
|
||||
- **Updated Node.js Types** - Compatibility with Node.js 22.x APIs
|
||||
- **ESLint Integration** - Better code quality and consistency
|
||||
- **MSBuild Compilation** - Integrated with Visual Studio build process
|
||||
|
||||
## Troubleshooting Advanced Scenarios
|
||||
|
||||
### Multi-Project Solutions
|
||||
|
||||
When using ElectronNET.Core in multi-project solutions:
|
||||
|
||||
1. **Install ElectronNET.Core.Api** in class library projects
|
||||
2. **Install ElectronNET.Core and ElectronNET.Core.AspNet** only in the startup project
|
||||
3. **Share configuration** through project references or shared files
|
||||
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **[Migration Guide](Migration-Guide.md)** - Complete migration process
|
||||
- **[What's New?](What's-New.md)** - Overview of all ElectronNET.Core features
|
||||
- **[Getting Started](../GettingStarted/ASP.Net.md)** - Development workflows
|
||||
256
docs/Core/Migration-Checks.md
Normal file
256
docs/Core/Migration-Checks.md
Normal file
@@ -0,0 +1,256 @@
|
||||
# Migration Checks
|
||||
|
||||
Electron.NET includes automatic build-time validation checks that help users migrating from previous versions avoid common configuration issues. These checks run automatically during the build process and provide helpful guidance when problems are detected.
|
||||
|
||||
## Overview
|
||||
|
||||
When you build an Electron.NET project, the following validation checks are performed:
|
||||
|
||||
| Code | Check | Description |
|
||||
|------|-------|-------------|
|
||||
| [ELECTRON001](#1-packagejson-rules) | package.json location rules | Ensures `package.json`/`package-lock.json` aren’t 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
|
||||
173
docs/Core/Migration-Guide.md
Normal file
173
docs/Core/Migration-Guide.md
Normal file
@@ -0,0 +1,173 @@
|
||||
# Migration Guide
|
||||
|
||||
Migrating from previous versions of Electron.NET to ElectronNET.Core is straightforward but requires several important changes. This guide walks you through the process step by step.
|
||||
|
||||
## 📋 Prerequisites
|
||||
|
||||
Before starting the migration:
|
||||
|
||||
- **Backup your project** - Ensure you have a working backup
|
||||
- **Update development tools** - Install Node.js 22.x and .NET 8.0+
|
||||
- **Review current setup** - Note your current Electron and ASP.NET versions
|
||||
|
||||
## 🚀 Migration Steps
|
||||
|
||||
### Step 1: Update NuGet Packages
|
||||
|
||||
**Uninstall old packages:**
|
||||
```powershell
|
||||
dotnet remove package ElectronNET.API
|
||||
```
|
||||
|
||||
**Install new packages:**
|
||||
```powershell
|
||||
dotnet add package ElectronNET.Core
|
||||
dotnet add package ElectronNET.Core.AspNet # For ASP.NET projects
|
||||
```
|
||||
|
||||
> **Note**: The API package is automatically included as a dependency of `ElectronNET.Core`. See [Package Description](../RelInfo/Package-Description.md) for details about the package structure.
|
||||
|
||||
|
||||
### Step 2: Configure Project Settings
|
||||
|
||||
**Auto-generated Configuration:**
|
||||
ElectronNET.Core automatically creates `electron-builder.json` in the `Properties` folder of your project during the first build or NuGet restore. No manual configuration is needed for basic setups.
|
||||
|
||||
**Migrate Existing Configuration:**
|
||||
If you have an existing `electron.manifest.json` file:
|
||||
|
||||
1. **Open the generated `electron-builder.json`** file in your project
|
||||
2. **Locate the 'build' section** in your old `electron.manifest.json`
|
||||
3. **Copy the contents** of the build section (not the "build" key itself) into the new `electron-builder.json`
|
||||
4. **Use Visual Studio Project Designer** to configure Electron settings through the UI
|
||||
5. **Delete the old `electron.manifest.json`** file
|
||||
|
||||
**Alternative: Manual Configuration**
|
||||
You can also manually edit `electron-builder.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"linux": {
|
||||
"target": [
|
||||
"tar.xz"
|
||||
]
|
||||
},
|
||||
"win": {
|
||||
"target": [
|
||||
{
|
||||
"target": "portable",
|
||||
"arch": "x64"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Modify Launch Settings:**
|
||||
ElectronNET.Core no longer needs a separate CLI tool (electronize.exe) for launching. You should update your launch settings to use either the ASP.NET-first or Electron-first approach. See [Debugging](../Using/Debugging.md) for details.
|
||||
|
||||
## 🎯 Testing Migration
|
||||
|
||||
After completing the migration steps:
|
||||
|
||||
1. **Build your project** to ensure no compilation errors
|
||||
2. **Test debugging** using the new ASP.NET-first approach
|
||||
3. **Verify packaging** works with the new configuration
|
||||
4. **Check cross-platform builds** if targeting multiple platforms
|
||||
|
||||
## 🚨 Common Migration Issues
|
||||
|
||||
### Build Errors
|
||||
- **Node.js version**: Verify Node.js 22.x is installed and in PATH
|
||||
- **Package conflicts**: Clean NuGet cache if needed
|
||||
|
||||
### Runtime Errors
|
||||
- **Missing electron-builder.json**: Trigger rebuild or manual NuGet restore
|
||||
- **Process termination**: Use .NET-first startup mode for better cleanup
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[What's New?](What's-New.md)** - Complete overview of ElectronNET.Core features
|
||||
- **[Advanced Migration Topics](Advanced-Migration-Topics.md)** - Handle complex scenarios
|
||||
- **[Getting Started](../GettingStarted/ASP.Net.md)** - Learn about new development workflows
|
||||
|
||||
## 💡 Migration Benefits
|
||||
|
||||
✅ **Simplified Configuration** - No more CLI tools or JSON files
|
||||
✅ **Better Debugging** - Native Visual Studio experience with Hot Reload
|
||||
✅ **Modern Architecture** - .NET-first process lifecycle
|
||||
✅ **Cross-Platform Ready** - Build Linux apps from Windows
|
||||
✅ **Future-Proof** - Flexible Electron version selection
|
||||
|
||||
### Step 3: Update Startup Code
|
||||
|
||||
**Update UseElectron() calls** to include the new callback parameter. This callback executes at the right moment to initialize your Electron UI.
|
||||
|
||||
#### Modern ASP.NET Core (WebApplication)
|
||||
|
||||
```csharp
|
||||
using ElectronNET.API;
|
||||
using ElectronNET.API.Entities;
|
||||
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.UseElectron(args, ElectronAppReady);
|
||||
|
||||
var app = builder.Build();
|
||||
app.Run();
|
||||
}
|
||||
|
||||
public static async Task ElectronAppReady()
|
||||
{
|
||||
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
|
||||
new BrowserWindowOptions { Show = false });
|
||||
|
||||
browserWindow.OnReadyToShow += () => browserWindow.Show();
|
||||
}
|
||||
```
|
||||
|
||||
#### Traditional ASP.NET Core (IWebHostBuilder)
|
||||
|
||||
```csharp
|
||||
using ElectronNET.API;
|
||||
using ElectronNET.API.Entities;
|
||||
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
WebHost.CreateDefaultBuilder(args)
|
||||
.UseElectron(args, ElectronAppReady)
|
||||
.UseStartup<Startup>()
|
||||
.Build()
|
||||
.Run();
|
||||
}
|
||||
|
||||
public static async Task ElectronAppReady()
|
||||
{
|
||||
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
|
||||
new BrowserWindowOptions { Show = false });
|
||||
|
||||
browserWindow.OnReadyToShow += () => browserWindow.Show();
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Step 4: Update Development Tools
|
||||
|
||||
See [System Requirements](../GettingStarted/System-Requirements.md).
|
||||
|
||||
### Step 5: Update Debugging Setup
|
||||
|
||||
**Watch Feature Removal:**
|
||||
|
||||
The old 'watch' feature is no longer supported. Instead, use the new ASP.NET-first debugging with Hot Reload:
|
||||
|
||||
- **Old approach**: Manual process attachment and slow refresh
|
||||
- **New approach**: Native Visual Studio debugging with Hot Reload
|
||||
- **Benefits**: Faster development cycle, better debugging experience
|
||||
|
||||
**Update Launch Settings:**
|
||||
|
||||
Replace old watch configurations with new debugging profiles. See [Debugging](../GettingStarted/Debugging.md) for detailed setup instructions.
|
||||
|
||||
131
docs/Core/What's-New.md
Normal file
131
docs/Core/What's-New.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# What's New in ElectronNET.Core
|
||||
|
||||
## A Complete Transformation
|
||||
|
||||
ElectronNET.Core represents a fundamental modernization of Electron.NET, addressing years of accumulated pain points while preserving full API compatibility. This isn't just an update—it's a complete rethinking of how .NET developers build and debug cross-platform desktop applications with Electron.
|
||||
|
||||
## Complete Build System Overhaul
|
||||
|
||||
### From CLI Complexity to MSBuild Simplicity
|
||||
|
||||
The most visible change is the complete elimination of the CLI tool dependency. Where developers once needed to manage complex command-line operations and JSON configuration files, everything now flows through Visual Studio's native project system.
|
||||
|
||||
The old `electron.manifest.json` file is gone, replaced by clean MSBuild project properties that integrate seamlessly with Visual Studio's project designer. This provides not just a better development experience, but also eliminates entire categories of configuration errors that plagued earlier versions.
|
||||
|
||||
### Intelligent Package Structure
|
||||
|
||||
The new package architecture reflects a clearer separation of concerns:
|
||||
|
||||
- **ElectronNET.Core** - The main package containing build logic and project system integration
|
||||
- **ElectronNET.Core.Api** - Pure API definitions for Electron integration
|
||||
- **ElectronNET.Core.AspNet** - ASP.NET-specific runtime components
|
||||
|
||||
This modular approach allows projects to include only what they need while maintaining the flexibility to scale from simple console applications to complex web applications.
|
||||
More about the available nuget packages: [Package Description](../RelInfo/Package-Description.md).
|
||||
|
||||
## Beyond ASP.NET: Console Application Support
|
||||
|
||||
### A Shift in Accessibility
|
||||
|
||||
A major new opportunity in ElectronNET.Core is the removal of the ASP.NET requirement. Developers can now build Electron solutions using simple DotNet console applications, expanding the use cases and removing a major barrier to adoption for a number of use cases.
|
||||
|
||||
### Flexible Content Sources
|
||||
|
||||
Console applications with ElectronNET.Core support multiple content scenarios:
|
||||
|
||||
- **File System HTML/JS**: Serve static web content directly from the file system
|
||||
- **Remote Server Integration**: Connect to existing web servers or APIs
|
||||
- **Lightweight Architecture**: Avoid the overhead of ASP.NET when it's not needed
|
||||
- **Simplified Deployment**: Package and distribute with minimal dependencies
|
||||
|
||||
This capability transforms ElectronNET from a web-focused framework into a versatile platform that can integrate with any HTML/JS content source, making it accessible to a much broader range of development scenarios and team structures.
|
||||
|
||||
## Revolutionary Development Experience
|
||||
|
||||
### Debugging Reimagined
|
||||
|
||||
The debugging experience has been completely transformed. The new DotNet-first launch mode means developers can now debug their .NET code directly, with full access to familiar debugging tools and Hot Reload capabilities. No more attaching to processes or working around limited debugging scenarios — the development workflow now matches standard .NET development patterns.
|
||||
|
||||
### Cross-Platform Development Without Compromises
|
||||
|
||||
One of the most significant breakthroughs is the ability to build and debug Linux applications directly from Windows Visual Studio through WSL integration. Developers can now:
|
||||
|
||||
- Build Linux packages while working on Windows
|
||||
- Debug Linux application behavior in real-time
|
||||
- Test cross-platform functionality without context switching
|
||||
- Deploy to Linux targets with confidence
|
||||
|
||||
This capability eliminates the traditional barriers between Windows development environments and Linux deployment targets.
|
||||
|
||||
### Flexible Runtime Identifier Support
|
||||
|
||||
Runtime Identifier (RID) selection is now a first-class part of the project configuration, allowing developers to explicitly target specific platforms and architectures. The build system automatically structures output folders using standard .NET conventions (`bin\net8.0\win-x64`) instead of the ambiguous `bin\Desktop` layout, making multi-target builds clean and predictable.
|
||||
|
||||
## Modernized Architecture
|
||||
|
||||
### Process Lifecycle Revolution
|
||||
|
||||
The underlying process architecture has been fundamentally redesigned. Instead of Electron launching first and managing the .NET process, ElectronNET.Core puts .NET in control. The .NET application launches first and runs Electron as a child process, providing:
|
||||
|
||||
- Better process lifecycle management
|
||||
- More reliable application termination
|
||||
- Enhanced error handling and recovery
|
||||
- Cleaner separation between web and native concerns
|
||||
|
||||
This architecture supports eight different launch scenarios, covering every combination of packaged/unpackaged deployment, console/ASP.NET hosting, and dotnet-first/electron-first initialization. The Electron-first launch method is still available or course.
|
||||
For more details, see: [Startup Methods](../GettingStarted/Startup-Methods.md).
|
||||
|
||||
### Unpackaged Development Mode
|
||||
|
||||
The new unpackaged run-mode transforms development workflows by using regular .NET builds with unpackaged Electron configurations. This approach leverages .NET's incremental build capabilities for both managed and native code, dramatically reducing rebuild times and improving the development feedback loop.
|
||||
|
||||
## Enhanced Technical Foundation
|
||||
|
||||
### TypeScript Integration
|
||||
|
||||
TypeScript compilation is now fully integrated with ASP.NET tooling, providing consistent builds across different development environments. The updated toolchain uses modern TypeScript versions with ESLint configuration, eliminating the compatibility issues that previously affected custom ElectronHostHook implementations.
|
||||
|
||||
### API Enhancements
|
||||
|
||||
The improved splash screen handling with automatic path resolution eliminates common configuration pitfalls, while maintaining full backward compatibility with existing ElectronHostHook code.
|
||||
|
||||
### Performance Optimizations
|
||||
|
||||
Package sizes have been reduced by eliminating unnecessary dependencies, while build performance has improved through intelligent incremental compilation. The new architecture also minimizes startup times through optimized build and launch procedures.
|
||||
|
||||
## Seamless Migration Path
|
||||
|
||||
### Backward Compatibility Focus
|
||||
|
||||
Despite the extensive changes, ElectronNET.Core maintains complete API compatibility with existing applications. The modular package structure allows for incremental adoption, and existing ElectronHostHook implementations continue to work without modification.
|
||||
|
||||
### Clear Upgrade Journey
|
||||
|
||||
The migration path is designed to be straightforward:
|
||||
1. Update package references to the new structure
|
||||
2. Remove the old manifest file
|
||||
3. Configure project properties through Visual Studio
|
||||
4. Adopt new debugging workflows at your own pace
|
||||
|
||||
Further reading: [Migration Guide](Migration-Guide.md).
|
||||
|
||||
## Future Horizons
|
||||
|
||||
### Unlocked Possibilities
|
||||
|
||||
This modernization removes the technical debt that was limiting Electron.NET's evolution. The flexible Electron versioning, integrated build system, and cross-platform capabilities create a foundation for:
|
||||
|
||||
- More frequent updates and feature additions
|
||||
- Enhanced community contributions
|
||||
- Better tooling and IDE integration
|
||||
- Expanded platform support
|
||||
|
||||
### Version Independence
|
||||
|
||||
The removal of rigid Electron version coupling means developers can now choose the Electron version that best fits their needs, with build-time validation ensuring compatibility. This approach encourages community feedback and enables faster adoption of new Electron features.
|
||||
|
||||
## Conclusion
|
||||
|
||||
ElectronNET.Core represents more than just new features—it's a complete reimagining of what .NET + Electron development can be. By eliminating friction points, removing the ASP.NET requirement to support console applications, improving debugging experiences, and enabling true cross-platform development, it transforms Electron.NET from a challenging framework to work with into a modern, efficient platform for building cross-platform desktop applications.
|
||||
|
||||
The changes address the core issues that were driving developers away from Electron.NET while opening new possibilities for the future. This foundation will enable more rapid innovation and better support for the growing demands of cross-platform .NET development.
|
||||
25
docs/Docs.shproj
Normal file
25
docs/Docs.shproj
Normal file
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>06caadc7-de5b-47b4-ab2a-e9501459a2d1</ProjectGuid>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Remove="About\Azure\**" />
|
||||
<Compile Remove="About\BuildBot\**" />
|
||||
<Compile Remove="images\AzureDevOps\**" />
|
||||
<Compile Remove="images\visualization\**" />
|
||||
<Compile Remove="schema_printing\**" />
|
||||
<EmbeddedResource Remove="About\Azure\**" />
|
||||
<EmbeddedResource Remove="About\BuildBot\**" />
|
||||
<EmbeddedResource Remove="images\AzureDevOps\**" />
|
||||
<EmbeddedResource Remove="images\visualization\**" />
|
||||
<EmbeddedResource Remove="schema_printing\**" />
|
||||
<None Remove="About\Azure\**" />
|
||||
<None Remove="About\BuildBot\**" />
|
||||
<None Remove="images\AzureDevOps\**" />
|
||||
<None Remove="images\visualization\**" />
|
||||
<None Remove="schema_printing\**" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<Import Project=".docproj\DocProj.props" />
|
||||
<Import Project=".docproj\DocProj.targets" />
|
||||
</Project>
|
||||
129
docs/GettingStarted/ASP.Net.md
Normal file
129
docs/GettingStarted/ASP.Net.md
Normal file
@@ -0,0 +1,129 @@
|
||||
|
||||
# ASP.NET Core Setup
|
||||
|
||||
ASP.NET Core remains the recommended approach for complex web applications with ElectronNET.Core, providing all the benefits of the ASP.NET ecosystem along with enhanced Electron integration.
|
||||
|
||||
## 🛠 System Requirements
|
||||
|
||||
See [System Requirements](../GettingStarted/System-Requirements.md).
|
||||
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### 1. Create ASP.NET Core Project
|
||||
|
||||
#### Visual Studio
|
||||
|
||||
Create a new ASP.NET Core Web App in Visual Studio by selecting **New Project** and choosing one of the ASP.NET Core project templates.
|
||||
|
||||
#### From the command line
|
||||
|
||||
```bash
|
||||
dotnet new webapp -n MyElectronWebApp
|
||||
cd MyElectronWebApp
|
||||
```
|
||||
|
||||
### 2. Install NuGet Packages
|
||||
|
||||
#### Visual Studio
|
||||
|
||||
Right-click the solution and select **Manage Nuget Packages**.
|
||||
Finr and install `ElectronNET.Core` as well as `ElectronNET.Core.AspNet`.
|
||||
|
||||
#### From the command line
|
||||
|
||||
```powershell
|
||||
dotnet add package ElectronNET.Core
|
||||
dotnet add package ElectronNET.Core.AspNet
|
||||
```
|
||||
|
||||
> [!Note]
|
||||
> The API package is automatically included as a dependency of `ElectronNET.Core`.
|
||||
|
||||
|
||||
### 3. Configure Program.cs
|
||||
|
||||
Update your `Program.cs` to enable Electron.NET:
|
||||
|
||||
```csharp
|
||||
using ElectronNET.API;
|
||||
using ElectronNET.API.Entities;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddRazorPages();
|
||||
|
||||
// Add this line to enable Electron.NET:
|
||||
builder.UseElectron(args, ElectronAppReady);
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Error");
|
||||
}
|
||||
app.UseStaticFiles();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapRazorPages();
|
||||
|
||||
app.Run();
|
||||
}
|
||||
|
||||
public static async Task ElectronAppReady()
|
||||
{
|
||||
var browserWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions { Show = false });
|
||||
|
||||
browserWindow.OnReadyToShow += () => browserWindow.Show();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### ASP.NET Port
|
||||
|
||||
If you want to launch a specific URL, you can retrieve the actual ASP.NET port from the new `ElectronNetRuntime` static class, for example:
|
||||
|
||||
```csharp
|
||||
await browserWindow.WebContents
|
||||
.LoadURLAsync($"http://localhost:{ElectronNetRuntime.AspNetWebPort}/mypage.html");
|
||||
```
|
||||
|
||||
### 4. Alternative: IWebHostBuilder Setup
|
||||
|
||||
For projects using the traditional `Startup.cs` pattern, please see "Traditional ASP.NET Core" in the [Migration Guide](../Core/Migration-Guide.md).
|
||||
|
||||
|
||||
### 5. Dependency Injection
|
||||
|
||||
ElectronNET.API can be added to your DI container within the `Startup` class. All of the modules available in Electron will be added as Singletons.
|
||||
|
||||
```csharp
|
||||
using ElectronNET.API;
|
||||
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddElectron();
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Debugging](../Using/Debugging.md)** - Learn about ASP.NET debugging features
|
||||
- **[Package Building](../Using/Package-Building.md)** - Create distributable packages
|
||||
- **[Startup Methods](../Using/Startup-Methods.md)** - Understanding launch scenarios
|
||||
|
||||
## 💡 Benefits of ASP.NET + Electron
|
||||
|
||||
✅ **Full Web Stack** - Use MVC, Razor Pages, Blazor, and all ASP.NET features
|
||||
✅ **Hot Reload** - Edit ASP.NET code and see changes instantly
|
||||
✅ **Rich Ecosystem** - Access to thousands of ASP.NET packages
|
||||
✅ **Modern Development** - Latest C# features and ASP.NET patterns
|
||||
✅ **Scalable Architecture** - Build complex, maintainable applications
|
||||
166
docs/GettingStarted/Console-App.md
Normal file
166
docs/GettingStarted/Console-App.md
Normal file
@@ -0,0 +1,166 @@
|
||||
|
||||
|
||||
# Console Application Setup
|
||||
|
||||
A major benefit in ElectronNET.Core is the ability to build Electron applications using simple console applications instead of requiring ASP.NET Core. This removes a significant barrier and enables many more use cases.
|
||||
|
||||
## 🎯 What You Can Build
|
||||
|
||||
Console applications with ElectronNET.Core support multiple content scenarios:
|
||||
|
||||
- **File System HTML/JS** - Serve static web content directly from the file system
|
||||
- **Remote Server Integration** - Connect to existing web servers or APIs
|
||||
- **Lightweight Architecture** - Avoid ASP.NET overhead when not needed
|
||||
- **Simplified Deployment** - Package and distribute with minimal dependencies
|
||||
|
||||
## 📋 Prerequisites
|
||||
|
||||
See [System Requirements](../GettingStarted/System-Requirements.md).
|
||||
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### 1. Create Console Application
|
||||
|
||||
#### Visual Studio
|
||||
|
||||
Create a new console application in Visual Studio by selecting **New Project** and choosing one of the project templates for console apps.
|
||||
|
||||
#### From the command line
|
||||
|
||||
```bash
|
||||
dotnet new console -n MyElectronApp
|
||||
cd MyElectronApp
|
||||
```
|
||||
|
||||
### 2. Install NuGet Packages
|
||||
|
||||
```powershell
|
||||
dotnet add package ElectronNET.Core
|
||||
```
|
||||
|
||||
> [!Note]
|
||||
> The API package is automatically included as a dependency of `ElectronNET.Core`.
|
||||
|
||||
### 3. Configure Project File
|
||||
|
||||
Add the Electron.NET configuration to your `.csproj` file:
|
||||
|
||||
```xml
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ElectronNET.Core" Version="0.4.1" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> Specifying `OutputType` property is crucial in order to get the ability of WSL debugging. Especially it is not included in ASP.NET projects.
|
||||
> When you migrate from ASP.NET to a console application, be sure to add this to the project file.
|
||||
|
||||
|
||||
### 4. Implement Basic Structure
|
||||
|
||||
Here's a complete console application example:
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ElectronNET.API.Entities;
|
||||
|
||||
namespace MyElectronApp
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
var runtimeController = ElectronNetRuntime.RuntimeController;
|
||||
|
||||
try
|
||||
{
|
||||
// Start Electron runtime
|
||||
await runtimeController.Start();
|
||||
await runtimeController.WaitReadyTask;
|
||||
|
||||
// Initialize your Electron app
|
||||
await InitializeApp();
|
||||
|
||||
// Wait for shutdown
|
||||
await runtimeController.WaitStoppedTask.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Error: {ex.Message}");
|
||||
await runtimeController.Stop().ConfigureAwait(false);
|
||||
await runtimeController.WaitStoppedTask.WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task InitializeApp()
|
||||
{
|
||||
// Create main window
|
||||
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
|
||||
new BrowserWindowOptions
|
||||
{
|
||||
Show = false,
|
||||
WebPreferences = new WebPreferences
|
||||
{
|
||||
// Add these two when using file:// URLs
|
||||
WebSecurity = false,
|
||||
AllowRunningInsecureContent = true,
|
||||
|
||||
NodeIntegration = false,
|
||||
ContextIsolation = true
|
||||
}
|
||||
});
|
||||
|
||||
// Load your content (file system, remote URL, etc.)
|
||||
await browserWindow.WebContents.LoadURLAsync("https://example.com");
|
||||
|
||||
// Show window when ready
|
||||
browserWindow.OnReadyToShow += () => browserWindow.Show();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 📁 Content Sources
|
||||
|
||||
### File System Content
|
||||
|
||||
Serve HTML/JS files from your project:
|
||||
|
||||
```csharp
|
||||
// In your project root, create wwwroot/index.html
|
||||
var fileInfo = new FileInfo(Environment.ProcessPath);
|
||||
var exeFolder = fileInfo.DirectoryName;
|
||||
var htmlPath = Path.Combine(exeFolder, "wwwroot/index.html");
|
||||
var url = new Uri(htmlPath, UriKind.Absolute);
|
||||
await browserWindow.WebContents.LoadFileAsync(url.ToString());
|
||||
```
|
||||
|
||||
### Remote Content
|
||||
|
||||
Load content from any web server:
|
||||
|
||||
```csharp
|
||||
await browserWindow.WebContents.LoadURLAsync("https://your-server.com/app");
|
||||
```
|
||||
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Debugging](../Using/Debugging.md)** - Learn about debugging console applications
|
||||
- **[Package Building](../Using/Package-Building.md)** - Create distributable packages
|
||||
- **[Migration Guide](../Core/Migration-Guide.md)** - Moving from ASP.NET projects
|
||||
|
||||
## 💡 Benefits of Console Apps
|
||||
|
||||
✅ **Simpler Architecture** - No ASP.NET complexity when not needed
|
||||
✅ **Flexible Content** - Use any HTML/JS source
|
||||
✅ **Faster Development** - Less overhead for simple applications
|
||||
✅ **Easy Deployment** - Minimal dependencies
|
||||
✅ **Better Performance** - Lighter weight than full web applications
|
||||
53
docs/GettingStarted/System-Requirements.md
Normal file
53
docs/GettingStarted/System-Requirements.md
Normal file
@@ -0,0 +1,53 @@
|
||||
|
||||
## 🛠 System Requirements
|
||||
|
||||
### Required Software
|
||||
|
||||
- **.NET 8.0** or later
|
||||
- **Node.js 22.x** or later (see below)
|
||||
- **Visual Studio 2022** (recommended) or other .NET IDE
|
||||
|
||||
### Supported Operating Systems
|
||||
|
||||
- **Windows 10/11** (x64, ARM64)
|
||||
- **macOS 11+** (Intel, Apple Silicon)
|
||||
- **Linux** (most distributions with glibc 2.31+)
|
||||
|
||||
> [!Note]
|
||||
> For Linux development on Windows, install [WSL2](https://docs.microsoft.com/windows/wsl/install) to build and debug Linux packages.
|
||||
> Do not forget to install NodeJS 22.x (LTS) on WSL.
|
||||
> Visual Studio will automatically install .NET when debugging on WSL. In all other cases you will need to install a matching .NET SDK on WSL as well.
|
||||
|
||||
|
||||
### NodeJS Installation
|
||||
|
||||
|
||||
ElectronNET.Core requires Node.js 22.x. Update your installation:
|
||||
|
||||
**Windows:**
|
||||
|
||||
1. Download from [nodejs.org](https://nodejs.org)
|
||||
2. Run the installer
|
||||
3. Verify: `node --version` should show v22.x.x
|
||||
|
||||
**Linux:**
|
||||
|
||||
```bash
|
||||
# Using Node Version Manager (recommended)
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
|
||||
source ~/.bashrc
|
||||
nvm install 22
|
||||
nvm use 22
|
||||
|
||||
# Or using package manager
|
||||
sudo apt update
|
||||
sudo apt install nodejs=22.*
|
||||
```
|
||||
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Debugging](../Using/Debugging.md)** - Learn about ASP.NET debugging features
|
||||
- **[Package Building](../Using/Package-Building.md)** - Create distributable packages
|
||||
- **[Startup Methods](../Using/Startup-Methods.md)** - Understanding launch scenarios
|
||||
|
||||
59
docs/Home.md
Normal file
59
docs/Home.md
Normal file
@@ -0,0 +1,59 @@
|
||||
|
||||
|
||||
# Electron.NET Wiki Home
|
||||
|
||||
Welcome to the **Electron.NET Core** documentation! This wiki covers everything you need to know about building cross-platform desktop applications with ASP.NET Core and Electron.NET.
|
||||
|
||||
## 🚀 What is Electron.NET Core?
|
||||
|
||||
Electron.NET Core is a complete modernization of Electron.NET that eliminates the CLI tool dependency and integrates deeply with Visual Studio's MSBuild system. It transforms the development experience by providing:
|
||||
|
||||
- **Native Visual Studio Integration** - No more CLI tools or JSON configuration files
|
||||
- **Console Application Support** - Build Electron apps with simple console applications, not just ASP.NET
|
||||
- **Cross-Platform Development** - Build and debug Linux applications from Windows via WSL
|
||||
- **Enhanced Debugging** - ASP.NET-first debugging with Hot Reload support
|
||||
- **Flexible Architecture** - Choose any Electron version and target multiple platforms
|
||||
|
||||
## 📚 Documentation Sections
|
||||
|
||||
### [Core Documentation](Core/What's-New.md)
|
||||
- **[What's New?](Core/What's-New.md)** - Complete overview of ElectronNET.Core features and improvements
|
||||
- **[Migration Guide](Core/Migration-Guide.md)** - Step-by-step migration from previous versions
|
||||
- **[Advanced Migration Topics](Core/Advanced-Migration-Topics.md)** - Technical details for complex scenarios
|
||||
|
||||
### [Getting Started](GettingStarted/ASP.Net.md)
|
||||
- **[ASP.NET Applications](GettingStarted/ASP.Net.md)** - Build Electron apps with ASP.NET Core
|
||||
- **[Console Applications](GettingStarted/Console-App.md)** - Use console apps for file system or remote content
|
||||
- **[Startup Methods](GettingStarted/Startup-Methods.md)** - Understanding different launch scenarios
|
||||
- **[Debugging](GettingStarted/Debugging.md)** - Debug Electron apps effectively in Visual Studio
|
||||
- **[Package Building](GettingStarted/Package-Building.md)** - Create distributable packages
|
||||
|
||||
### [Release Information](RelInfo/Package-Description.md)
|
||||
- **[Package Description](RelInfo/Package-Description.md)** - Understanding the three NuGet packages
|
||||
- **[Changelog](../Changelog.md)** - Complete list of changes and improvements
|
||||
|
||||
## 🛠 System Requirements
|
||||
|
||||
See [System Requirements](GettingStarted/System-Requirements.md).
|
||||
|
||||
## 💡 Key Benefits
|
||||
|
||||
✅ **No CLI Tools Required** - Everything works through Visual Studio
|
||||
✅ **Console App Support** - Use any HTML/JS source, not just ASP.NET
|
||||
✅ **True Cross-Platform** - Build Linux apps from Windows
|
||||
✅ **Modern Debugging** - Hot Reload and ASP.NET-first debugging
|
||||
✅ **Flexible Packaging** - Choose any Electron version
|
||||
✅ **MSBuild Integration** - Leverages .NET's build system
|
||||
|
||||
## 🚦 Getting Started
|
||||
|
||||
New to ElectronNET.Core? Start here:
|
||||
|
||||
1. **[ASP.NET Setup](GettingStarted/ASP.Net.md)** - Traditional web application approach
|
||||
2. **[Console App Setup](GettingStarted/Console-App.md)** - Lightweight console application approach
|
||||
3. **[Migration Guide](Core/Migration-Guide.md)** - Moving from previous versions
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Found an issue or want to improve the documentation? Contributions are welcome!
|
||||
The wiki is auto-generated from the `/docs` folder in the [GitHub repository](https://github.com/ElectronNET/Electron.NET).
|
||||
116
docs/RelInfo/Package-Description.md
Normal file
116
docs/RelInfo/Package-Description.md
Normal file
@@ -0,0 +1,116 @@
|
||||
# Package Description
|
||||
|
||||
ElectronNET.Core consists of three specialized NuGet packages designed for different development scenarios and project architectures.
|
||||
|
||||
## 📦 Package Overview
|
||||
|
||||
### ElectronNET.Core (Main Package)
|
||||
**Primary package for Electron.NET applications**
|
||||
|
||||
- **Build system integration** - MSBuild targets and tasks for Electron
|
||||
- **Project system extensions** - Visual Studio designer integration
|
||||
- **Runtime orchestration** - Process lifecycle management
|
||||
- **Automatic configuration** - Generates electron-builder.json and package.json
|
||||
- **Includes ElectronNET.Core.Api** as a dependency
|
||||
|
||||
**When to use:**
|
||||
- Main application projects (startup projects)
|
||||
- Projects that need full Electron.NET functionality
|
||||
- Applications requiring build-time Electron configuration
|
||||
|
||||
### ElectronNET.Core.Api (API Package)
|
||||
**Pure API definitions without build integration**
|
||||
|
||||
- **Electron API wrappers** - Complete Electron API surface
|
||||
- **Type definitions** - Full TypeScript-style IntelliSense
|
||||
- **No build dependencies** - Clean API-only package
|
||||
- **Multi-platform support** - Windows, macOS, Linux
|
||||
|
||||
**When to use:**
|
||||
- Class library projects that interact with Electron APIs
|
||||
- Projects that only need API access without build integration
|
||||
- Multi-project solutions where only the startup project needs build integration
|
||||
|
||||
### ElectronNET.Core.AspNet (ASP.NET Integration)
|
||||
**ASP.NET-specific runtime components**
|
||||
|
||||
- **ASP.NET middleware** - UseElectron() extension methods
|
||||
- **WebHost integration** - Seamless ASP.NET + Electron hosting
|
||||
- **Hot Reload support** - Enhanced debugging experience
|
||||
- **Web-specific optimizations** - ASP.NET tailored performance
|
||||
|
||||
**When to use:**
|
||||
- ASP.NET Core projects building Electron applications
|
||||
- Applications requiring web server functionality
|
||||
- Projects using MVC, Razor Pages, or Blazor
|
||||
|
||||
## 🏗 Architecture Benefits
|
||||
|
||||
### Separation of Concerns
|
||||
- **Build logic separate from API** - Clean dependency management
|
||||
- **Optional ASP.NET integration** - Use only what you need
|
||||
- **Multi-project friendly** - Share APIs across projects without build conflicts
|
||||
|
||||
### Project Scenarios
|
||||
|
||||
**Single Project (ASP.NET):**
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ElectronNET.Core" Version="1.0.0" />
|
||||
<PackageReference Include="ElectronNET.Core.AspNet" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
**Single Project (Console):**
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ElectronNET.Core" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
**Multi-Project Solution (ASP.NET):**
|
||||
```xml
|
||||
<!-- Startup project -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ElectronNET.Core" Version="1.0.0" />
|
||||
<PackageReference Include="ElectronNET.Core.AspNet" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Class library projects -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ElectronNET.Core.Api" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
**Multi-Project Solution (Console):**
|
||||
```xml
|
||||
<!-- Startup project -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ElectronNET.Core" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Class library projects -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ElectronNET.Core.Api" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
## 🔗 Dependency Chain
|
||||
|
||||
```
|
||||
ElectronNET.Core.AspNet → ElectronNET.Core.Api
|
||||
|
||||
ElectronNET.Core → ElectronNET.Core.Api
|
||||
```
|
||||
|
||||
- **ElectronNET.Core.AspNet** depends on ElectronNET.Core.Api
|
||||
- **ElectronNET.Core** depends on ElectronNET.Core.Api
|
||||
- **ElectronNET.Core.Api** has no dependencies
|
||||
|
||||
## 💡 Recommendations
|
||||
|
||||
✅ **Start with ElectronNET.Core** for new projects
|
||||
✅ **Add ElectronNET.Core.AspNet** only for ASP.NET applications
|
||||
✅ **Use ElectronNET.Core.Api** for class libraries and API-only scenarios
|
||||
✅ **Multi-project solutions** benefit from the modular architecture
|
||||
|
||||
94
docs/Using/Configuration.md
Normal file
94
docs/Using/Configuration.md
Normal file
@@ -0,0 +1,94 @@
|
||||
|
||||
# Project Configuration
|
||||
|
||||
|
||||
## 🔧 Visual Studio App Designer
|
||||
|
||||
Electron.NET provides close integration via the Visual Studio Project System and MSBuild. After adding the ElectronNET.Core package, you will see this in the project configuration page after double-click on the 'Properties' folder or right-click on the project and choosing 'Properties':
|
||||
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
## Project File Settings
|
||||
|
||||
The same settings can be configured manually by editing the MSBuild properties in your `.csproj` file.
|
||||
These are the current default values when you don't make any changes:
|
||||
|
||||
```xml
|
||||
<PropertyGroup Label="ElectronNetCommon">
|
||||
<ElectronVersion>30.4.0</ElectronVersion>
|
||||
<ElectronBuilderVersion>26.0</ElectronBuilderVersion>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<ElectronSingleInstance>true</ElectronSingleInstance>
|
||||
<ElectronSplashScreen></ElectronSplashScreen>
|
||||
<ElectronIcon></ElectronIcon>
|
||||
<ElectronPackageId>$(MSBuildProjectName.Replace(".", "-").ToLower())</ElectronPackageId>
|
||||
<ElectronBuilderJson>electron-builder.json</ElectronBuilderJson>
|
||||
<Title>$(MSBuildProjectName)</Title>
|
||||
</PropertyGroup>
|
||||
```
|
||||
|
||||
### Relation to package.json
|
||||
|
||||
ElectronNET.Core does not work with an `electron-manifest.json` file anymore.
|
||||
Since electron builder still expects a `package.json` file to exist, ElectronNET.Core is creating this under the hood automatically during build. For reference, here's the package.json template file that is being used, so you can see how the MSBuild properties are being mapped to `package.json` data:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "$(ElectronPackageId)",
|
||||
"productName": "$(ElectronTitle)",
|
||||
"build": {
|
||||
"appId": "$(ElectronPackageId)",
|
||||
"linux": {
|
||||
"desktop": {
|
||||
"entry": { "Name": "$(Title)" }
|
||||
},
|
||||
"executableName": "$(ElectronPackageId)"
|
||||
},
|
||||
"deb": {
|
||||
"desktop": {
|
||||
"entry": { "Name": "$(Title)" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "$(Description)",
|
||||
"version": "$(Version)",
|
||||
"main": "main.js",
|
||||
"author": {
|
||||
"name": "$(Company)"
|
||||
},
|
||||
"license": "$(License)",
|
||||
"executable": "$(TargetName)",
|
||||
"singleInstance": "$(ElectronSingleInstance)",
|
||||
"homepage": "$(ProjectUrl)",
|
||||
"splashscreen": {
|
||||
"imageFile": "$(ElectronSplashScreen)"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Node.js Integration
|
||||
|
||||
Electron.NET requires Node.js integration to be enabled for IPC to function. If you are not using the IPC functionality you can disable Node.js integration like so:
|
||||
|
||||
```csharp
|
||||
WebPreferences wp = new WebPreferences();
|
||||
wp.NodeIntegration = false;
|
||||
BrowserWindowOptions browserWindowOptions = new BrowserWindowOptions
|
||||
{
|
||||
WebPreferences = wp
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Startup Methods](Startup-Methods.md)** - Understanding launch scenarios
|
||||
- **[Debugging](../Using/Debugging.md)** - Learn about ASP.NET debugging features
|
||||
- **[Package Building](Package-Building.md)** - Create distributable packages
|
||||
|
||||
74
docs/Using/Custom_main.md
Normal file
74
docs/Using/Custom_main.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# Using custom_main.js
|
||||
|
||||
This guide explains how to include and use a `custom_main.js` file in your Electron.NET application for advanced Electron/Node.js customization.
|
||||
|
||||
## Why use custom_main.js?
|
||||
|
||||
- Register custom protocol handlers (e.g., `myapp://`) — protocols must be registered before the app is fully initialized
|
||||
- Integrate Node.js modules (e.g., telemetry, OS APIs)
|
||||
- Control startup logic (abort, environment checks)
|
||||
- Set up IPC messaging or preload scripts
|
||||
|
||||
## Step-by-Step Process
|
||||
|
||||
### 1. Create the custom_main.js file
|
||||
|
||||
Place your custom logic in `electron/custom_main.js`:
|
||||
|
||||
```javascript
|
||||
module.exports.onStartup = function(host) {
|
||||
// Example: Register a global shortcut for opening dev tools
|
||||
const { app, globalShortcut, BrowserWindow } = require('electron');
|
||||
app.on('ready', () => {
|
||||
const ret = globalShortcut.register('Control+Shift+I', () => {
|
||||
BrowserWindow.getAllWindows().forEach(win => win.webContents.openDevTools());
|
||||
console.log('Ctrl+Shift+I is pressed: DevTools opened!');
|
||||
});
|
||||
});
|
||||
app.on('will-quit', () => {
|
||||
globalShortcut.unregisterAll();
|
||||
});
|
||||
return true;
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Configure your .csproj to copy custom_main.js to output
|
||||
|
||||
Add this to your `.csproj` file:
|
||||
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<None Update="electron\custom_main.js">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<TargetPath>.electron\custom_main.js</TargetPath>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
### 3. Build and run your app
|
||||
|
||||
Use the standard build/run commands:
|
||||
|
||||
```powershell
|
||||
dotnet build
|
||||
dotnet run
|
||||
```
|
||||
|
||||
Electron.NET will automatically load and execute your `custom_main.js` before initializing the .NET backend.
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
Use environment variables to control features:
|
||||
|
||||
```javascript
|
||||
const env = process.env.ASPNETCORE_ENVIRONMENT || 'Production';
|
||||
if (env === 'Development') { /* enable dev features */ }
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- `custom_main.js` must use CommonJS syntax (`module.exports.onStartup = ...`).
|
||||
- Place the file in your source directory and copy it to `.electron` using `.csproj`.
|
||||
- Electron.NET will abort startup if `onStartup` returns `false`.
|
||||
|
||||
### Complete example is available here [ElectronNetSampleApp](https://github.com/niteshsinghal85/ElectronNetSampleApp)
|
||||
242
docs/Using/Debugging.md
Normal file
242
docs/Using/Debugging.md
Normal file
@@ -0,0 +1,242 @@
|
||||
# Debugging
|
||||
|
||||
ElectronNET.Core transforms the debugging experience by providing native Visual Studio integration with multiple debugging modes. No more complex setup or manual process attachment—debugging now works as expected for .NET developers.
|
||||
|
||||
## 🎯 Debugging Modes
|
||||
|
||||
ElectronNET.Core supports three main debugging approaches, all configured through Visual Studio's launch profiles:
|
||||
|
||||
### 1. ASP.NET-First Debugging (Recommended)
|
||||
|
||||
Debug your .NET code directly with full Hot Reload support:
|
||||
|
||||
```json
|
||||
{
|
||||
"profiles": {
|
||||
"ASP.Net (unpackaged)": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "http://localhost:8001/"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- ✅ Full C# debugging with breakpoints
|
||||
- ✅ Hot Reload for ASP.NET code
|
||||
- ✅ Edit-and-continue functionality
|
||||
- ✅ Native Visual Studio debugging experience
|
||||
|
||||
### 2. Electron-First Debugging
|
||||
|
||||
Debug the Electron process when you need to inspect native Electron APIs:
|
||||
|
||||
```json
|
||||
{
|
||||
"profiles": {
|
||||
"Electron (unpackaged)": {
|
||||
"commandName": "Executable",
|
||||
"executablePath": "node",
|
||||
"commandLineArgs": "node_modules/electron/cli.js main.js -unpackedelectron",
|
||||
"workingDirectory": "$(TargetDir).electron",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- ✅ Debug Electron main process
|
||||
- ✅ Inspect native Electron APIs
|
||||
- ✅ Node.js debugging capabilities
|
||||
|
||||
### 3. Cross-Platform WSL Debugging
|
||||
|
||||
Debug Linux builds directly from Windows Visual Studio:
|
||||
|
||||
```json
|
||||
{
|
||||
"profiles": {
|
||||
"WSL": {
|
||||
"commandName": "WSL2",
|
||||
"launchUrl": "http://localhost:8001/",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"ASPNETCORE_URLS": "http://localhost:8001/"
|
||||
},
|
||||
"distributionName": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- ✅ Debug Linux applications from Windows
|
||||
- ✅ Test Linux-specific behavior
|
||||
- ✅ Validate cross-platform compatibility
|
||||
|
||||
## 🔧 Setup Instructions
|
||||
|
||||
### 1. Configure Launch Settings
|
||||
|
||||
Add the debugging profiles to `Properties/launchSettings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"profiles": {
|
||||
"ASP.Net (unpackaged)": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "http://localhost:8001/"
|
||||
},
|
||||
"Electron (unpackaged)": {
|
||||
"commandName": "Executable",
|
||||
"executablePath": "node",
|
||||
"commandLineArgs": "node_modules/electron/cli.js main.js -unpackedelectron",
|
||||
"workingDirectory": "$(TargetDir).electron",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"WSL": {
|
||||
"commandName": "WSL2",
|
||||
"launchUrl": "http://localhost:8001/",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"ASPNETCORE_URLS": "http://localhost:8001/"
|
||||
},
|
||||
"distributionName": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Switch Runtime Identifiers
|
||||
|
||||
When switching between Windows and WSL debugging:
|
||||
|
||||
1. **Right-click your project** in Solution Explorer
|
||||
2. Select **Properties**
|
||||
3. Adjust the Runtime Identifier
|
||||
|
||||
|
||||
Without Visual Studio:
|
||||
|
||||
1. **Edit** the .csproj file
|
||||
2. **Update the RuntimeIdentifier**:
|
||||
|
||||
```xml
|
||||
<!-- For Windows debugging -->
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
|
||||
<!-- For WSL/Linux debugging -->
|
||||
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
|
||||
```
|
||||
|
||||
### 3. Enable WSL Debugging
|
||||
|
||||
For WSL debugging, ensure:
|
||||
|
||||
- **WSL2 is installed** and configured
|
||||
- **Linux distribution** is set in the launch profile
|
||||
- **Project targets Linux RID** for WSL debugging
|
||||
|
||||
## 🚀 Debugging Workflow
|
||||
|
||||
### ASP.NET-First Debugging (Default)
|
||||
|
||||
1. **Select "ASP.Net (unpackaged)"** profile in Visual Studio
|
||||
2. **Press F5** to start debugging
|
||||
3. **Set breakpoints** in your C# code
|
||||
4. **Use Hot Reload** to edit ASP.NET code during runtime
|
||||
5. **Stop debugging** when finished
|
||||
|
||||
### Electron Process Debugging
|
||||
|
||||
1. **Select "Electron (unpackaged)"** profile
|
||||
2. **Press F5** to start debugging
|
||||
3. **Attach to Electron process** if needed
|
||||
4. **Debug Node.js and Electron APIs**
|
||||
|
||||
### Cross-Platform Debugging
|
||||
|
||||
1. **Set RuntimeIdentifier** to `linux-x64`
|
||||
2. **Select "WSL"** profile
|
||||
3. **Press F5** to debug in WSL
|
||||
4. **Test Linux-specific behavior**
|
||||
|
||||
## 🔍 Debugging Tips
|
||||
|
||||
### Hot Reload
|
||||
|
||||
- **Works with ASP.NET-first debugging**
|
||||
- **Edit Razor views, controllers, and pages**
|
||||
- **See changes instantly** without restart
|
||||
- **Preserves application state**
|
||||
|
||||
### Breakpoint Debugging
|
||||
|
||||
```csharp
|
||||
// Set breakpoints here
|
||||
public async Task<IActionResult> Index()
|
||||
{
|
||||
var data = await GetData(); // ← Breakpoint
|
||||
return View(data);
|
||||
}
|
||||
```
|
||||
|
||||
### Process Management
|
||||
|
||||
- **ASP.NET-first mode** automatically manages Electron process lifecycle
|
||||
- **Proper cleanup** on debugging session end
|
||||
- **No manual process killing** required
|
||||
|
||||
## 🛠 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**"Electron process not found"**
|
||||
- Ensure Node.js 22.x is installed
|
||||
- Check that packages are restored (`dotnet restore`)
|
||||
- Verify RuntimeIdentifier matches your target platform
|
||||
|
||||
**"WSL debugging fails"**
|
||||
- Install and configure WSL2
|
||||
- Ensure Linux distribution is properly set up
|
||||
- Check that project targets correct RID
|
||||
|
||||
**"Hot Reload not working"**
|
||||
- Use ASP.NET-first debugging profile
|
||||
- Ensure ASPNETCORE_ENVIRONMENT=Development
|
||||
- Check for compilation errors
|
||||
|
||||
## 🎨 Visual Debugging
|
||||
|
||||
*Placeholder for image showing Visual Studio debugging interface with Electron.NET*
|
||||
|
||||
The debugging interface provides familiar Visual Studio tools:
|
||||
- **Locals and Watch windows** for variable inspection
|
||||
- **Call Stack** for method call tracing
|
||||
- **Immediate Window** for runtime evaluation
|
||||
- **Hot Reload** indicator for edit-and-continue
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Startup Methods](Startup-Methods.md)** - Understanding different launch scenarios
|
||||
- **[Package Building](Package-Building.md)** - Debug packaged applications
|
||||
- **[Migration Guide](../Core/Migration-Guide.md)** - Moving from old debugging workflows
|
||||
|
||||
## 💡 Benefits
|
||||
|
||||
✅ **Native Visual Studio Experience** - No complex setup or manual attachment
|
||||
✅ **Hot Reload Support** - Edit ASP.NET code during debugging
|
||||
✅ **Cross-Platform Debugging** - Debug Linux apps from Windows
|
||||
✅ **Multiple Debugging Modes** - Choose the right approach for your needs
|
||||
✅ **Process Lifecycle Management** - Automatic cleanup and proper termination
|
||||
237
docs/Using/Package-Building.md
Normal file
237
docs/Using/Package-Building.md
Normal file
@@ -0,0 +1,237 @@
|
||||
# Package Building
|
||||
|
||||
ElectronNET.Core integrates with Visual Studio's publishing system to create distributable Electron packages using electron-builder. The process leverages .NET's build system while automatically generating the necessary Electron configuration files.
|
||||
|
||||
## 🎯 Publishing Overview
|
||||
|
||||
The publishing process differs slightly between ASP.NET and console applications:
|
||||
|
||||
- **ASP.NET Apps** - Use folder publishing with SelfContained=true
|
||||
- **Console Apps** - Use folder publishing with SelfContained=false
|
||||
|
||||
|
||||
## 🚀 Publishing Process
|
||||
|
||||
### Step 1: Create Publish Profiles
|
||||
|
||||
Add publish profiles to `Properties/PublishProfiles/`:
|
||||
|
||||
#### ASP.NET Application Profile (Windows)
|
||||
|
||||
**win-x64.pubxml:**
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Any CPU</Platform>
|
||||
<DeleteExistingFiles>true</DeleteExistingFiles>
|
||||
<PublishProvider>FileSystem</PublishProvider>
|
||||
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
|
||||
<WebPublishMethod>FileSystem</WebPublishMethod>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
|
||||
<SelfContained>true</SelfContained>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
#### ASP.NET Application Profile (Linux)
|
||||
|
||||
**linux-x64.pubxml:**
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Any CPU</Platform>
|
||||
<DeleteExistingFiles>true</DeleteExistingFiles>
|
||||
<PublishProvider>FileSystem</PublishProvider>
|
||||
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
|
||||
<WebPublishMethod>FileSystem</WebPublishMethod>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
|
||||
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
|
||||
<SelfContained>true</SelfContained>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
#### ASP.NET Application Profile (macOS Apple Silicon ARM64)
|
||||
|
||||
**osx-arm64.pubxml:**
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Any CPU</Platform>
|
||||
<DeleteExistingFiles>true</DeleteExistingFiles>
|
||||
<PublishProvider>FileSystem</PublishProvider>
|
||||
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
|
||||
<WebPublishMethod>FileSystem</WebPublishMethod>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>osx-arm64</RuntimeIdentifier>
|
||||
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
|
||||
<SelfContained>true</SelfContained>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
#### ASP.NET Application Profile (macOS Intel x64)
|
||||
|
||||
**osx-x64.pubxml:**
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Any CPU</Platform>
|
||||
<DeleteExistingFiles>true</DeleteExistingFiles>
|
||||
<PublishProvider>FileSystem</PublishProvider>
|
||||
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
|
||||
<WebPublishMethod>FileSystem</WebPublishMethod>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>osx-x64</RuntimeIdentifier>
|
||||
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
|
||||
<SelfContained>true</SelfContained>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
#### Console Application Profile (Windows)
|
||||
|
||||
**win-x64.pubxml:**
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Any CPU</Platform>
|
||||
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
<PublishReadyToRun>false</PublishReadyToRun>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
#### Console Application Profile (Linux)
|
||||
|
||||
**linux-x64.pubxml:**
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Any CPU</Platform>
|
||||
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
#### Console Application Profile (macOS Apple Silicon ARM64)
|
||||
|
||||
**osx-arm64.pubxml:**
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Any CPU</Platform>
|
||||
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>osx-arm64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
#### Console Application Profile (macOS Intel x64)
|
||||
|
||||
**osx-x64.pubxml:**
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Any CPU</Platform>
|
||||
<PublishDir>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>osx-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
### Step 2: Configure Electron Builder
|
||||
|
||||
ElectronNET.Core automatically adds a default `electron-builder.json` file under `Properties\electron-builder.json`.
|
||||
Please see here for details of the available configuration options: https://www.electron.build/.
|
||||
|
||||
|
||||
### Step 3: Publish from Visual Studio
|
||||
|
||||
1. **Right-click your project** in Solution Explorer
|
||||
2. **Select "Publish"**
|
||||
4. **Select your publish profile** (Windows/Linux)
|
||||
5. **Click "Publish"**
|
||||
|
||||
The publish process will:
|
||||
- Build your .NET application
|
||||
- Copy all files as needed
|
||||
- Install npm dependencies
|
||||
- Run electron-builder
|
||||
|
||||
> [!NOTE]
|
||||
> When running publish for a Linux configuration on Windows, Electron.NET will automatically use WSL for the platform-specific steps.
|
||||
|
||||
**After publishing**, the final results will be in
|
||||
|
||||
`publish\Release\netx.0\xxx-xxx\`
|
||||
|
||||
|
||||
## MacOS
|
||||
|
||||
> [!NOTE]
|
||||
> macOS builds can't be created on Windows machines because they require symlinks that aren't supported on Windows (per [this Electron issue](https://github.com/electron-userland/electron-packager/issues/71)). macOS builds can be produced on either Linux or macOS machines.
|
||||
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Startup Methods](Startup-Methods.md)** - Understanding different launch modes for packaged apps
|
||||
- **[Debugging](Debugging.md)** - Debug packaged applications
|
||||
- **[Migration Guide](../Core/Migration-Guide.md)** - Update existing projects for new publishing
|
||||
|
||||
## 💡 Benefits
|
||||
|
||||
✅ **Native VS Integration** - Use familiar publish workflows
|
||||
✅ **Cross-Platform Building** - Build Linux packages from Windows
|
||||
✅ **Automatic Configuration** - No manual electron-builder setup
|
||||
✅ **Multiple Package Types** - NSIS, AppImage, DMG, etc.
|
||||
✅ **CI/CD Ready** - Easy integration with build pipelines
|
||||
246
docs/Using/Startup-Methods.md
Normal file
246
docs/Using/Startup-Methods.md
Normal file
@@ -0,0 +1,246 @@
|
||||
# Startup Methods
|
||||
|
||||
ElectronNET.Core supports multiple startup methods to handle different development and deployment scenarios. The framework automatically detects the appropriate mode based on command-line flags and environment.
|
||||
|
||||
## 🎯 Startup Scenarios
|
||||
|
||||
The framework supports **8 different launch scenarios** covering every combination of:
|
||||
|
||||
- **Packaged vs Unpackaged** deployment
|
||||
- **Console vs ASP.NET** application types
|
||||
- **Dotnet-first vs Electron-first** initialization
|
||||
|
||||
## 🚀 Command-Line Flags
|
||||
|
||||
### Unpackaged Debugging Modes
|
||||
|
||||
#### **`-unpackedelectron`** - Electron-first debugging
|
||||
```bash
|
||||
# Launch Electron first, which then starts .NET
|
||||
node node_modules/electron/cli.js main.js -unpackedelectron
|
||||
```
|
||||
|
||||
#### **`-unpackeddotnet`** - .NET-first debugging
|
||||
```bash
|
||||
# Launch .NET first, which then starts Electron
|
||||
dotnet run -unpackeddotnet
|
||||
```
|
||||
|
||||
### Packaged Deployment Modes
|
||||
|
||||
#### **`-dotnetpacked`** - .NET-first packaged execution
|
||||
```bash
|
||||
# Run packaged app with .NET starting first
|
||||
MyApp.exe -dotnetpacked
|
||||
```
|
||||
|
||||
#### **No flags** - Electron-first packaged execution (default)
|
||||
```bash
|
||||
# Run packaged app with Electron starting first
|
||||
MyApp.exe
|
||||
```
|
||||
|
||||
## 📋 Startup Method Details
|
||||
|
||||
### 1. Unpackaged + Electron-First (Development)
|
||||
- **Use Case**: Debug Electron main process and Node.js code
|
||||
- **Command**: `-unpackedelectron` flag
|
||||
- **Process Flow**:
|
||||
1. Electron starts first
|
||||
2. Electron launches .NET process
|
||||
3. .NET connects back to Electron
|
||||
4. Application runs with Electron in control
|
||||
|
||||
### 2. Unpackaged + .NET-First (Development)
|
||||
- **Use Case**: Debug ASP.NET/C# code with Hot Reload
|
||||
- **Command**: `-unpackeddotnet` flag
|
||||
- **Process Flow**:
|
||||
1. .NET application starts first
|
||||
2. .NET launches Electron process
|
||||
3. Electron connects back to .NET
|
||||
4. Application runs with .NET in control
|
||||
|
||||
### 3. Packaged + .NET-First (Production)
|
||||
- **Use Case**: Deployed application with .NET controlling lifecycle
|
||||
- **Command**: `-dotnetpacked` flag
|
||||
- **Process Flow**:
|
||||
1. .NET executable starts first
|
||||
2. .NET launches Electron from packaged files
|
||||
3. Electron loads from app.asar or extracted files
|
||||
4. .NET maintains process control
|
||||
|
||||
### 4. Packaged + Electron-First (Production)
|
||||
- **Use Case**: Traditional Electron app behavior
|
||||
- **Command**: No special flags
|
||||
- **Process Flow**:
|
||||
1. Electron executable starts first
|
||||
2. Electron launches .NET from packaged files
|
||||
3. .NET runs from Electron's process context
|
||||
4. Electron maintains UI control
|
||||
|
||||
## 🔧 Configuration Examples
|
||||
|
||||
### ASP.NET Application Startup
|
||||
|
||||
```csharp
|
||||
// Program.cs
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Configure for different startup modes
|
||||
builder.WebHost.UseElectron(args, async () =>
|
||||
{
|
||||
var browserWindow = await Electron.WindowManager.CreateWindowAsync(
|
||||
new BrowserWindowOptions { Show = false });
|
||||
|
||||
await browserWindow.WebContents.LoadURLAsync("http://localhost:8001");
|
||||
browserWindow.OnReadyToShow += () => browserWindow.Show();
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
app.Run();
|
||||
```
|
||||
|
||||
### Console Application Startup
|
||||
|
||||
```csharp
|
||||
// Program.cs
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
var runtimeController = ElectronNetRuntime.RuntimeController;
|
||||
|
||||
await runtimeController.Start();
|
||||
await runtimeController.WaitReadyTask;
|
||||
|
||||
await InitializeApplication();
|
||||
|
||||
await runtimeController.WaitStoppedTask;
|
||||
}
|
||||
```
|
||||
|
||||
## 🎨 Visual Process Flow
|
||||
|
||||
|
||||

|
||||
|
||||
The image above illustrates how each combination of deployment type, application type, and initialization order affects the process lifecycle.
|
||||
|
||||
## 🚀 Development Workflows
|
||||
|
||||
### Debugging Workflow
|
||||
|
||||
**ASP.NET-First Debugging** (Recommended)
|
||||
```json
|
||||
// launchSettings.json
|
||||
{
|
||||
"ASP.Net (unpackaged)": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "-unpackeddotnet"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Electron-First Debugging**
|
||||
```json
|
||||
// launchSettings.json
|
||||
{
|
||||
"Electron (unpackaged)": {
|
||||
"commandName": "Executable",
|
||||
"executablePath": "node",
|
||||
"commandLineArgs": "node_modules/electron/cli.js main.js -unpackedelectron"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Production Deployment
|
||||
|
||||
**Dotnet-First Deployment**
|
||||
|
||||
```bash
|
||||
# Build and package
|
||||
dotnet publish -c Release -r win-x64
|
||||
cd publish\Release\net8.0\win-x64
|
||||
npm install
|
||||
npx electron-builder
|
||||
|
||||
# Run with dotnet-first
|
||||
MyApp.exe -dotnetpacked
|
||||
```
|
||||
|
||||
**Electron-First Deployment** (Default)
|
||||
|
||||
```bash
|
||||
# Run packaged application (no special flags needed)
|
||||
MyApp.exe
|
||||
```
|
||||
|
||||
## 🔍 Process Lifecycle Management
|
||||
|
||||
### Automatic Cleanup
|
||||
|
||||
ElectronNET.Core automatically manages process lifecycle:
|
||||
|
||||
- **Graceful shutdown** when main window is closed
|
||||
- **Proper cleanup** of child processes
|
||||
- **Error handling** for process failures
|
||||
- **Cross-platform compatibility** for process management
|
||||
|
||||
### Manual Control
|
||||
|
||||
Access runtime controller for advanced scenarios:
|
||||
|
||||
```csharp
|
||||
var runtime = ElectronNetRuntime.RuntimeController;
|
||||
|
||||
// Wait for Electron to be ready
|
||||
await runtime.WaitReadyTask;
|
||||
|
||||
// Stop Electron runtime
|
||||
await runtime.Stop();
|
||||
await runtime.WaitStoppedTask;
|
||||
```
|
||||
|
||||
## 🛠 Troubleshooting
|
||||
|
||||
### Common Startup Issues
|
||||
|
||||
**"Electron process not found"**
|
||||
- Ensure Node.js 22.x is installed
|
||||
- Check that .NET build succeeded
|
||||
- Verify RuntimeIdentifier is set correctly
|
||||
|
||||
**"Port conflicts"**
|
||||
- Use different ports for different startup modes
|
||||
- Check that no other instances are running
|
||||
- Verify firewall settings
|
||||
|
||||
**"Process won't terminate"**
|
||||
- Use dotnet-first mode for better cleanup
|
||||
- Check for unhandled exceptions
|
||||
- Verify all windows are properly closed
|
||||
|
||||
## 💡 Best Practices
|
||||
|
||||
### Choose the Right Mode
|
||||
|
||||
- **Development**: Use .NET-first for C# debugging, Electron-first for Node.js debugging
|
||||
- **Production**: Use .NET-first for better process control, Electron-first for traditional behavior
|
||||
- **Cross-platform**: Use .NET-first for consistent behavior across platforms
|
||||
|
||||
### Environment Configuration
|
||||
|
||||
```xml
|
||||
<!-- .csproj -->
|
||||
<PropertyGroup>
|
||||
<ElectronNETCoreEnvironment>Production</ElectronNETCoreEnvironment>
|
||||
</PropertyGroup>
|
||||
```
|
||||
|
||||
## 🚀 Next Steps
|
||||
|
||||
- **[Debugging](Debugging.md)** - Debug different startup modes
|
||||
- **[Package Building](Package-Building.md)** - Package for different deployment scenarios
|
||||
- **[Migration Guide](../Core/Migration-Guide.md)** - Update existing apps for new startup methods
|
||||
|
||||
## 🎯 Summary
|
||||
|
||||
The flexible startup system ensures ElectronNET.Core works optimally in every scenario while providing the control and debugging experience .NET developers expect. Choose the appropriate mode based on your development workflow and deployment requirements.
|
||||
2
docs/_Footer.md
Normal file
2
docs/_Footer.md
Normal file
@@ -0,0 +1,2 @@
|
||||
|
||||
Want to contribute to this documentation? Please fork and create a PR! The Wiki is autogenerated from the /docs content in the repository.
|
||||
52
docs/_Sidebar.md
Normal file
52
docs/_Sidebar.md
Normal file
@@ -0,0 +1,52 @@
|
||||
<!-- First line gets deleted -->
|
||||
|
||||
# Wiki
|
||||
|
||||
- [Home](Home.md)
|
||||
- [About this Project](About.md)
|
||||
|
||||
# Electron.NET Core
|
||||
|
||||
- [What's new?](Core/What's-New.md)
|
||||
- [Migration Guide](Core/Migration-Guide.md)
|
||||
- [Migration Checks](Core/Migration-Checks.md)
|
||||
- [Advanced Migration](Core/Advanced-Migration-Topics.md)
|
||||
|
||||
# Getting Started
|
||||
|
||||
- [System Requirements](GettingStarted/System-Requirements.md)
|
||||
- [With ASP.Net](GettingStarted/ASP.Net.md)
|
||||
- [With a Console App](GettingStarted/Console-App.md)
|
||||
|
||||
# Using Electron.NET
|
||||
|
||||
- [Configuration](Using/Configuration.md)
|
||||
- [Startup-Methods](Using/Startup-Methods.md)
|
||||
- [Debugging](Using/Debugging.md)
|
||||
- [Package Building](Using/Package-Building.md)
|
||||
- [Adding a `custom_main.js`](Using/Custom_main.md)
|
||||
|
||||
# API Reference
|
||||
|
||||
- [API Overview](API/Overview.md)
|
||||
- [Electron.App](API/App.md)
|
||||
- [Electron.Dialog](API/Dialog.md)
|
||||
- [Electron.Menu](API/Menu.md)
|
||||
- [Electron.WindowManager](API/WindowManager.md)
|
||||
- [Electron.Shell](API/Shell.md)
|
||||
- [Electron.Screen](API/Screen.md)
|
||||
- [Electron.Notification](API/Notification.md)
|
||||
- [Electron.Tray](API/Tray.md)
|
||||
- [Electron.Clipboard](API/Clipboard.md)
|
||||
- [Electron.Dock](API/Dock.md)
|
||||
- [Electron.HostHook](API/HostHook.md)
|
||||
- [Electron.IpcMain](API/IpcMain.md)
|
||||
- [Electron.GlobalShortcut](API/GlobalShortcut.md)
|
||||
- [Electron.AutoUpdater](API/AutoUpdater.md)
|
||||
- [Electron.NativeTheme](API/NativeTheme.md)
|
||||
- [Electron.PowerMonitor](API/PowerMonitor.md)
|
||||
|
||||
# Release Information
|
||||
|
||||
- [Package Description](RelInfo/Package-Description.md)
|
||||
- [Changelog](RelInfo/Changelog.md)
|
||||
BIN
docs/images/app_designer1.png
Normal file
BIN
docs/images/app_designer1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
BIN
docs/images/app_designer2.png
Normal file
BIN
docs/images/app_designer2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
BIN
docs/images/startup_modes.png
Normal file
BIN
docs/images/startup_modes.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
7857
docs/md-styles.css
Normal file
7857
docs/md-styles.css
Normal file
File diff suppressed because it is too large
Load Diff
7
global.json
Normal file
7
global.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "10.0.100",
|
||||
"rollForward": "feature",
|
||||
"allowPrerelease": false
|
||||
}
|
||||
}
|
||||
180
nuke/Build.cs
180
nuke/Build.cs
@@ -3,6 +3,7 @@ using Nuke.Common;
|
||||
using Nuke.Common.CI.GitHubActions;
|
||||
using Nuke.Common.IO;
|
||||
using Nuke.Common.ProjectModel;
|
||||
using Nuke.Common.Tooling;
|
||||
using Nuke.Common.Tools.DotNet;
|
||||
using Nuke.Common.Tools.GitHub;
|
||||
using Nuke.Common.Tools.NuGet;
|
||||
@@ -15,9 +16,9 @@ using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
using static Nuke.Common.IO.FileSystemTasks;
|
||||
using static Nuke.Common.IO.PathConstruction;
|
||||
using static Nuke.Common.Tools.DotNet.DotNetTasks;
|
||||
// ReSharper disable ArrangeThisQualifier
|
||||
|
||||
class Build : NukeBuild
|
||||
{
|
||||
@@ -27,25 +28,20 @@ class Build : NukeBuild
|
||||
/// - Microsoft VisualStudio https://nuke.build/visualstudio
|
||||
/// - Microsoft VSCode https://nuke.build/vscode
|
||||
|
||||
public static int Main () => Execute<Build>(x => x.RunUnitTests);
|
||||
public static int Main() => Execute<Build>(x => x.RunUnitTests);
|
||||
|
||||
[Nuke.Common.Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
|
||||
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
|
||||
|
||||
[Nuke.Common.Parameter("ReleaseNotesFilePath - To determine the SemanticVersion")]
|
||||
[Nuke.Common.Parameter("ReleaseNotesFilePath - To determine the lates changelog version")]
|
||||
readonly AbsolutePath ReleaseNotesFilePath = RootDirectory / "Changelog.md";
|
||||
|
||||
[Nuke.Common.Parameter("common.props file path - to determine the configured version")]
|
||||
readonly AbsolutePath CommonPropsFilePath = RootDirectory / "src" / "common.props";
|
||||
|
||||
[Solution]
|
||||
readonly Solution Solution;
|
||||
|
||||
string TargetProjectName => "ElectronNET";
|
||||
|
||||
string ApiTargetLibName => $"{TargetProjectName}.API";
|
||||
|
||||
string CliTargetLibName => $"{TargetProjectName}.CLI";
|
||||
|
||||
string DemoTargetLibName => $"{TargetProjectName}.WebApp";
|
||||
|
||||
AbsolutePath SourceDirectory => RootDirectory / "src";
|
||||
|
||||
AbsolutePath ResultDirectory => RootDirectory / "artifacts";
|
||||
@@ -60,16 +56,7 @@ class Build : NukeBuild
|
||||
|
||||
string Version { get; set; }
|
||||
|
||||
AbsolutePath[] Projects
|
||||
{
|
||||
get
|
||||
{
|
||||
var api = SourceDirectory / ApiTargetLibName / $"{ApiTargetLibName}.csproj";
|
||||
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
|
||||
var projects = new[] { api, cli };
|
||||
return projects;
|
||||
}
|
||||
}
|
||||
string VersionPostFix { get; set; }
|
||||
|
||||
protected override void OnBuildInitialized()
|
||||
{
|
||||
@@ -82,9 +69,19 @@ class Build : NukeBuild
|
||||
LatestReleaseNotes = ChangeLog.First();
|
||||
LatestReleaseNotes.NotNull("LatestVersion could not be read!");
|
||||
|
||||
Log.Debug("Using LastestVersion from ChangeLog: {LatestVersion}", LatestReleaseNotes.Version);
|
||||
var propsParser = new CommonPropsParser();
|
||||
|
||||
var propsVersion = propsParser.Parse(CommonPropsFilePath);
|
||||
|
||||
propsVersion.NotNull("Version from common.props could not be read!");
|
||||
|
||||
Assert.True(propsVersion == LatestReleaseNotes.Version,
|
||||
$"The version in common.props ({propsVersion}) does not " +
|
||||
$"equal the latest version in the changelog ({LatestReleaseNotes.Version})");
|
||||
|
||||
Log.Debug("Using version: {LatestVersion}", propsVersion);
|
||||
SemVersion = LatestReleaseNotes.SemVersion;
|
||||
Version = LatestReleaseNotes.Version.ToString();
|
||||
Version = propsVersion.ToString();
|
||||
|
||||
if (GitHubActions != null)
|
||||
{
|
||||
@@ -94,145 +91,60 @@ class Build : NukeBuild
|
||||
|
||||
if (ScheduledTargets.Contains(Default))
|
||||
{
|
||||
Version = $"{Version}-ci.{buildNumber}";
|
||||
VersionPostFix = $"-ci.{buildNumber}";
|
||||
}
|
||||
else if (ScheduledTargets.Contains(PrePublish))
|
||||
{
|
||||
Version = $"{Version}-alpha.{buildNumber}";
|
||||
VersionPostFix = $"-pre.{buildNumber}";
|
||||
}
|
||||
}
|
||||
else if (ScheduledTargets.Contains(PrePublish))
|
||||
{
|
||||
VersionPostFix = $"-pre";
|
||||
}
|
||||
|
||||
Log.Information("Building version: {Version}", Version);
|
||||
Log.Information("Building version {Version} with postfix {VersionPostFix}", Version, VersionPostFix);
|
||||
}
|
||||
|
||||
Target Clean => _ => _
|
||||
.Before(Restore)
|
||||
.Executes(() =>
|
||||
{
|
||||
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory);
|
||||
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(dir => dir.DeleteDirectory());
|
||||
});
|
||||
|
||||
Target Restore => _ => _
|
||||
.Executes(() =>
|
||||
{
|
||||
Projects.ForEach(project =>
|
||||
{
|
||||
DotNetRestore(s => s
|
||||
.SetProjectFile(project));
|
||||
});
|
||||
DotNetRestore(s => s.SetProjectFile(Solution));
|
||||
});
|
||||
|
||||
Target Compile => _ => _
|
||||
.DependsOn(Restore)
|
||||
.Executes(() =>
|
||||
{
|
||||
Projects.ForEach(project =>
|
||||
{
|
||||
DotNetBuild(s => s
|
||||
.SetProjectFile(project)
|
||||
.SetVersion(Version)
|
||||
.SetConfiguration(Configuration)
|
||||
.EnableNoRestore());
|
||||
});
|
||||
DotNetBuild(s => s
|
||||
.SetProjectFile(Solution)
|
||||
.SetConfiguration(Configuration)
|
||||
.SetProperty("GeneratePackageOnBuild", "True")
|
||||
.SetProperty("VersionPostFix", VersionPostFix ?? string.Empty));
|
||||
});
|
||||
|
||||
Target RunUnitTests => _ => _
|
||||
.DependsOn(Compile)
|
||||
.Executes(() =>
|
||||
{
|
||||
Projects.ForEach(project =>
|
||||
{
|
||||
DotNetTest(s => s
|
||||
.SetProjectFile(project)
|
||||
.SetConfiguration(Configuration)
|
||||
.EnableNoRestore()
|
||||
.EnableNoBuild());
|
||||
});
|
||||
});
|
||||
var TestProject = SourceDirectory / "ElectronNET.IntegrationTests" / "ElectronNET.IntegrationTests.csproj";
|
||||
|
||||
Target CreatePackages => _ => _
|
||||
.DependsOn(Compile)
|
||||
.Executes(() =>
|
||||
{
|
||||
Projects.ForEach(project =>
|
||||
{
|
||||
DotNetPack(s => s
|
||||
.SetProject(project)
|
||||
.SetVersion(Version)
|
||||
.SetConfiguration(Configuration)
|
||||
.SetOutputDirectory(ResultDirectory)
|
||||
.SetIncludeSymbols(true)
|
||||
.SetSymbolPackageFormat("snupkg")
|
||||
.EnableNoRestore()
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
Target CompileSample => _ => _
|
||||
.DependsOn(Compile)
|
||||
.Executes(() =>
|
||||
{
|
||||
var sample = SourceDirectory / DemoTargetLibName / $"{DemoTargetLibName}.csproj";
|
||||
DotNetBuild(s => s.SetProjectFile(sample).SetConfiguration(Configuration));
|
||||
});
|
||||
|
||||
Target ElectronizeGenericTargetSample => _ => _
|
||||
.DependsOn(CompileSample)
|
||||
.Executes(() =>
|
||||
{
|
||||
var sample = SourceDirectory / DemoTargetLibName;
|
||||
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
|
||||
var args = "build /target custom win7-x86;win /dotnet-configuration Debug /electron-arch ia32 /electron-params \"--publish never\"";
|
||||
|
||||
DotNet($"run --project {cli} -- {args}", sample);
|
||||
});
|
||||
|
||||
Target ElectronizeWindowsTargetSample => _ => _
|
||||
.DependsOn(CompileSample)
|
||||
.Executes(() =>
|
||||
{
|
||||
var sample = SourceDirectory / DemoTargetLibName;
|
||||
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
|
||||
var args = "build /target win /electron-params \"--publish never\"";
|
||||
|
||||
DotNet($"run --project {cli} -- {args}", sample);
|
||||
});
|
||||
|
||||
Target ElectronizeCustomWin7TargetSample => _ => _
|
||||
.DependsOn(CompileSample)
|
||||
.Executes(() =>
|
||||
{
|
||||
var sample = SourceDirectory / DemoTargetLibName;
|
||||
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
|
||||
var args = "build /target custom win7-x86;win /electron-params \"--publish never\"";
|
||||
|
||||
DotNet($"run --project {cli} -- {args}", sample);
|
||||
});
|
||||
|
||||
Target ElectronizeMacOsTargetSample => _ => _
|
||||
.DependsOn(CompileSample)
|
||||
.Executes(() =>
|
||||
{
|
||||
var sample = SourceDirectory / DemoTargetLibName;
|
||||
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
|
||||
var args = "build /target osx /electron-params \"--publish never\"";
|
||||
|
||||
DotNet($"run --project {cli} -- {args}", sample);
|
||||
});
|
||||
|
||||
Target ElectronizeLinuxTargetSample => _ => _
|
||||
.DependsOn(CompileSample)
|
||||
.Executes(() =>
|
||||
{
|
||||
var sample = SourceDirectory / DemoTargetLibName;
|
||||
var cli = SourceDirectory / CliTargetLibName / $"{CliTargetLibName}.csproj";
|
||||
var args = "build /target linux /electron-params \"--publish never\"";
|
||||
|
||||
DotNet($"run --project {cli} -- {args}", sample);
|
||||
DotNetTest(s => s
|
||||
.SetProjectFile(TestProject)
|
||||
.SetConfiguration(Configuration)
|
||||
.When(_ => GitHubActions.Instance is not null, x => x.SetLoggers("GitHubActions"))
|
||||
);
|
||||
});
|
||||
|
||||
Target PublishPackages => _ => _
|
||||
.DependsOn(CreatePackages)
|
||||
.DependsOn(Compile)
|
||||
.DependsOn(RunUnitTests)
|
||||
.Executes(() =>
|
||||
{
|
||||
@@ -244,7 +156,7 @@ class Build : NukeBuild
|
||||
throw new BuildAbortedException("Could not resolve the NuGet API key.");
|
||||
}
|
||||
|
||||
foreach (var nupkg in GlobFiles(ResultDirectory, "*.nupkg"))
|
||||
foreach (var nupkg in ResultDirectory.GlobFiles("*.nupkg"))
|
||||
{
|
||||
DotNetNuGetPush(s => s
|
||||
.SetTargetPath(nupkg)
|
||||
@@ -280,9 +192,9 @@ class Build : NukeBuild
|
||||
new InMemoryCredentialStore(credentials));
|
||||
|
||||
GitHubTasks.GitHubClient.Repository.Release
|
||||
.Create("ElectronNET", "Electron.NET", new NewRelease(Version)
|
||||
.Create("ElectronNET", "Electron.NET", new NewRelease(Version + VersionPostFix)
|
||||
{
|
||||
Name = Version,
|
||||
Name = "ElectronNET.Core " + Version + VersionPostFix,
|
||||
Body = String.Join(Environment.NewLine, LatestReleaseNotes.Notes),
|
||||
Prerelease = true,
|
||||
TargetCommitish = "develop",
|
||||
@@ -318,7 +230,7 @@ class Build : NukeBuild
|
||||
GitHubTasks.GitHubClient.Repository.Release
|
||||
.Create("ElectronNET", "Electron.NET", new NewRelease(Version)
|
||||
{
|
||||
Name = Version,
|
||||
Name = "ElectronNET.Core " + Version,
|
||||
Body = String.Join(Environment.NewLine, LatestReleaseNotes.Notes),
|
||||
Prerelease = false,
|
||||
TargetCommitish = "main",
|
||||
@@ -327,7 +239,7 @@ class Build : NukeBuild
|
||||
|
||||
Target Package => _ => _
|
||||
.DependsOn(RunUnitTests)
|
||||
.DependsOn(CreatePackages);
|
||||
.DependsOn(Compile);
|
||||
|
||||
Target Default => _ => _
|
||||
.DependsOn(Package);
|
||||
|
||||
33
nuke/CommonPropsParser.cs
Normal file
33
nuke/CommonPropsParser.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Xml.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// Parses a version from an MSBuild .props file (XML).
|
||||
/// </summary>
|
||||
public sealed class CommonPropsParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReleaseNotesParser"/> class.
|
||||
/// </summary>
|
||||
public CommonPropsParser()
|
||||
{
|
||||
}
|
||||
|
||||
public Version Parse(string propsPath)
|
||||
{
|
||||
var doc = XDocument.Load(propsPath);
|
||||
|
||||
var versionElement = doc
|
||||
.Descendants()
|
||||
.FirstOrDefault(e => e.Name.LocalName == "Version");
|
||||
|
||||
if (Version.TryParse(versionElement?.Value.Trim(), out var version))
|
||||
{
|
||||
version = new Version(version.Major, version.Minor, version.Build);
|
||||
return version;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ public sealed class ReleaseNotesParser
|
||||
|
||||
// Parse content.
|
||||
var notes = new List<string>();
|
||||
|
||||
|
||||
while (true)
|
||||
{
|
||||
// Sanity checks.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace></RootNamespace>
|
||||
<NoWarn>CS0649;CS0169</NoWarn>
|
||||
<NukeRootDirectory>..</NukeRootDirectory>
|
||||
@@ -11,11 +11,13 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Nuke.Common" Version="6.2.1" />
|
||||
<PackageReference Include="Microsoft.Build" Version="18.0.2" />
|
||||
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="18.0.2" />
|
||||
<PackageReference Include="Nuke.Common" Version="10.1.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageDownload Include="NuGet.CommandLine" Version="[6.3.1]" />
|
||||
<PackageDownload Include="NuGet.CommandLine" Version="[6.12.2]" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
4
src/.editorconfig
Normal file
4
src/.editorconfig
Normal file
@@ -0,0 +1,4 @@
|
||||
[*.cs]
|
||||
|
||||
# CA1416: Validate platform compatibility
|
||||
dotnet_diagnostic.CA1416.severity = error
|
||||
382
src/ElectronNET.API/API/ApiBase.cs
Normal file
382
src/ElectronNET.API/API/ApiBase.cs
Normal file
@@ -0,0 +1,382 @@
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
using Common;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public abstract class ApiBase
|
||||
{
|
||||
protected enum SocketTaskEventNameTypes
|
||||
{
|
||||
DashesLowerFirst,
|
||||
NoDashUpperFirst
|
||||
}
|
||||
|
||||
protected enum SocketTaskMessageNameTypes
|
||||
{
|
||||
DashesLowerFirst,
|
||||
NoDashUpperFirst
|
||||
}
|
||||
|
||||
protected enum SocketEventNameTypes
|
||||
{
|
||||
DashedLower,
|
||||
CamelCase,
|
||||
}
|
||||
|
||||
private static readonly TimeSpan InvocationTimeout = 1000.ms();
|
||||
|
||||
private readonly string objectName;
|
||||
private readonly ConcurrentDictionary<string, Invocator> invocators;
|
||||
private readonly ConcurrentDictionary<string, string> invocationEventNames = new();
|
||||
private readonly ConcurrentDictionary<string, string> invocationMessageNames = new();
|
||||
private readonly ConcurrentDictionary<string, string> methodMessageNames = new();
|
||||
private static readonly ConcurrentDictionary<string, EventContainer> eventContainers = new();
|
||||
private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, Invocator>> AllInvocators = new();
|
||||
|
||||
private readonly object objLock = new object();
|
||||
|
||||
public virtual int Id
|
||||
{
|
||||
get => -1;
|
||||
|
||||
// ReSharper disable once ValueParameterNotUsed
|
||||
protected set
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract SocketTaskEventNameTypes SocketTaskEventNameType { get; }
|
||||
protected virtual SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.NoDashUpperFirst;
|
||||
protected virtual SocketEventNameTypes SocketEventNameType => SocketEventNameTypes.DashedLower;
|
||||
|
||||
protected ApiBase()
|
||||
{
|
||||
this.objectName = this.GetType().Name.LowerFirst();
|
||||
this.invocators = AllInvocators.GetOrAdd(this.objectName, _ => new ConcurrentDictionary<string, Invocator>());
|
||||
}
|
||||
|
||||
protected void CallMethod0([CallerMemberName] string callerName = null)
|
||||
{
|
||||
var messageName = this.methodMessageNames.GetOrAdd(callerName, s => this.objectName + s);
|
||||
if (this.Id >= 0)
|
||||
{
|
||||
BridgeConnector.Socket.Emit(messageName, this.Id);
|
||||
}
|
||||
else
|
||||
{
|
||||
BridgeConnector.Socket.Emit(messageName);
|
||||
}
|
||||
}
|
||||
|
||||
protected void CallMethod1(object val1, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
var messageName = this.methodMessageNames.GetOrAdd(callerName, s => this.objectName + s);
|
||||
if (this.Id >= 0)
|
||||
{
|
||||
BridgeConnector.Socket.Emit(messageName, this.Id, val1);
|
||||
}
|
||||
else
|
||||
{
|
||||
BridgeConnector.Socket.Emit(messageName, val1);
|
||||
}
|
||||
}
|
||||
|
||||
protected void CallMethod2(object val1, object val2, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
var messageName = this.methodMessageNames.GetOrAdd(callerName, s => this.objectName + s);
|
||||
if (this.Id >= 0)
|
||||
{
|
||||
BridgeConnector.Socket.Emit(messageName, this.Id, val1, val2);
|
||||
}
|
||||
else
|
||||
{
|
||||
BridgeConnector.Socket.Emit(messageName, val1, val2);
|
||||
}
|
||||
}
|
||||
|
||||
protected void CallMethod3(object val1, object val2, object val3, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
var messageName = this.methodMessageNames.GetOrAdd(callerName, s => this.objectName + s);
|
||||
if (this.Id >= 0)
|
||||
{
|
||||
BridgeConnector.Socket.Emit(messageName, this.Id, val1, val2, val3);
|
||||
}
|
||||
else
|
||||
{
|
||||
BridgeConnector.Socket.Emit(messageName, val1, val2, val3);
|
||||
}
|
||||
}
|
||||
|
||||
protected Task<T> InvokeAsync<T>(object arg = null, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
return this.InvokeAsyncWithTimeout<T>(InvocationTimeout, arg, callerName);
|
||||
}
|
||||
|
||||
protected Task<T> InvokeAsyncWithTimeout<T>(TimeSpan invocationTimeout, object arg = null, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
Debug.Assert(callerName != null, nameof(callerName) + " != null");
|
||||
|
||||
lock (this.objLock)
|
||||
{
|
||||
return this.invocators.GetOrAdd(callerName, _ =>
|
||||
{
|
||||
var getter = new Invocator<T>(this, callerName, invocationTimeout, arg);
|
||||
|
||||
getter.Task<T>().ContinueWith(_ =>
|
||||
{
|
||||
lock (this.objLock)
|
||||
{
|
||||
return this.invocators.TryRemove(callerName, out var _);
|
||||
}
|
||||
});
|
||||
|
||||
return getter;
|
||||
}).Task<T>();
|
||||
}
|
||||
}
|
||||
|
||||
protected void AddEvent(Action value, int? id = null, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
Debug.Assert(callerName != null, nameof(callerName) + " != null");
|
||||
var eventName = this.EventName(callerName);
|
||||
|
||||
var eventKey = this.EventKey(eventName, id);
|
||||
|
||||
lock (this.objLock)
|
||||
{
|
||||
var container = eventContainers.GetOrAdd(eventKey, _ =>
|
||||
{
|
||||
var container = new EventContainer();
|
||||
BridgeConnector.Socket.On(eventKey, container.OnEventAction);
|
||||
BridgeConnector.Socket.Emit($"register-{eventName}", id);
|
||||
return container;
|
||||
});
|
||||
|
||||
container.Register(value);
|
||||
}
|
||||
}
|
||||
|
||||
protected void RemoveEvent(Action value, int? id = null, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
Debug.Assert(callerName != null, nameof(callerName) + " != null");
|
||||
var eventName = this.EventName(callerName);
|
||||
var eventKey = this.EventKey(eventName, id);
|
||||
|
||||
lock (this.objLock)
|
||||
{
|
||||
if (eventContainers.TryGetValue(eventKey, out var container) && !container.Unregister(value))
|
||||
{
|
||||
BridgeConnector.Socket.Off(eventKey);
|
||||
eventContainers.TryRemove(eventKey, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void AddEvent<T>(Action<T> value, int? id = null, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
Debug.Assert(callerName != null, nameof(callerName) + " != null");
|
||||
|
||||
var eventName = this.EventName(callerName);
|
||||
var eventKey = this.EventKey(eventName, id);
|
||||
|
||||
lock (this.objLock)
|
||||
{
|
||||
var container = eventContainers.GetOrAdd(eventKey, _ =>
|
||||
{
|
||||
var container = new EventContainer();
|
||||
BridgeConnector.Socket.On<T>(eventKey, container.OnEventActionT);
|
||||
BridgeConnector.Socket.Emit($"register-{eventName}", id);
|
||||
return container;
|
||||
});
|
||||
|
||||
container.Register(value);
|
||||
}
|
||||
}
|
||||
|
||||
protected void RemoveEvent<T>(Action<T> value, int? id = null, [CallerMemberName] string callerName = null)
|
||||
{
|
||||
Debug.Assert(callerName != null, nameof(callerName) + " != null");
|
||||
var eventName = this.EventName(callerName);
|
||||
var eventKey = this.EventKey(eventName, id);
|
||||
|
||||
lock (this.objLock)
|
||||
{
|
||||
if (eventContainers.TryGetValue(eventKey, out var container) && !container.Unregister(value))
|
||||
{
|
||||
BridgeConnector.Socket.Off(eventKey);
|
||||
eventContainers.TryRemove(eventKey, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string EventName(string callerName)
|
||||
{
|
||||
switch (this.SocketEventNameType)
|
||||
{
|
||||
case SocketEventNameTypes.DashedLower:
|
||||
return $"{this.objectName}-{callerName.ToDashedEventName()}";
|
||||
case SocketEventNameTypes.CamelCase:
|
||||
return $"{this.objectName}-{callerName.ToCamelCaseEventName()}";
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
}
|
||||
|
||||
private string EventKey(string eventName, int? id)
|
||||
{
|
||||
return string.Format(CultureInfo.InvariantCulture, "{0}{1:D}", eventName, id);
|
||||
}
|
||||
|
||||
internal abstract class Invocator
|
||||
{
|
||||
public abstract Task<T> Task<T>();
|
||||
}
|
||||
|
||||
internal class Invocator<T> : Invocator
|
||||
{
|
||||
private readonly Task<T> tcsTask;
|
||||
private TaskCompletionSource<T> tcs;
|
||||
|
||||
public Invocator(ApiBase apiBase, string callerName, TimeSpan timeout, object arg = null)
|
||||
{
|
||||
this.tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
this.tcsTask = this.tcs.Task;
|
||||
|
||||
string eventName;
|
||||
string messageName;
|
||||
|
||||
switch (apiBase.SocketTaskEventNameType)
|
||||
{
|
||||
case SocketTaskEventNameTypes.DashesLowerFirst:
|
||||
eventName = apiBase.invocationEventNames.GetOrAdd(callerName, s => $"{apiBase.objectName}-{s.StripAsync().LowerFirst()}-completed");
|
||||
break;
|
||||
case SocketTaskEventNameTypes.NoDashUpperFirst:
|
||||
eventName = apiBase.invocationEventNames.GetOrAdd(callerName, s => $"{apiBase.objectName}{s.StripAsync()}Completed");
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
|
||||
switch (apiBase.SocketTaskMessageNameType)
|
||||
{
|
||||
case SocketTaskMessageNameTypes.DashesLowerFirst:
|
||||
messageName = apiBase.invocationMessageNames.GetOrAdd(callerName, s => $"{apiBase.objectName}-{s.StripAsync().LowerFirst()}");
|
||||
break;
|
||||
case SocketTaskMessageNameTypes.NoDashUpperFirst:
|
||||
messageName = apiBase.invocationMessageNames.GetOrAdd(callerName, s => apiBase.objectName + s.StripAsync());
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
|
||||
BridgeConnector.Socket.Once<T>(eventName, (result) =>
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
try
|
||||
{
|
||||
var value = result;
|
||||
this.tcs?.SetResult(value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.tcs?.TrySetException(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.tcs = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (arg != null)
|
||||
{
|
||||
_ = apiBase.Id >= 0 ? BridgeConnector.Socket.Emit(messageName, apiBase.Id, arg) : BridgeConnector.Socket.Emit(messageName, arg);
|
||||
}
|
||||
else
|
||||
{
|
||||
_ = apiBase.Id >= 0 ? BridgeConnector.Socket.Emit(messageName, apiBase.Id) : BridgeConnector.Socket.Emit(messageName);
|
||||
}
|
||||
|
||||
System.Threading.Tasks.Task.Delay(timeout).ContinueWith(_ =>
|
||||
{
|
||||
if (this.tcs != null)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (this.tcs != null)
|
||||
{
|
||||
var ex = new TimeoutException(
|
||||
$"No response after {(long)timeout.TotalMilliseconds}ms trying to retrieve value {apiBase.objectName}.{callerName}()"
|
||||
);
|
||||
this.tcs.TrySetException(ex);
|
||||
this.tcs = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public override Task<T1> Task<T1>()
|
||||
{
|
||||
return this.tcsTask as Task<T1>;
|
||||
}
|
||||
}
|
||||
|
||||
[SuppressMessage("ReSharper", "InconsistentlySynchronizedField")]
|
||||
private class EventContainer
|
||||
{
|
||||
private Action eventAction;
|
||||
private Delegate eventActionT;
|
||||
|
||||
private Action<T> GetEventActionT<T>()
|
||||
{
|
||||
return (Action<T>)this.eventActionT;
|
||||
}
|
||||
|
||||
private void SetEventActionT<T>(Action<T> actionT)
|
||||
{
|
||||
this.eventActionT = actionT;
|
||||
}
|
||||
|
||||
public void OnEventAction() => this.eventAction?.Invoke();
|
||||
|
||||
public void OnEventActionT<T>(T p) => this.GetEventActionT<T>()?.Invoke(p);
|
||||
|
||||
public void Register(Action receiver)
|
||||
{
|
||||
this.eventAction += receiver;
|
||||
}
|
||||
|
||||
public void Register<T>(Action<T> receiver)
|
||||
{
|
||||
var actionT = this.GetEventActionT<T>();
|
||||
actionT += receiver;
|
||||
this.SetEventActionT(actionT);
|
||||
}
|
||||
|
||||
public bool Unregister(Action receiver)
|
||||
{
|
||||
this.eventAction -= receiver;
|
||||
return this.eventAction != null;
|
||||
}
|
||||
|
||||
public bool Unregister<T>(Action<T> receiver)
|
||||
{
|
||||
var actionT = this.GetEventActionT<T>();
|
||||
actionT -= receiver;
|
||||
this.SetEventActionT(actionT);
|
||||
|
||||
return actionT != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
378
src/ElectronNET.API/API/AutoUpdater.cs
Normal file
378
src/ElectronNET.API/API/AutoUpdater.cs
Normal file
@@ -0,0 +1,378 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Enable apps to automatically update themselves. Based on electron-updater.
|
||||
/// </summary>
|
||||
public sealed class AutoUpdater : ApiBase
|
||||
{
|
||||
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
|
||||
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
|
||||
protected override SocketEventNameTypes SocketEventNameType => SocketEventNameTypes.DashedLower;
|
||||
|
||||
/// <summary>
|
||||
/// Whether to automatically download an update when it is found. (Default is true)
|
||||
/// </summary>
|
||||
public bool AutoDownload
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => this.InvokeAsync<bool>()).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-autoDownload-set", value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether to automatically install a downloaded update on app quit (if `QuitAndInstall` was not called before).
|
||||
///
|
||||
/// Applicable only on Windows and Linux.
|
||||
/// </summary>
|
||||
public bool AutoInstallOnAppQuit
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => this.InvokeAsync<bool>()).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-autoInstallOnAppQuit-set", value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// *GitHub provider only.* Whether to allow update to pre-release versions.
|
||||
/// Defaults to "true" if application version contains prerelease components (e.g. "0.12.1-alpha.1", here "alpha" is a prerelease component), otherwise "false".
|
||||
///
|
||||
/// If "true", downgrade will be allowed("allowDowngrade" will be set to "true").
|
||||
/// </summary>
|
||||
public bool AllowPrerelease
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => this.InvokeAsync<bool>()).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-allowPrerelease-set", value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// *GitHub provider only.*
|
||||
/// Get all release notes (from current version to latest), not just the latest (Default is false).
|
||||
/// </summary>
|
||||
public bool FullChangelog
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => this.InvokeAsync<bool>()).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-fullChangelog-set", value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).
|
||||
/// Taken in account only if channel differs (pre-release version component in terms of semantic versioning).
|
||||
/// Default is false.
|
||||
/// </summary>
|
||||
public bool AllowDowngrade
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => this.InvokeAsync<bool>()).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("autoUpdater-allowDowngrade-set", value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For test only.
|
||||
/// </summary>
|
||||
public string UpdateConfigPath
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => this.InvokeAsync<string>()).Result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The current application version
|
||||
/// </summary>
|
||||
public Task<SemVer> CurrentVersionAsync
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => this.InvokeAsync<SemVer>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the update channel. Not applicable for GitHub.
|
||||
/// Doesn’t return channel from the update configuration, only if was previously set.
|
||||
/// </summary>
|
||||
[Obsolete("Use the asynchronous version ChannelAsync instead")]
|
||||
public string Channel
|
||||
{
|
||||
get
|
||||
{
|
||||
return ChannelAsync.Result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the update channel. Not applicable for GitHub.
|
||||
/// Doesn’t return channel from the update configuration, only if was previously set.
|
||||
/// </summary>
|
||||
public Task<string> ChannelAsync
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run(() => 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,22 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using ElectronNET.API.Entities;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// A BrowserView can be used to embed additional web content into a BrowserWindow.
|
||||
/// It is like a child window, except that it is positioned relative to its owning window.
|
||||
/// A BrowserView can be used to embed additional web content into a BrowserWindow.
|
||||
/// It is like a child window, except that it is positioned relative to its owning window.
|
||||
/// It is meant to be an alternative to the webview tag.
|
||||
/// </summary>
|
||||
public class BrowserView
|
||||
public class BrowserView : ApiBase
|
||||
{
|
||||
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
|
||||
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the identifier.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The identifier.
|
||||
/// </value>
|
||||
public int Id { get; internal set; }
|
||||
public override int Id { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Render and control web pages.
|
||||
@@ -28,38 +25,24 @@ namespace ElectronNET.API
|
||||
|
||||
/// <summary>
|
||||
/// Resizes and moves the view to the supplied bounds relative to the window.
|
||||
///
|
||||
/// (experimental)
|
||||
/// </summary>
|
||||
public Rectangle Bounds
|
||||
{
|
||||
get
|
||||
{
|
||||
return Task.Run<Rectangle>(() =>
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<Rectangle>();
|
||||
|
||||
BridgeConnector.Socket.On("browserView-getBounds-reply", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("browserView-getBounds-reply");
|
||||
taskCompletionSource.SetResult((Rectangle)result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("browserView-getBounds", Id);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}).Result;
|
||||
return Task.Run(() => this.InvokeAsync<Rectangle>()).Result;
|
||||
}
|
||||
set
|
||||
{
|
||||
BridgeConnector.Socket.Emit("browserView-setBounds", Id, JObject.FromObject(value, _jsonSerializer));
|
||||
BridgeConnector.Socket.Emit("browserView-bounds-set", Id, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// BrowserView
|
||||
/// </summary>
|
||||
internal BrowserView(int id)
|
||||
internal BrowserView(int id)
|
||||
{
|
||||
Id = id;
|
||||
|
||||
@@ -74,12 +57,11 @@ namespace ElectronNET.API
|
||||
/// <param name="options"></param>
|
||||
public void SetAutoResize(AutoResizeOptions options)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("browserView-setAutoResize", Id, JObject.FromObject(options, _jsonSerializer));
|
||||
BridgeConnector.Socket.Emit("browserView-setAutoResize", Id, options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Color in #aarrggbb or #argb form. The alpha channel is optional.
|
||||
///
|
||||
/// (experimental)
|
||||
/// </summary>
|
||||
/// <param name="color">Color in #aarrggbb or #argb form. The alpha channel is optional.</param>
|
||||
@@ -87,11 +69,5 @@ namespace ElectronNET.API
|
||||
{
|
||||
BridgeConnector.Socket.Emit("browserView-setBackgroundColor", Id, color);
|
||||
}
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
1224
src/ElectronNET.API/API/BrowserWindow.cs
Normal file
1224
src/ElectronNET.API/API/BrowserWindow.cs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,20 +1,27 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Serialization;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Perform copy and paste operations on the system clipboard.
|
||||
/// </summary>
|
||||
public sealed class Clipboard
|
||||
public sealed class Clipboard : ApiBase
|
||||
{
|
||||
protected override SocketTaskEventNameTypes SocketTaskEventNameType => SocketTaskEventNameTypes.DashesLowerFirst;
|
||||
protected override SocketTaskMessageNameTypes SocketTaskMessageNameType => SocketTaskMessageNameTypes.DashesLowerFirst;
|
||||
|
||||
private static Clipboard _clipboard;
|
||||
private static object _syncRoot = new object();
|
||||
|
||||
internal Clipboard() { }
|
||||
internal Clipboard()
|
||||
{
|
||||
}
|
||||
|
||||
internal static Clipboard Instance
|
||||
{
|
||||
@@ -40,21 +47,7 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns>The content in the clipboard as plain text.</returns>
|
||||
public Task<string> ReadTextAsync(string type = "")
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
|
||||
BridgeConnector.Socket.On("clipboard-readText-Completed", (text) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("clipboard-readText-Completed");
|
||||
|
||||
taskCompletionSource.SetResult(text.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("clipboard-readText", type);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
public Task<string> ReadTextAsync(string type = "") => this.InvokeAsync<string>(type);
|
||||
|
||||
/// <summary>
|
||||
/// Writes the text into the clipboard as plain text.
|
||||
@@ -71,21 +64,7 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public Task<string> ReadHTMLAsync(string type = "")
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
|
||||
BridgeConnector.Socket.On("clipboard-readHTML-Completed", (text) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("clipboard-readHTML-Completed");
|
||||
|
||||
taskCompletionSource.SetResult(text.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("clipboard-readHTML", type);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
public Task<string> ReadHTMLAsync(string type = "") => this.InvokeAsync<string>(type);
|
||||
|
||||
/// <summary>
|
||||
/// Writes markup to the clipboard.
|
||||
@@ -102,21 +81,7 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public Task<string> ReadRTFAsync(string type = "")
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
|
||||
BridgeConnector.Socket.On("clipboard-readRTF-Completed", (text) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("clipboard-readRTF-Completed");
|
||||
|
||||
taskCompletionSource.SetResult(text.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("clipboard-readRTF", type);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
public Task<string> ReadRTFAsync(string type = "") => this.InvokeAsync<string>(type);
|
||||
|
||||
/// <summary>
|
||||
/// Writes the text into the clipboard in RTF.
|
||||
@@ -125,41 +90,31 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void WriteRTF(string text, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeHTML", text, type);
|
||||
BridgeConnector.Socket.Emit("clipboard-writeRTF", text, type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns an Object containing title and url keys representing
|
||||
/// the bookmark in the clipboard. The title and url values will
|
||||
/// Returns an Object containing title and url keys representing
|
||||
/// the bookmark in the clipboard. The title and url values will
|
||||
/// be empty strings when the bookmark is unavailable.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Task<ReadBookmark> ReadBookmarkAsync()
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<ReadBookmark>();
|
||||
|
||||
BridgeConnector.Socket.On("clipboard-readBookmark-Completed", (bookmark) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("clipboard-readBookmark-Completed");
|
||||
|
||||
taskCompletionSource.SetResult(((JObject)bookmark).ToObject<ReadBookmark>());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("clipboard-readBookmark");
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
[SupportedOSPlatform("macOS")]
|
||||
[SupportedOSPlatform("Windows")]
|
||||
public Task<ReadBookmark> ReadBookmarkAsync() => this.InvokeAsync<ReadBookmark>();
|
||||
|
||||
/// <summary>
|
||||
/// Writes the title and url into the clipboard as a bookmark.
|
||||
///
|
||||
/// Note: Most apps on Windows don’t support pasting bookmarks
|
||||
/// into them so you can use clipboard.write to write both a
|
||||
/// into them so you can use clipboard.write to write both a
|
||||
/// bookmark and fallback text to the clipboard.
|
||||
/// </summary>
|
||||
/// <param name="title"></param>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="type"></param>
|
||||
[SupportedOSPlatform("macOS")]
|
||||
[SupportedOSPlatform("Windows")]
|
||||
public void WriteBookmark(string title, string url, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeBookmark", title, url, type);
|
||||
@@ -171,27 +126,15 @@ namespace ElectronNET.API
|
||||
/// find pasteboard whenever the application is activated.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Task<string> ReadFindTextAsync()
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
|
||||
BridgeConnector.Socket.On("clipboard-readFindText-Completed", (text) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("clipboard-readFindText-Completed");
|
||||
|
||||
taskCompletionSource.SetResult(text.ToString());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("clipboard-readFindText");
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
[SupportedOSPlatform("macOS")]
|
||||
public Task<string> ReadFindTextAsync() => this.InvokeAsync<string>();
|
||||
|
||||
/// <summary>
|
||||
/// macOS: Writes the text into the find pasteboard as plain text. This method uses
|
||||
/// macOS: Writes the text into the find pasteboard as plain text. This method uses
|
||||
/// synchronous IPC when called from the renderer process.
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
[SupportedOSPlatform("macOS")]
|
||||
public void WriteFindText(string text)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeFindText", text);
|
||||
@@ -211,21 +154,7 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public Task<string[]> AvailableFormatsAsync(string type = "")
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string[]>();
|
||||
|
||||
BridgeConnector.Socket.On("clipboard-availableFormats-Completed", (formats) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("clipboard-availableFormats-Completed");
|
||||
|
||||
taskCompletionSource.SetResult(((JArray)formats).ToObject<string[]>());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("clipboard-availableFormats", type);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
public Task<string[]> AvailableFormatsAsync(string type = "") => this.InvokeAsync<string[]>(type);
|
||||
|
||||
/// <summary>
|
||||
/// Writes data to the clipboard.
|
||||
@@ -234,7 +163,7 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void Write(Data data, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-write", JObject.FromObject(data, _jsonSerializer), type);
|
||||
BridgeConnector.Socket.Emit("clipboard-write", data, type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -242,25 +171,8 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public Task<NativeImage> ReadImageAsync(string type = "")
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<NativeImage>();
|
||||
public Task<NativeImage> ReadImageAsync(string type = "") => this.InvokeAsync<NativeImage>(type);
|
||||
|
||||
BridgeConnector.Socket.On("clipboard-readImage-Completed", (image) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("clipboard-readImage-Completed");
|
||||
|
||||
var nativeImage = ((JObject)image).ToObject<NativeImage>();
|
||||
|
||||
taskCompletionSource.SetResult(nativeImage);
|
||||
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("clipboard-readImage", type);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an image to the clipboard.
|
||||
/// </summary>
|
||||
@@ -268,14 +180,7 @@ namespace ElectronNET.API
|
||||
/// <param name="type"></param>
|
||||
public void WriteImage(NativeImage image, string type = "")
|
||||
{
|
||||
BridgeConnector.Socket.Emit("clipboard-writeImage", JsonConvert.SerializeObject(image), type);
|
||||
BridgeConnector.Socket.Emit("clipboard-writeImage", JsonSerializer.Serialize(image, ElectronJson.Options), type);
|
||||
}
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,9 @@ namespace ElectronNET.API
|
||||
/// </summary>
|
||||
public sealed class CommandLine
|
||||
{
|
||||
internal CommandLine() { }
|
||||
internal CommandLine()
|
||||
{
|
||||
}
|
||||
|
||||
internal static CommandLine Instance
|
||||
{
|
||||
@@ -66,22 +68,17 @@ namespace ElectronNET.API
|
||||
/// <param name="switchName">A command-line switch</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns>Whether the command-line switch is present.</returns>
|
||||
public async Task<bool> HasSwitchAsync(string switchName, CancellationToken cancellationToken = default(CancellationToken))
|
||||
public async Task<bool> HasSwitchAsync(string switchName, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.On("appCommandLineHasSwitchCompleted", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("appCommandLineHasSwitchCompleted");
|
||||
taskCompletionSource.SetResult((bool)result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Once<bool>("appCommandLineHasSwitchCompleted", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("appCommandLineHasSwitch", switchName);
|
||||
|
||||
return await taskCompletionSource.Task.ConfigureAwait(false);
|
||||
return await tcs.Task.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,23 +91,18 @@ namespace ElectronNET.API
|
||||
/// <remarks>
|
||||
/// Note: When the switch is not present or has no value, it returns empty string.
|
||||
/// </remarks>
|
||||
public async Task<string> GetSwitchValueAsync(string switchName, CancellationToken cancellationToken = default(CancellationToken))
|
||||
public async Task<string> GetSwitchValueAsync(string switchName, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
var tcs = new TaskCompletionSource<string>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.On("appCommandLineGetSwitchValueCompleted", (result) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("appCommandLineGetSwitchValueCompleted");
|
||||
taskCompletionSource.SetResult((string)result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Once<string>("appCommandLineGetSwitchValueCompleted", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("appCommandLineGetSwitchValue", switchName);
|
||||
|
||||
return await taskCompletionSource.Task.ConfigureAwait(false);
|
||||
return await tcs.Task.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using ElectronNET.API.Serialization;
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
@@ -34,16 +33,21 @@ namespace ElectronNET.API
|
||||
{
|
||||
if (_changed == null)
|
||||
{
|
||||
BridgeConnector.Socket.On("webContents-session-cookies-changed" + Id, (args) =>
|
||||
BridgeConnector.Socket.On<JsonElement>("webContents-session-cookies-changed" + Id, (args) =>
|
||||
{
|
||||
Cookie cookie = ((JArray)args)[0].ToObject<Cookie>();
|
||||
CookieChangedCause cause = ((JArray)args)[1].ToObject<CookieChangedCause>();
|
||||
bool removed = ((JArray)args)[2].ToObject<bool>();
|
||||
var e = args.EnumerateArray().GetEnumerator();
|
||||
e.MoveNext();
|
||||
var cookie = e.Current.Deserialize<Cookie>(ElectronJson.Options);
|
||||
e.MoveNext();
|
||||
var cause = e.Current.Deserialize<CookieChangedCause>(ElectronJson.Options);
|
||||
e.MoveNext();
|
||||
var removed = e.Current.GetBoolean();
|
||||
_changed(cookie, cause, removed);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("register-webContents-session-cookies-changed", Id);
|
||||
}
|
||||
|
||||
_changed += value;
|
||||
}
|
||||
remove
|
||||
@@ -51,12 +55,16 @@ namespace ElectronNET.API
|
||||
_changed -= value;
|
||||
|
||||
if (_changed == null)
|
||||
{
|
||||
BridgeConnector.Socket.Off("webContents-session-cookies-changed" + Id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private event Action<Cookie, CookieChangedCause, bool> _changed;
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sends a request to get all cookies matching filter, and resolves a callack with the response.
|
||||
/// </summary>
|
||||
@@ -65,20 +73,13 @@ namespace ElectronNET.API
|
||||
/// <returns>A task which resolves an array of cookie objects.</returns>
|
||||
public Task<Cookie[]> GetAsync(CookieFilter filter)
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<Cookie[]>();
|
||||
string guid = Guid.NewGuid().ToString();
|
||||
var tcs = new TaskCompletionSource<Cookie[]>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("webContents-session-cookies-get-completed" + guid, (cookies) =>
|
||||
{
|
||||
Cookie[] result = ((JArray)cookies).ToObject<Cookie[]>();
|
||||
BridgeConnector.Socket.Once<Cookie[]>("webContents-session-cookies-get-completed" + guid, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-get", Id, filter, guid);
|
||||
|
||||
BridgeConnector.Socket.Off("webContents-session-cookies-get-completed" + guid);
|
||||
taskCompletionSource.SetResult(result);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-get", Id, JObject.FromObject(filter, _jsonSerializer), guid);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -88,18 +89,13 @@ namespace ElectronNET.API
|
||||
/// <returns></returns>
|
||||
public Task SetAsync(CookieDetails details)
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<object>();
|
||||
string guid = Guid.NewGuid().ToString();
|
||||
var tcs = new TaskCompletionSource<object>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("webContents-session-cookies-set-completed" + guid, () =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("webContents-session-cookies-set-completed" + guid);
|
||||
taskCompletionSource.SetResult(null);
|
||||
});
|
||||
BridgeConnector.Socket.Once<object>("webContents-session-cookies-set-completed" + guid, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-set", Id, details, guid);
|
||||
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-set", Id, JObject.FromObject(details, _jsonSerializer), guid);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -110,18 +106,13 @@ namespace ElectronNET.API
|
||||
/// <returns>A task which resolves when the cookie has been removed</returns>
|
||||
public Task RemoveAsync(string url, string name)
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<object>();
|
||||
string guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("webContents-session-cookies-remove-completed" + guid, () =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("webContents-session-cookies-remove-completed" + guid);
|
||||
taskCompletionSource.SetResult(null);
|
||||
});
|
||||
var tcs = new TaskCompletionSource<object>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.Once<object>("webContents-session-cookies-remove-completed" + guid, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-remove", Id, url, name, guid);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -130,25 +121,13 @@ namespace ElectronNET.API
|
||||
/// <returns>A task which resolves when the cookie store has been flushed</returns>
|
||||
public Task FlushStoreAsync()
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<object>();
|
||||
string guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("webContents-session-cookies-flushStore-completed" + guid, () =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("webContents-session-cookies-flushStore-completed" + guid);
|
||||
taskCompletionSource.SetResult(null);
|
||||
});
|
||||
var tcs = new TaskCompletionSource<object>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.Once<object>("webContents-session-cookies-flushStore-completed" + guid, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("webContents-session-cookies-flushStore", Id, guid);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
using ElectronNET.API.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using ElectronNET.API.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ElectronNET.API
|
||||
@@ -16,7 +14,9 @@ namespace ElectronNET.API
|
||||
private static Dialog _dialog;
|
||||
private static object _syncRoot = new object();
|
||||
|
||||
internal Dialog() { }
|
||||
internal Dialog()
|
||||
{
|
||||
}
|
||||
|
||||
internal static Dialog Instance
|
||||
{
|
||||
@@ -26,7 +26,7 @@ namespace ElectronNET.API
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
if(_dialog == null)
|
||||
if (_dialog == null)
|
||||
{
|
||||
_dialog = new Dialog();
|
||||
}
|
||||
@@ -38,8 +38,8 @@ namespace ElectronNET.API
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Note: On Windows and Linux an open dialog can not be both a file selector
|
||||
/// and a directory selector, so if you set properties to ['openFile', 'openDirectory']
|
||||
/// Note: On Windows and Linux an open dialog can not be both a file selector
|
||||
/// and a directory selector, so if you set properties to ['openFile', 'openDirectory']
|
||||
/// on these platforms, a directory selector will be shown.
|
||||
/// </summary>
|
||||
/// <param name="browserWindow">The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.</param>
|
||||
@@ -47,23 +47,16 @@ namespace ElectronNET.API
|
||||
/// <returns>An array of file paths chosen by the user</returns>
|
||||
public Task<string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options)
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string[]>();
|
||||
string guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("showOpenDialogComplete" + guid, (filePaths) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("showOpenDialogComplete" + guid);
|
||||
|
||||
var result = ((JArray)filePaths).ToObject<string[]>();
|
||||
taskCompletionSource.SetResult(result);
|
||||
});
|
||||
|
||||
var tcs = new TaskCompletionSource<string[]>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.Once<string[]>("showOpenDialogComplete" + guid, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("showOpenDialog",
|
||||
JObject.FromObject(browserWindow, _jsonSerializer),
|
||||
JObject.FromObject(options, _jsonSerializer), guid);
|
||||
browserWindow,
|
||||
options,
|
||||
guid);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -74,22 +67,16 @@ namespace ElectronNET.API
|
||||
/// <returns>Returns String, the path of the file chosen by the user, if a callback is provided it returns an empty string.</returns>
|
||||
public Task<string> ShowSaveDialogAsync(BrowserWindow browserWindow, SaveDialogOptions options)
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
string guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("showSaveDialogComplete" + guid, (filename) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("showSaveDialogComplete" + guid);
|
||||
|
||||
taskCompletionSource.SetResult(filename.ToString());
|
||||
});
|
||||
var tcs = new TaskCompletionSource<string>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.Once<string>("showSaveDialogComplete" + guid, tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("showSaveDialog",
|
||||
JObject.FromObject(browserWindow, _jsonSerializer),
|
||||
JObject.FromObject(options, _jsonSerializer),
|
||||
guid);
|
||||
browserWindow,
|
||||
options,
|
||||
guid);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -103,7 +90,7 @@ namespace ElectronNET.API
|
||||
/// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns>
|
||||
public async Task<MessageBoxResult> ShowMessageBoxAsync(string message)
|
||||
{
|
||||
return await ShowMessageBoxAsync(null, new MessageBoxOptions(message));
|
||||
return await this.ShowMessageBoxAsync(null, new MessageBoxOptions(message)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -117,7 +104,7 @@ namespace ElectronNET.API
|
||||
/// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns>
|
||||
public async Task<MessageBoxResult> ShowMessageBoxAsync(MessageBoxOptions messageBoxOptions)
|
||||
{
|
||||
return await ShowMessageBoxAsync(null, messageBoxOptions);
|
||||
return await this.ShowMessageBoxAsync(null, messageBoxOptions).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -130,7 +117,7 @@ namespace ElectronNET.API
|
||||
/// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns>
|
||||
public async Task<MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, string message)
|
||||
{
|
||||
return await ShowMessageBoxAsync(browserWindow, new MessageBoxOptions(message));
|
||||
return await this.ShowMessageBoxAsync(browserWindow, new MessageBoxOptions(message)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -143,43 +130,47 @@ namespace ElectronNET.API
|
||||
/// <returns>The API call will be asynchronous and the result will be passed via MessageBoxResult.</returns>
|
||||
public Task<MessageBoxResult> ShowMessageBoxAsync(BrowserWindow browserWindow, MessageBoxOptions messageBoxOptions)
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<MessageBoxResult>();
|
||||
var tcs = new TaskCompletionSource<MessageBoxResult>();
|
||||
var guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("showMessageBoxComplete" + guid, (args) =>
|
||||
BridgeConnector.Socket.Once<JsonElement>("showMessageBoxComplete" + guid, (args) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("showMessageBoxComplete" + guid);
|
||||
// args is [response:int, checkboxChecked:boolean]
|
||||
var arr = args.EnumerateArray();
|
||||
var e = arr.GetEnumerator();
|
||||
e.MoveNext();
|
||||
var response = e.Current.GetInt32();
|
||||
e.MoveNext();
|
||||
var checkbox = e.Current.GetBoolean();
|
||||
|
||||
var result = ((JArray)args);
|
||||
|
||||
taskCompletionSource.SetResult(new MessageBoxResult
|
||||
tcs.SetResult(new MessageBoxResult
|
||||
{
|
||||
Response = (int)result.First,
|
||||
CheckboxChecked = (bool)result.Last
|
||||
Response = response,
|
||||
CheckboxChecked = checkbox
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
if (browserWindow == null)
|
||||
{
|
||||
BridgeConnector.Socket.Emit("showMessageBox", JObject.FromObject(messageBoxOptions, _jsonSerializer), guid);
|
||||
} else
|
||||
BridgeConnector.Socket.Emit("showMessageBox", messageBoxOptions, guid);
|
||||
}
|
||||
else
|
||||
{
|
||||
BridgeConnector.Socket.Emit("showMessageBox",
|
||||
JObject.FromObject(browserWindow, _jsonSerializer),
|
||||
JObject.FromObject(messageBoxOptions, _jsonSerializer),
|
||||
BridgeConnector.Socket.Emit("showMessageBox",
|
||||
browserWindow,
|
||||
messageBoxOptions,
|
||||
guid);
|
||||
}
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Displays a modal dialog that shows an error message.
|
||||
///
|
||||
/// This API can be called safely before the ready event the app module emits,
|
||||
/// it is usually used to report errors in early stage of startup.If called
|
||||
/// before the app readyevent on Linux, the message will be emitted to stderr,
|
||||
/// This API can be called safely before the ready event the app module emits,
|
||||
/// it is usually used to report errors in early stage of startup.If called
|
||||
/// before the app readyevent on Linux, the message will be emitted to stderr,
|
||||
/// and no GUI dialog will appear.
|
||||
/// </summary>
|
||||
/// <param name="title">The title to display in the error box.</param>
|
||||
@@ -191,11 +182,13 @@ namespace ElectronNET.API
|
||||
|
||||
/// <summary>
|
||||
/// On macOS, this displays a modal dialog that shows a message and certificate information,
|
||||
/// and gives the user the option of trusting/importing the certificate. If you provide a
|
||||
/// and gives the user the option of trusting/importing the certificate. If you provide a
|
||||
/// browserWindow argument the dialog will be attached to the parent window, making it modal.
|
||||
/// </summary>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
[SupportedOSPlatform("macOS")]
|
||||
[SupportedOSPlatform("Windows")]
|
||||
public Task ShowCertificateTrustDialogAsync(CertificateTrustDialogOptions options)
|
||||
{
|
||||
return ShowCertificateTrustDialogAsync(null, options);
|
||||
@@ -203,36 +196,26 @@ namespace ElectronNET.API
|
||||
|
||||
/// <summary>
|
||||
/// On macOS, this displays a modal dialog that shows a message and certificate information,
|
||||
/// and gives the user the option of trusting/importing the certificate. If you provide a
|
||||
/// and gives the user the option of trusting/importing the certificate. If you provide a
|
||||
/// browserWindow argument the dialog will be attached to the parent window, making it modal.
|
||||
/// </summary>
|
||||
/// <param name="browserWindow"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
[SupportedOSPlatform("macOS")]
|
||||
[SupportedOSPlatform("Windows")]
|
||||
public Task ShowCertificateTrustDialogAsync(BrowserWindow browserWindow, CertificateTrustDialogOptions options)
|
||||
{
|
||||
var taskCompletionSource = new TaskCompletionSource<object>();
|
||||
var tcs = new TaskCompletionSource();
|
||||
string guid = Guid.NewGuid().ToString();
|
||||
|
||||
BridgeConnector.Socket.On("showCertificateTrustDialogComplete" + guid, () =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("showCertificateTrustDialogComplete" + guid);
|
||||
taskCompletionSource.SetResult(null);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Once("showCertificateTrustDialogComplete" + guid, () => tcs.SetResult());
|
||||
BridgeConnector.Socket.Emit("showCertificateTrustDialog",
|
||||
JObject.FromObject(browserWindow, _jsonSerializer),
|
||||
JObject.FromObject(options, _jsonSerializer),
|
||||
browserWindow,
|
||||
options,
|
||||
guid);
|
||||
|
||||
return taskCompletionSource.Task;
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ElectronNET.API.Entities;
|
||||
using ElectronNET.API.Extensions;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// Control your app in the macOS dock.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macOS")]
|
||||
public sealed class Dock
|
||||
{
|
||||
private static Dock _dock;
|
||||
@@ -54,18 +53,13 @@ namespace ElectronNET.API
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var taskCompletionSource = new TaskCompletionSource<int>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
var tcs = new TaskCompletionSource<int>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.On("dock-bounce-completed", (id) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("dock-bounce-completed");
|
||||
taskCompletionSource.SetResult((int) id);
|
||||
});
|
||||
BridgeConnector.Socket.Once<int>("dock-bounce-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("dock-bounce", type);
|
||||
|
||||
BridgeConnector.Socket.Emit("dock-bounce", type.GetDescription());
|
||||
|
||||
return await taskCompletionSource.Task
|
||||
return await tcs.Task
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -106,18 +100,13 @@ namespace ElectronNET.API
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var taskCompletionSource = new TaskCompletionSource<string>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
var tcs = new TaskCompletionSource<string>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.On("dock-getBadge-completed", (text) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("dock-getBadge-completed");
|
||||
taskCompletionSource.SetResult((string) text);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Once<string>("dock-getBadge-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("dock-getBadge");
|
||||
|
||||
return await taskCompletionSource.Task
|
||||
return await tcs.Task
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -148,18 +137,13 @@ namespace ElectronNET.API
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var taskCompletionSource = new TaskCompletionSource<bool>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.On("dock-isVisible-completed", (isVisible) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("dock-isVisible-completed");
|
||||
taskCompletionSource.SetResult((bool) isVisible);
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Once<bool>("dock-isVisible-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("dock-isVisible");
|
||||
|
||||
return await taskCompletionSource.Task
|
||||
return await tcs.Task
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -170,7 +154,14 @@ namespace ElectronNET.API
|
||||
/// <value>
|
||||
/// The menu items.
|
||||
/// </value>
|
||||
public IReadOnlyCollection<MenuItem> MenuItems { get { return _items.AsReadOnly(); } }
|
||||
public IReadOnlyCollection<MenuItem> MenuItems
|
||||
{
|
||||
get
|
||||
{
|
||||
return _items.AsReadOnly();
|
||||
}
|
||||
}
|
||||
|
||||
private List<MenuItem> _items = new List<MenuItem>();
|
||||
|
||||
/// <summary>
|
||||
@@ -179,15 +170,15 @@ namespace ElectronNET.API
|
||||
public void SetMenu(MenuItem[] menuItems)
|
||||
{
|
||||
menuItems.AddMenuItemsId();
|
||||
BridgeConnector.Socket.Emit("dock-setMenu", JArray.FromObject(menuItems, _jsonSerializer));
|
||||
BridgeConnector.Socket.Emit("dock-setMenu", new[] { menuItems });
|
||||
_items.AddRange(menuItems);
|
||||
|
||||
BridgeConnector.Socket.Off("dockMenuItemClicked");
|
||||
BridgeConnector.Socket.On("dockMenuItemClicked", (id) => {
|
||||
MenuItem menuItem = _items.GetMenuItem(id.ToString());
|
||||
BridgeConnector.Socket.On<string>("dockMenuItemClicked", (id) =>
|
||||
{
|
||||
MenuItem menuItem = _items.GetMenuItem(id);
|
||||
menuItem?.Click();
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -198,18 +189,13 @@ namespace ElectronNET.API
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var taskCompletionSource = new TaskCompletionSource<Menu>();
|
||||
using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled()))
|
||||
var tcs = new TaskCompletionSource<Menu>();
|
||||
using (cancellationToken.Register(() => tcs.TrySetCanceled()))
|
||||
{
|
||||
BridgeConnector.Socket.On("dock-getMenu-completed", (menu) =>
|
||||
{
|
||||
BridgeConnector.Socket.Off("dock-getMenu-completed");
|
||||
taskCompletionSource.SetResult(((JObject)menu).ToObject<Menu>());
|
||||
});
|
||||
|
||||
BridgeConnector.Socket.Once<Menu>("dock-getMenu-completed", tcs.SetResult);
|
||||
BridgeConnector.Socket.Emit("dock-getMenu");
|
||||
|
||||
return await taskCompletionSource.Task
|
||||
return await tcs.Task
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -222,11 +208,5 @@ namespace ElectronNET.API
|
||||
{
|
||||
BridgeConnector.Socket.Emit("dock-setIcon", image);
|
||||
}
|
||||
|
||||
private JsonSerializer _jsonSerializer = new JsonSerializer()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
NullValueHandling = NullValueHandling.Ignore
|
||||
};
|
||||
}
|
||||
}
|
||||
199
src/ElectronNET.API/API/Electron.cs
Normal file
199
src/ElectronNET.API/API/Electron.cs
Normal file
@@ -0,0 +1,199 @@
|
||||
namespace ElectronNET.API
|
||||
{
|
||||
/// <summary>
|
||||
/// The Electron.NET API
|
||||
/// </summary>
|
||||
public static class Electron
|
||||
{
|
||||
/// <summary>
|
||||
/// Communicate asynchronously from the main process to renderer processes.
|
||||
/// </summary>
|
||||
public static IpcMain IpcMain
|
||||
{
|
||||
get
|
||||
{
|
||||
return IpcMain.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Control your application's event lifecycle.
|
||||
/// </summary>
|
||||
public static App App
|
||||
{
|
||||
get
|
||||
{
|
||||
return App.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enable apps to automatically update themselves. Based on electron-updater.
|
||||
/// </summary>
|
||||
public static AutoUpdater AutoUpdater
|
||||
{
|
||||
get
|
||||
{
|
||||
return AutoUpdater.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Control your windows.
|
||||
/// </summary>
|
||||
public static WindowManager WindowManager
|
||||
{
|
||||
get
|
||||
{
|
||||
return WindowManager.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create native application menus and context menus.
|
||||
/// </summary>
|
||||
public static Menu Menu
|
||||
{
|
||||
get
|
||||
{
|
||||
return Menu.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Display native system dialogs for opening and saving files, alerting, etc.
|
||||
/// </summary>
|
||||
public static Dialog Dialog
|
||||
{
|
||||
get
|
||||
{
|
||||
return Dialog.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create OS desktop notifications
|
||||
/// </summary>
|
||||
public static Notification Notification
|
||||
{
|
||||
get
|
||||
{
|
||||
return Notification.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add icons and context menus to the system’s notification area.
|
||||
/// </summary>
|
||||
public static Tray Tray
|
||||
{
|
||||
get
|
||||
{
|
||||
return Tray.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detect keyboard events when the application does not have keyboard focus.
|
||||
/// </summary>
|
||||
public static GlobalShortcut GlobalShortcut
|
||||
{
|
||||
get
|
||||
{
|
||||
return GlobalShortcut.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Manage files and URLs using their default applications.
|
||||
/// </summary>
|
||||
public static Shell Shell
|
||||
{
|
||||
get
|
||||
{
|
||||
return Shell.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve information about screen size, displays, cursor position, etc.
|
||||
/// </summary>
|
||||
public static Screen Screen
|
||||
{
|
||||
get
|
||||
{
|
||||
return Screen.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Perform copy and paste operations on the system clipboard.
|
||||
/// </summary>
|
||||
public static Clipboard Clipboard
|
||||
{
|
||||
get
|
||||
{
|
||||
return Clipboard.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allows you to execute native JavaScript/TypeScript code from the host process.
|
||||
///
|
||||
/// It is only possible if the Electron.NET CLI has previously added an
|
||||
/// ElectronHostHook directory:
|
||||
/// <c>electronize add HostHook</c>
|
||||
/// </summary>
|
||||
public static HostHook HostHook
|
||||
{
|
||||
get
|
||||
{
|
||||
return HostHook.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allows you to execute native Lock and Unlock process.
|
||||
/// </summary>
|
||||
public static PowerMonitor PowerMonitor
|
||||
{
|
||||
get
|
||||
{
|
||||
return PowerMonitor.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read and respond to changes in Chromium's native color theme.
|
||||
/// </summary>
|
||||
public static NativeTheme NativeTheme
|
||||
{
|
||||
get
|
||||
{
|
||||
return NativeTheme.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Control your app in the macOS dock.
|
||||
/// </summary>
|
||||
public static Dock Dock
|
||||
{
|
||||
get
|
||||
{
|
||||
return Dock.Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Electeon extensions to the Nodejs process object.
|
||||
/// </summary>
|
||||
public static Process Process
|
||||
{
|
||||
get
|
||||
{
|
||||
return Process.Instance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
namespace ElectronNET.API.Entities
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
/// About panel options.
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class AboutPanelOptions
|
||||
{
|
||||
/// <summary>
|
||||
@@ -21,28 +24,35 @@
|
||||
public string Copyright { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The app's build version number.
|
||||
/// The app's build version number (macOS).
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public string Version { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Credit information.
|
||||
/// Credit information (macOS, Windows).
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
[SupportedOSPlatform("windows")]
|
||||
public string Credits { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// List of app authors.
|
||||
/// List of app authors (Linux).
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("linux")]
|
||||
public string[] Authors { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The app's website.
|
||||
/// The app's website (Linux).
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("linux")]
|
||||
public string Website { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Path to the app's icon. On Linux, will be shown as 64x64 pixels while retaining aspect ratio.
|
||||
/// Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio. On Windows, a 48x48 PNG will result in the best visual quality.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("linux")]
|
||||
[SupportedOSPlatform("windows")]
|
||||
public string IconPath { get; set; }
|
||||
}
|
||||
}
|
||||
36
src/ElectronNET.API/API/Entities/AddRepresentationOptions.cs
Normal file
36
src/ElectronNET.API/API/Entities/AddRepresentationOptions.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class AddRepresentationOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the width in pixels. Defaults to 0. Required if a bitmap buffer is specified as <see cref="Buffer"/>.
|
||||
/// </summary>
|
||||
public int? Width { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the height in pixels. Defaults to 0. Required if a bitmap buffer is specified as <see cref="Buffer"/>.
|
||||
/// </summary>
|
||||
public int? Height { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the image scale factor. Defaults to 1.0.
|
||||
/// </summary>
|
||||
public float ScaleFactor { get; set; } = 1.0f;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the buffer containing the raw image data.
|
||||
/// </summary>
|
||||
public byte[] Buffer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the data URL containing a base 64 encoded PNG or JPEG image.
|
||||
/// </summary>
|
||||
public string DataUrl { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,36 @@
|
||||
namespace ElectronNET.API.Entities
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public class AppDetailsOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Window’s App User Model ID. It has to be set, otherwise the other options will have no effect.
|
||||
/// Window's App User Model ID. It has to be set, otherwise the other options will have no effect.
|
||||
/// </summary>
|
||||
public string AppId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Window’s Relaunch Icon.
|
||||
/// Window's relaunch icon resource path.
|
||||
/// </summary>
|
||||
public string AppIconPath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Index of the icon in appIconPath. Ignored when appIconPath is not set. Default is 0.
|
||||
/// Index of the icon in <see cref="AppIconPath"/>. Ignored when <see cref="AppIconPath"/> is not set. Default is 0.
|
||||
/// </summary>
|
||||
public int AppIconIndex { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Window’s Relaunch Command.
|
||||
/// Window's relaunch command.
|
||||
/// </summary>
|
||||
public string RelaunchCommand { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Window’s Relaunch Display Name.
|
||||
/// Window's relaunch display name.
|
||||
/// </summary>
|
||||
public string RelaunchDisplayName { get; set; }
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace ElectronNET.API.Entities
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class AutoResizeOptions
|
||||
{
|
||||
/// <summary>
|
||||
@@ -35,4 +36,4 @@ namespace ElectronNET.API.Entities
|
||||
[DefaultValue(false)]
|
||||
public bool Vertical { get; set; } = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,12 @@
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class BitmapOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the scale factor
|
||||
/// The image scale factor. Defaults to 1.0.
|
||||
/// </summary>
|
||||
public float ScaleFactor { get; set; } = 1.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class Blob : IPostData
|
||||
{
|
||||
/// <summary>
|
||||
@@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
@@ -32,4 +28,4 @@ namespace ElectronNET.API.Entities
|
||||
/// </summary>
|
||||
public bool IsAdminRightsRequired { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,23 +3,26 @@
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class BrowserViewConstructorOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// See BrowserWindow.
|
||||
/// Gets or sets the web preferences for the view (see WebPreferences).
|
||||
/// </summary>
|
||||
public WebPreferences WebPreferences { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// A proxy to set on creation in the format host:port.
|
||||
/// Gets or sets a proxy to use on creation in the format host:port.
|
||||
/// The proxy can be alternatively set using the BrowserView.WebContents.SetProxyAsync function.
|
||||
/// </summary>
|
||||
/// <remarks>This is custom shortcut. Not part of the Electron API.</remarks>
|
||||
public string Proxy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The credentials of the Proxy in the format username:password.
|
||||
/// Gets or sets the credentials of the proxy in the format username:password.
|
||||
/// These will only be used if the Proxy field is also set.
|
||||
/// </summary>
|
||||
/// <remarks>This is custom shortcut. Not part of the Electron API.</remarks>
|
||||
public string ProxyCredentials { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using ElectronNET.Converter;
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
@@ -23,13 +24,13 @@ namespace ElectronNET.API.Entities
|
||||
/// ( if y is used) Window's left offset from screen. Default is to center the
|
||||
/// window.
|
||||
/// </summary>
|
||||
public int X { get; set; } = -1;
|
||||
public int? X { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// ( if x is used) Window's top offset from screen. Default is to center the
|
||||
/// window.
|
||||
/// </summary>
|
||||
public int Y { get; set; } = -1;
|
||||
public int? Y { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The width and height would be used as web page's size, which means the actual
|
||||
@@ -72,24 +73,32 @@ namespace ElectronNET.API.Entities
|
||||
/// <summary>
|
||||
/// Whether window is movable. This is not implemented on Linux. Default is true.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
[SupportedOSPlatform("windows")]
|
||||
[DefaultValue(true)]
|
||||
public bool Movable { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Whether window is minimizable. This is not implemented on Linux. Default is true.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
[SupportedOSPlatform("windows")]
|
||||
[DefaultValue(true)]
|
||||
public bool Minimizable { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Whether window is maximizable. This is not implemented on Linux. Default is true.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
[SupportedOSPlatform("windows")]
|
||||
[DefaultValue(true)]
|
||||
public bool Maximizable { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Whether window is closable. This is not implemented on Linux. Default is true.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
[SupportedOSPlatform("windows")]
|
||||
[DefaultValue(true)]
|
||||
public bool Closable { get; set; } = true;
|
||||
|
||||
@@ -115,16 +124,24 @@ namespace ElectronNET.API.Entities
|
||||
|
||||
/// <summary>
|
||||
/// Whether the window can be put into fullscreen mode. On macOS, also whether the
|
||||
/// maximize/zoom button should toggle full screen mode or maximize window.Default
|
||||
/// is true.
|
||||
/// maximize/zoom button should toggle full screen mode or maximize window. Default
|
||||
/// is true (Electron default).
|
||||
/// </summary>
|
||||
public bool Fullscreenable { get; set; }
|
||||
[DefaultValue(true)]
|
||||
public bool Fullscreenable { get; set; } = true; // FIX: previously defaulted to false in C#
|
||||
|
||||
/// <summary>
|
||||
/// Whether to show the window in taskbar. Default is false.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
[SupportedOSPlatform("windows")]
|
||||
public bool SkipTaskbar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Determines if Blazor is used. Will disable "module" and "process" globals. Default is false.
|
||||
/// </summary>
|
||||
public bool IsRunningBlazor { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The kiosk mode. Default is false.
|
||||
/// </summary>
|
||||
@@ -136,8 +153,7 @@ namespace ElectronNET.API.Entities
|
||||
public string Title { get; set; } = "Electron.NET";
|
||||
|
||||
/// <summary>
|
||||
/// The window icon. On Windows it is recommended to use ICO icons to get best
|
||||
/// visual effects, you can also leave it undefined so the executable's icon will be used.
|
||||
/// The window icon. Can be a NativeImage or a string path. On Windows it is recommended to use ICO icons; when undefined, the executable's icon will be used.
|
||||
/// </summary>
|
||||
public string Icon { get; set; }
|
||||
|
||||
@@ -148,7 +164,7 @@ namespace ElectronNET.API.Entities
|
||||
public bool Show { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Specify false to create a . Default is true.
|
||||
/// Specify false to create a frameless window. Default is true.
|
||||
/// </summary>
|
||||
[DefaultValue(true)]
|
||||
public bool Frame { get; set; } = true;
|
||||
@@ -163,6 +179,7 @@ namespace ElectronNET.API.Entities
|
||||
/// Whether the web view accepts a single mouse-down event that simultaneously
|
||||
/// activates the window.Default is false.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public bool AcceptFirstMouse { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -173,33 +190,40 @@ namespace ElectronNET.API.Entities
|
||||
/// <summary>
|
||||
/// Auto hide the menu bar unless the Alt key is pressed. Default is false.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
[SupportedOSPlatform("linux")]
|
||||
public bool AutoHideMenuBar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Enable the window to be resized larger than screen. Default is false.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public bool EnableLargerThanScreen { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Window's background color as Hexadecimal value, like #66CD00 or #FFF or
|
||||
/// #80FFFFFF (alpha is supported). Default is #FFF (white).
|
||||
/// The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if transparent is set to true. Default is #FFF (white).
|
||||
/// </summary>
|
||||
public string BackgroundColor { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether window should have a shadow. This is only implemented on macOS. Default
|
||||
/// is true.
|
||||
/// Initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). Only implemented on Windows and macOS.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
[SupportedOSPlatform("macos")]
|
||||
public double? Opacity { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether window should have a shadow. Default is true.
|
||||
/// </summary>
|
||||
public bool HasShadow { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Forces using dark theme for the window, only works on some GTK+3 desktop
|
||||
/// environments.Default is false.
|
||||
/// Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default is false.
|
||||
/// </summary>
|
||||
public bool DarkTheme { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Makes the window . Default is false.
|
||||
/// Makes the window transparent. Default is false.
|
||||
/// </summary>
|
||||
public bool Transparent { get; set; }
|
||||
|
||||
@@ -212,13 +236,30 @@ namespace ElectronNET.API.Entities
|
||||
/// The style of window title bar. Default is default. Possible values are:
|
||||
/// 'default' | 'hidden' | 'hiddenInset' | 'customButtonsOnHover'
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
public TitleBarStyle TitleBarStyle { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Shows the title in the tile bar in full screen mode on macOS for all
|
||||
/// titleBarStyle options.Default is false.
|
||||
/// Set a custom position for the traffic light buttons in frameless windows (macOS).
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public Point TrafficLightPosition { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Configures the window's title bar overlay when using a frameless window.
|
||||
/// Can be either:
|
||||
/// - false: No title bar overlay.
|
||||
/// - true: Enables the default title bar overlay.
|
||||
/// - An object defining custom overlay options (such as height, color, etc.).
|
||||
///
|
||||
/// Default is false.
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(TitleBarOverlayConverter))]
|
||||
public TitleBarOverlay TitleBarOverlay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Shows the title in the title bar in full screen mode on macOS for all titleBarStyle options. Default is false.
|
||||
/// </summary>
|
||||
/// <remarks>Not documented by MCP base-window-options / browser-window-options.</remarks>
|
||||
public bool FullscreenWindowTitle { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -226,15 +267,27 @@ namespace ElectronNET.API.Entities
|
||||
/// window frame.Setting it to false will remove window shadow and window
|
||||
/// animations. Default is true.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
[DefaultValue(true)]
|
||||
public bool ThickFrame { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Add a type of vibrancy effect to the window, only on macOS. Can be
|
||||
/// appearance-based, light, dark, titlebar, selection, menu, popover, sidebar,
|
||||
/// medium-light or ultra-dark.
|
||||
/// Whether frameless window should have rounded corners. Default is true. Setting this
|
||||
/// property to false will prevent the window from being fullscreenable on macOS. On
|
||||
/// Windows versions older than Windows 11 Build 22000 this property has no effect, and
|
||||
/// frameless windows will not have rounded corners.
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
[SupportedOSPlatform("macos")]
|
||||
[SupportedOSPlatform("windows")]
|
||||
[DefaultValue(true)]
|
||||
public bool RoundedCorners { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Add a type of vibrancy effect to the window, only on macOS. Can be
|
||||
/// appearance-based, titlebar, selection, menu, popover, sidebar, header, sheet,
|
||||
/// window, hud, fullscreen-ui, tooltip, content, under-window, or under-page.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public Vibrancy Vibrancy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -244,6 +297,7 @@ namespace ElectronNET.API.Entities
|
||||
/// it to zoom to the width of the screen.This will also affect the behavior when
|
||||
/// calling maximize() directly.Default is false.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public bool ZoomToPageWidth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -252,6 +306,7 @@ namespace ElectronNET.API.Entities
|
||||
/// adds a native new tab button to your window's tab bar and allows your app and
|
||||
/// window to receive the new-window-for-tab event.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public string TabbingIdentifier { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@@ -263,12 +318,39 @@ namespace ElectronNET.API.Entities
|
||||
/// A proxy to set on creation in the format host:port.
|
||||
/// The proxy can be alternatively set using the BrowserWindow.WebContents.SetProxyAsync function.
|
||||
/// </summary>
|
||||
/// <remarks>Not documented by MCP base-window-options / browser-window-options.</remarks>
|
||||
public string Proxy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The credentials of the Proxy in the format username:password.
|
||||
/// These will only be used if the Proxy field is also set.
|
||||
/// </summary>
|
||||
/// <remarks>Not documented by MCP base-window-options / browser-window-options.</remarks>
|
||||
public string ProxyCredentials { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether to use pre-Lion fullscreen on macOS. Default is false.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public bool SimpleFullscreen { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the window should be hidden when the user toggles into mission control (macOS).
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public bool HiddenInMissionControl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets how the material appearance should reflect window activity state on macOS. Must be used with the vibrancy property.
|
||||
/// Possible values: 'followWindow' (default), 'active', 'inactive'.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("macos")]
|
||||
public string VisualEffectState { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the system-drawn background material on Windows. Can be 'auto', 'none', 'mica', 'acrylic' or 'tabbed'.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public string BackgroundMaterial { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
25
src/ElectronNET.API/API/Entities/CPUUsage.cs
Normal file
25
src/ElectronNET.API/API/Entities/CPUUsage.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class CPUUsage
|
||||
{
|
||||
/// <summary>
|
||||
/// Percentage of CPU used since the last call to getCPUUsage. First call returns 0.
|
||||
/// </summary>
|
||||
public double PercentCPUUsage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Total seconds of CPU time used since process startup, if available.
|
||||
/// </summary>
|
||||
public double? CumulativeCPUUsage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The number of average idle CPU wakeups per second since the last call to
|
||||
/// getCPUUsage. First call returns 0. Will always return 0 on Windows.
|
||||
/// </summary>
|
||||
public double IdleWakeupsPerSecond { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class Certificate
|
||||
{
|
||||
/// <summary>
|
||||
@@ -3,6 +3,7 @@
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class CertificatePrincipal
|
||||
{
|
||||
/// <summary>
|
||||
@@ -3,6 +3,7 @@
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class CertificateTrustDialogOptions
|
||||
{
|
||||
/// <summary>
|
||||
@@ -1,12 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
/// Provide metadata about the current loaded Chrome extension
|
||||
/// </summary>
|
||||
/// <yremarks>Project-specific: no matching Electron structure found in MCP docs (electronjs).</yremarks>
|
||||
public class ChromeExtensionInfo
|
||||
{
|
||||
/// <summary>
|
||||
@@ -30,4 +27,4 @@ namespace ElectronNET.API.Entities
|
||||
/// </summary>
|
||||
public string Version { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
28
src/ElectronNET.API/API/Entities/ClearStorageDataOptions.cs
Normal file
28
src/ElectronNET.API/API/Entities/ClearStorageDataOptions.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class ClearStorageDataOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Should follow window.location.origin’s 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; }
|
||||
}
|
||||
}
|
||||
59
src/ElectronNET.API/API/Entities/Cookie.cs
Normal file
59
src/ElectronNET.API/API/Entities/Cookie.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
/// Cookie structure as used by Electron session.cookies APIs.
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class Cookie
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the cookie.
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the cookie.
|
||||
/// </summary>
|
||||
public string Value { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the domain of the cookie; this will be normalized with a preceding dot so that it's also valid for subdomains.
|
||||
/// </summary>
|
||||
public string Domain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the cookie is a host-only cookie; this will only be true if no domain was passed.
|
||||
/// </summary>
|
||||
public bool? HostOnly { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path of the cookie.
|
||||
/// </summary>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the cookie is marked as secure.
|
||||
/// </summary>
|
||||
public bool? Secure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the cookie is marked as HTTP only.
|
||||
/// </summary>
|
||||
public bool? HttpOnly { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the cookie is a session cookie or a persistent cookie with an expiration date.
|
||||
/// </summary>
|
||||
public bool? Session { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies.
|
||||
/// </summary>
|
||||
public double? ExpirationDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the SameSite policy applied to this cookie. Can be "unspecified", "no_restriction", "lax" or "strict".
|
||||
/// </summary>
|
||||
public string SameSite { get; set; }
|
||||
}
|
||||
}
|
||||
36
src/ElectronNET.API/API/Entities/CookieChangedCause.cs
Normal file
36
src/ElectronNET.API/API/Entities/CookieChangedCause.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
/// <summary>
|
||||
/// The cause of the cookie change (per Electron Cookies 'changed' event).
|
||||
/// </summary>
|
||||
public enum CookieChangedCause
|
||||
{
|
||||
/// <summary>
|
||||
/// The cookie was changed directly by a consumer's action.
|
||||
/// </summary>
|
||||
@explicit,
|
||||
|
||||
/// <summary>
|
||||
/// The cookie was automatically removed due to an insert operation that overwrote it.
|
||||
/// </summary>
|
||||
overwrite,
|
||||
|
||||
/// <summary>
|
||||
/// The cookie was automatically removed as it expired.
|
||||
/// </summary>
|
||||
expired,
|
||||
|
||||
/// <summary>
|
||||
/// The cookie was automatically evicted during garbage collection.
|
||||
/// </summary>
|
||||
evicted,
|
||||
|
||||
/// <summary>
|
||||
/// The cookie was overwritten with an already-expired expiration date.
|
||||
/// </summary>
|
||||
[JsonPropertyName("expired_overwrite")]
|
||||
expiredOverwrite
|
||||
}
|
||||
}
|
||||
63
src/ElectronNET.API/API/Entities/CookieDetails.cs
Normal file
63
src/ElectronNET.API/API/Entities/CookieDetails.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class CookieDetails
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the URL to associate the cookie with. The operation will be rejected if the URL is invalid.
|
||||
/// </summary>
|
||||
public string Url { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the cookie. Empty by default if omitted.
|
||||
/// </summary>
|
||||
[DefaultValue("")]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the cookie. Empty by default if omitted.
|
||||
/// </summary>
|
||||
[DefaultValue("")]
|
||||
public string Value { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the domain of the cookie; this will be normalized with a preceding dot so that it's also valid for subdomains. Empty by default if omitted.
|
||||
/// </summary>
|
||||
[DefaultValue("")]
|
||||
public string Domain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path of the cookie. Empty by default if omitted.
|
||||
/// </summary>
|
||||
[DefaultValue("")]
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the cookie should be marked as secure. Defaults to false unless the SameSite policy is set to <c>no_restriction</c> (SameSite=None).
|
||||
/// </summary>
|
||||
[DefaultValue(false)]
|
||||
public bool Secure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the cookie should be marked as HTTP only. Defaults to false.
|
||||
/// </summary>
|
||||
[DefaultValue(false)]
|
||||
public bool HttpOnly { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie and will not be retained between sessions.
|
||||
/// </summary>
|
||||
[DefaultValue(0)]
|
||||
public double ExpirationDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the SameSite policy to apply to this cookie. Can be "unspecified", "no_restriction", "lax" or "strict". Default is "lax".
|
||||
/// </summary>
|
||||
public string SameSite { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace ElectronNET.API.Entities
|
||||
namespace ElectronNET.API.Entities
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class CookieFilter
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class CookieFilter
|
||||
{
|
||||
/// <summary>
|
||||
/// (optional) - Retrieves cookies which are associated with url.Empty implies retrieving cookies of all URLs.
|
||||
/// (optional) - Retrieves cookies which are associated with url. Empty implies retrieving cookies of all URLs.
|
||||
/// </summary>
|
||||
public string Url { get; set; }
|
||||
|
||||
@@ -32,12 +29,16 @@ namespace ElectronNET.API.Entities
|
||||
/// <summary>
|
||||
/// (optional) - Filters cookies by their Secure property.
|
||||
/// </summary>
|
||||
public bool Secure { get; set; }
|
||||
public bool? Secure { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// (optional) - Filters out session or persistent cookies.
|
||||
/// </summary>
|
||||
public bool Session { get; set; }
|
||||
public bool? Session { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// (optional) - Filters cookies by httpOnly.
|
||||
/// </summary>
|
||||
public bool? HttpOnly { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,21 +3,22 @@
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class CreateFromBitmapOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the width
|
||||
/// Gets or sets the width in pixels. Required for nativeImage.createFromBitmap(buffer, options).
|
||||
/// </summary>
|
||||
public int? Width { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the height
|
||||
/// Gets or sets the height in pixels. Required for nativeImage.createFromBitmap(buffer, options).
|
||||
/// </summary>
|
||||
public int? Height { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the scalefactor
|
||||
/// Gets or sets the image scale factor. Optional, defaults to 1.0.
|
||||
/// </summary>
|
||||
public float ScaleFactor { get; set; } = 1.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,21 @@ namespace ElectronNET.API.Entities
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class CreateFromBufferOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the width
|
||||
/// Gets or sets the width. Required for bitmap buffers passed to nativeImage.createFromBuffer.
|
||||
/// </summary>
|
||||
public int? Width { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the height
|
||||
/// Gets or sets the height. Required for bitmap buffers passed to nativeImage.createFromBuffer.
|
||||
/// </summary>
|
||||
public int? Height { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the scalefactor
|
||||
/// The image scale factor. Optional, defaults to 1.0.
|
||||
/// </summary>
|
||||
public float ScaleFactor { get; set; } = 1.0f;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <remarks>Up-to-date with Electron API 39.2</remarks>
|
||||
public class CreateInterruptedDownloadOptions
|
||||
{
|
||||
/// <summary>
|
||||
@@ -16,7 +17,7 @@
|
||||
public string[] UrlChain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// (optional) - MIME type of the download.
|
||||
/// </summary>
|
||||
public string MimeType { get; set; }
|
||||
|
||||
@@ -41,9 +42,10 @@
|
||||
public string ETag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Time when download was started in number of seconds since UNIX epoch.
|
||||
/// (optional) - Time when download was started in number of seconds since UNIX epoch.
|
||||
/// Electron documents this as a Number (Double).
|
||||
/// </summary>
|
||||
public int StartTime { get; set; }
|
||||
public double? StartTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
@@ -64,4 +66,4 @@
|
||||
ETag = eTag;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,12 @@
|
||||
/// </value>
|
||||
public string Html { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the image.
|
||||
/// Maps to clipboard.write({ image: NativeImage }).
|
||||
/// </summary>
|
||||
public NativeImage Image { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the RTF.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user