system.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { ipcMain } from 'electron';
  2. import { exec } from 'child_process';
  3. import { promisify } from 'util';
  4. import { getCachedAdbPath } from '../config.js';
  5. const execAsync = promisify(exec);
  6. /**
  7. * 发送系统按键事件到设备
  8. * @param {string} ipPort - 设备 ID/IP:Port
  9. * @param {string} keyCode - 按键代码(如 "4" 表示返回键,"3" 表示Home键)
  10. * @returns {Promise<{success: boolean, error?: string}>}
  11. */
  12. export async function sendSystemKey(ipPort, keyCode) {
  13. if (!ipPort) {
  14. return { success: false, error: '缺少设备 ID' };
  15. }
  16. if (typeof keyCode !== 'string') {
  17. return { success: false, error: '按键代码必须是字符串' };
  18. }
  19. try {
  20. const adbPath = getCachedAdbPath();
  21. const command = `${adbPath} -s ${ipPort} shell input keyevent ${keyCode}`;
  22. await execAsync(command, {
  23. timeout: 5000,
  24. maxBuffer: 1024 * 1024
  25. });
  26. return { success: true };
  27. } catch (error) {
  28. return { success: false, error: error.message };
  29. }
  30. }
  31. /**
  32. * 返回键
  33. * @param {string} ipPort - 设备 ID/IP:Port
  34. * @returns {Promise<{success: boolean, error?: string}>}
  35. */
  36. export async function sendBackKey(ipPort) {
  37. return sendSystemKey(ipPort, '4');
  38. }
  39. /**
  40. * Home键
  41. * @param {string} ipPort - 设备 ID/IP:Port
  42. * @returns {Promise<{success: boolean, error?: string}>}
  43. */
  44. export async function sendHomeKey(ipPort) {
  45. return sendSystemKey(ipPort, '3');
  46. }
  47. /**
  48. * 最近任务键
  49. * @param {string} ipPort - 设备 ID/IP:Port
  50. * @returns {Promise<{success: boolean, error?: string}>}
  51. */
  52. export async function sendRecentAppsKey(ipPort) {
  53. return sendSystemKey(ipPort, '187');
  54. }
  55. /**
  56. * 注册 IPC 处理器
  57. */
  58. export function registerIpcHandlers() {
  59. // IPC 处理程序:发送系统按键
  60. ipcMain.handle('send-system-key', async (event, ipPort, keyCode) => {
  61. return await sendSystemKey(ipPort, keyCode);
  62. });
  63. // IPC 处理程序:返回键
  64. ipcMain.handle('send-back-key', async (event, ipPort) => {
  65. return await sendBackKey(ipPort);
  66. });
  67. // IPC 处理程序:Home键
  68. ipcMain.handle('send-home-key', async (event, ipPort) => {
  69. return await sendHomeKey(ipPort);
  70. });
  71. // IPC 处理程序:最近任务键
  72. ipcMain.handle('send-recent-apps-key', async (event, ipPort) => {
  73. return await sendRecentAppsKey(ipPort);
  74. });
  75. }