gpt4 book ai didi

angular - 从 Angular 组件关闭 Electron 应用程序

转载 作者:行者123 更新时间:2023-12-03 12:20:34 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何关闭带有 Angular 组件的 Electron 应用程序。我通过在 BrowserWindow 上设置 frame: false 删除了菜单栏({... inside main.js。我在组件的 Electron 应用程序的右上角有一个关闭按钮。我想能够在单击时从 component.ts 文件关闭应用程序,但我还没有看到任何从 Angular 组件关闭 Electron 的示例。

我认为以下内容会起作用,但没有。我正在从 main.js 导出一个函数并从组件调用该函数。像这样(参见 closeApp()):

const { app, BrowserWindow } = require('electron')
const url = require("url");
const path = require("path");

let mainWindow

function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false,
webPreferences: {
nodeIntegration: true
}
})
mainWindow.maximize();
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, `/dist/index.html`),
protocol: "file:",
slashes: true
})
);

...

function closeApp() {
mainWindow = null
}

export { closeApp };

然后我会尝试将它导入到组件中

import { Component, OnInit } from '@angular/core';
import { closeApp } from '../../../main.js';

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

constructor() { }

ngOnInit(): void {

}
testClose() {
closeApp();
}

}

如何从 Angular 关闭 Electron 应用程序?感谢您的帮助!

最佳答案

您可以在浏览器窗口中使用这样的代码。请记住,它需要 enableRemoteModule,出于安全原因不推荐这样做。您可以使用更复杂的代码来解决这个问题,但这应该向您展示基本思想

更简单但不太安全的方法

在您的主进程中:

mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false,
fullscreen: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
})

从您的mainWindow,在渲染器中

点击您应用的关闭按钮(您的自定义按钮)后,您应该让它运行以下逻辑:

const win = remote.getCurrentWindow();
win.close();

https://www.electronjs.org/docs/api/browser-window#winclose

win.destroy() 也可用,但 win.close() 应该是首选。


更难但更安全的方式

这需要使用预加载脚本那是另一个问题,但我将包含以这种方式执行此操作的代码,但由于多种原因,它更难开始工作。

也就是说,从长远来看,这就是您实现目标的方式。

  import { browserWindow, ipcMain } from 'electron';

mainWindow = new BrowserWindow({
width: 800,
height: 600,
frame: false,
fullscreen: false,
preload: [Absolute file path to your preload file],
webPreferences: {}
});

ipcMain.handle('close-main-window', async (evt) => {
mainWindow.close();
// You can also return values from here

});


preload.js

  const { ipcRenderer } = require('electron');

// We only pass closeWindow to be used in the renderer page, rather than passing the entire ipcRenderer, which is a security issue
const closeWindow = async () => {
await ipcRenderer.invoke('close-main-window'); // We don't actually need async/await here, but if you were returning a value from `ipcRenderer.invoke` then you would need async/await
}

window.api = {
closeWindow
}

渲染器页面

  
// I don't know Angular, but just call window.api.closeWindow() in response to the button you want to use

关于angular - 从 Angular 组件关闭 Electron 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66082739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com