vue3+Electron,在系统页面点击事件调用硬件快捷键

发布于:2025-07-09 ⋅ 阅读:(15) ⋅ 点赞:(0)

最近在做项目中,需要在桌面应用中点击按钮,触发钱箱驱动设置的快捷键打开钱箱,
找了两天,终于在AI那找到了解决方法,
只想说一句AI NB
下面是解决方案:

  1. 主进程代码(main.js)
const { app, BrowserWindow, ipcMain } = require('electron');
const { exec } = require('child_process');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true,
      preload: __dirname + '/preload.js'
    }
  });

  // 监听渲染进程的按键请求
  ipcMain.on('trigger-global-key', (event, key) => {
    simulateGlobalKey(key);
  });
}

// 跨平台模拟全局按键
function simulateGlobalKey(key) {
  const platform = process.platform;
  let command = '';

  if (platform === 'win32') {
    // Windows: 使用PowerShell模拟按键
    command = `powershell -command "$wshell = New-Object -ComObject WScript.Shell; $wshell.SendKeys('{${key}}')"`;
  } 
  else if (platform === 'darwin') {
    // macOS: 使用AppleScript模拟按键
    const keyCodeMap = {
      'F1': 122,
      'F2': 120,
      'F3': 99,
      'F4': 118,
      'F5': 96,
      'F6': 97,
      'F7': 98,
      'F8': 100,
      'F9': 101,
      'F10': 109,
      'F11': 103,
      'F12': 111
    };
    
    const code = keyCodeMap[key] || 122; // 默认F1
    command = `osascript -e 'tell application "System Events" to key code ${code}'`;
  } 
  else if (platform === 'linux') {
    // Linux: 使用xdotool模拟按键(需先安装)
    command = `xdotool key ${key}`;
  }

  // 执行命令
  exec(command, (error) => {
    if (error) {
      console.error(`模拟${key}失败:`, error);
    } else {
      console.log(`已成功模拟${key}按键`);
    }
  });
}

app.whenReady().then(createWindow);
  1. 预加载脚本(preload.js)
const { contextBridge, ipcRenderer } = require('electron');

// 暴露API给渲染进程
contextBridge.exposeInMainWorld('keyboardAPI', {
  triggerKey: (key) => ipcRenderer.send('trigger-global-key', key)
});
  1. Vue 组件中调用
<template>
  <button @click="openCashDrawer">打开钱箱</button>
</template>

<script setup>
const openCashDrawer = () => {
  try {
    // 触发全局F1按键
    window.keyboardAPI.triggerKey('F1');
    console.log('已请求触发F1快捷键');
  } catch (error) {
    console.error('触发失败:', error);
  }
};
</script>

以上就是全部代码了,遇到此种问题的小伙伴可以试试,希望可以帮到你~
如果对你有用的话,不如点赞加个关注叭~~~~


网站公告

今日签到

点亮在社区的每一天
去签到