Skip to content

Commit c04af1c

Browse files
committed
Electron Tray Support
1 parent 4e1400b commit c04af1c

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

desktop/main.js

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,38 @@
1-
const { app, BrowserWindow, protocol } = require('electron')
1+
const { app, BrowserWindow, protocol, Tray, Menu } = require('electron')
22
const path = require('path')
33
const fs = require('fs')
44
const url = require('url')
55

6+
let tray = null
7+
let win = null
8+
9+
function createTray() {
10+
tray = new Tray(path.join(__dirname, 'icon.png'))
11+
const contextMenu = Menu.buildFromTemplate([
12+
{
13+
label: 'Show',
14+
click: () => {
15+
win.show()
16+
}
17+
},
18+
{
19+
label: 'Quit',
20+
click: () => {
21+
app.quit()
22+
}
23+
}
24+
])
25+
26+
tray.setToolTip('TrustyNotes')
27+
tray.setContextMenu(contextMenu)
28+
29+
tray.on('click', () => {
30+
win.show()
31+
})
32+
}
33+
634
function createWindow() {
7-
const win = new BrowserWindow({
35+
win = new BrowserWindow({
836
width: 1280,
937
height: 720,
1038
icon: path.join(__dirname, 'icon.png'),
@@ -17,6 +45,20 @@ function createWindow() {
1745
}
1846
})
1947

48+
win.on('minimize', (event) => {
49+
event.preventDefault()
50+
win.hide()
51+
})
52+
53+
win.on('close', (event) => {
54+
if (!app.isQuitting) {
55+
event.preventDefault()
56+
win.hide()
57+
return false
58+
}
59+
return true
60+
})
61+
2062
win.webContents.session.webRequest.onHeadersReceived((details, callback) => {
2163
callback({
2264
responseHeaders: {
@@ -81,6 +123,7 @@ app.whenReady().then(() => {
81123
})
82124

83125
createWindow()
126+
createTray()
84127
}).catch(err => {
85128
console.error('Failed to initialize app:', err)
86129
})
@@ -91,6 +134,10 @@ app.on('window-all-closed', () => {
91134
}
92135
})
93136

137+
app.on('before-quit', () => {
138+
app.isQuitting = true
139+
})
140+
94141
app.on('activate', () => {
95142
if (BrowserWindow.getAllWindows().length === 0) {
96143
createWindow()

desktop/preload.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ contextBridge.exposeInMainWorld('electron', {
66
versions: {
77
node: process.versions.node,
88
electron: process.versions.electron
9+
},
10+
minimizeToTray: () => {
11+
const window = require('@electron/remote').getCurrentWindow()
12+
window.minimize()
913
}
1014
})
1115

src/types/electron.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ interface ElectronAPI {
55
node: string;
66
electron: string;
77
};
8+
minimizeToTray: () => void;
89
}
910

1011
declare global {

0 commit comments

Comments
 (0)