LoginSignup
0
0

More than 3 years have passed since last update.

Angular から Electron のイベントを呼び出し

Last updated at Posted at 2020-03-31

前回 Angular での Electron 環境構築したので次は Angular から Electron のイベント呼び出し。

IPC(inter-process communication module of Electron)の追加

Electron の main.js に ipcMain を追加

const { app, BrowserWindow, ipcMain } = require('electron');

IPC は ここを参照すると IPC は Electron のプロセス間通信モジュールらしい。

IPC を利用したイベントの定義

引き続き main.js に以下を追加。

ipcMain.on('testIpc', (event, arg) => {
  console.log('IPC のテスト');
})

Angular component に IPC 用の処理を追加

/sample1/src/app/app.component.ts を以下に。

import { Component } from '@angular/core';
import { IpcRenderer } from 'electron';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.scss'],
  templateUrl: './app.component.html',
})
export class AppComponent {
  public title = 'sample1';
  private ipc: IpcRenderer;

  constructor() {
    if ((window as any).require) {
      try {
        this.ipc = (window as any).require('electron').ipcRenderer;
      } catch (e) {
        throw e;
      }
    } else {
      console.warn('App not running inside Electron!');
    }
  }

  // ボタンクリックで ipc の指定イベント呼び出し
  public clickIpcTestBtn() {
    this.ipc.send('testIpc');
  }
}

レイアウトにボタン追加

/sample1/src/app/app.component.html をわかりやすく以下のみにに。

<button type="button" name="button" (click)="clickIpcTestBtn()">
  IPC のテスト
</button>

動作確認

npm run start:electron

でビルド、ボタンクリックでターミナルのログに

IPC のテスト

と出るようになる。
次はローカルファイル呼び出し。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0