0Pricing
Electron Desktop App Development · درس

القوائم الأصلية وقوائم السياق

طبّق قوائم مخصّصة للتطبيق وقوائم سياق وقوائم شريط النظام لتوفير تنقّل وخيارات مألوفة للمستخدمين

القوائم الأصلية وقوائم السياق درس مجاني في Electron Desktop App Development على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Electron Desktop App Development، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Electron Desktop App Development 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Native Menus in Electron

Electron lets you build desktop apps using web technologies. But desktop apps also need native features like menus!

Native menus offer a familiar experience to users, fitting seamlessly into their operating system. Electron's Menu module allows you to create these.

  • Application Menus: The main menu bar (File, Edit, View).
  • Context Menus: Right-click menus specific to an element.
  • Tray Menus: Menus for icons in the system tray or dock.

Building the Main Menu Bar

The Application Menu is the main menu bar at the top of your app window (Windows/Linux) or the top of the screen (macOS).

It usually contains standard options like "File", "Edit", "View", and "Help". These menus make your app feel native and provide essential navigation.

You define its structure using a JavaScript array of objects, called a menu template.

Code: Basic Application Menu

Let's create a minimal application menu. This code snippet goes into your Electron app's main.js file.

It defines a "File" menu with an "Exit" option that quits the app. (Note: nodeIntegration: true, contextIsolation: false are used here for simplicity in examples, but often require more secure configurations for production apps).

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

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  mainWindow.loadFile('index.html'); // Ensure you have an index.html file

  const template = [
    {
      label: 'File',
      submenu: [
        {
          label: 'Exit',
          accelerator: 'CmdOrCtrl+Q',
          click() { app.quit(); }
        }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

  mainWindow.on('closed', () => { mainWindow = null; });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (mainWindow === null) createWindow();
});

Advanced Menu Items & Roles

Menu items can have special roles that provide standard functionality (like 'copy', 'paste', 'quit') and ensure platform-specific behavior.

You can also create nested menus (submenus) to organize options better. Accelerators (keyboard shortcuts) can be added for quick access.

  • role: 'quit': Quits the app.
  • role: 'separator': Adds a dividing line.
  • accelerator: 'CmdOrCtrl+Z': Defines a keyboard shortcut.

Code: Full Application Menu

Let's enhance our application menu. We'll add an "Edit" menu with standard roles and a "Help" menu with a custom item.

Notice how roles simplify common actions, and submenus keep the main menu clean.

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

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  mainWindow.loadFile('index.html');

  const template = [
    {
      label: 'File',
      submenu: [
        { label: 'New', accelerator: 'CmdOrCtrl+N' },
        { type: 'separator' },
        { label: 'Exit', role: 'quit' }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        { label: 'Undo', role: 'undo' },
        { label: 'Redo', role: 'redo' },
        { type: 'separator' },
        { label: 'Cut', role: 'cut' },
        { label: 'Copy', role: 'copy' },
        { label: 'Paste', role: 'paste' }
      ]
    },
    {
      label: 'Help',
      submenu: [
        { label: 'About App', click() { console.log('About clicked!'); } }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

  mainWindow.on('closed', () => { mainWindow = null; });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (mainWindow === null) createWindow();
});

Dynamic Context Menus

Context menus are those "right-click" menus that appear when you interact with specific elements or areas of an application.

Unlike the static application menu, context menus are often dynamic, changing based on what you've clicked on. They're built using the same Menu module.

They are typically created in the main process and then displayed (popped up) from the renderer process via Inter-Process Communication (IPC).

Code: Creating a Context Menu

Here's how to define a simple context menu. For this example, we'll demonstrate it being popped up from the main process after a delay for simplicity. In a real app, it's usually triggered by a right-click event in the renderer process, communicating with the main process.

The popup() method displays the menu.

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

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  mainWindow.loadFile('index.html');

  const contextMenuTemplate = [
    { label: 'Inspect Element', click() { mainWindow.webContents.openDevTools(); } },
    { type: 'separator' },
    { label: 'Reload Page', role: 'reload' }
  ];

  const contextMenu = Menu.buildFromTemplate(contextMenuTemplate);

  // For demonstration: show context menu after a delay
  setTimeout(() => {
    contextMenu.popup({ window: mainWindow });
    console.log('Context menu popped up!');
  }, 3000);

  mainWindow.on('closed', () => { mainWindow = null; });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (mainWindow === null) createWindow();
});

System Tray & Dock Menus

A tray icon (also known as a status bar icon on macOS or system tray icon on Windows/Linux) allows your application to run in the background and provide quick access to common actions.

The Tray module in Electron lets you create these icons and attach a tray menu to them, which appears when the user interacts with the icon (e.g., right-click).

Code: Basic Tray Menu

This example shows how to create a simple tray icon with a context menu. Remember to provide a small icon file (e.g., icon.png) in your project root.

The tray icon will appear in your system's notification area or dock. Clicking the tray icon will toggle the main window's visibility.

const { app, BrowserWindow, Menu, Tray } = require('electron');
const path = require('path');

let mainWindow;
let tray;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300,
    show: false, // Start hidden for tray app
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  mainWindow.loadFile('index.html');

  mainWindow.on('closed', () => { mainWindow = null; });
}

app.whenReady().then(() => {
  createWindow();

  // Path to your icon file (e.g., in the same directory as main.js)
  const iconPath = path.join(__dirname, 'icon.png'); 
  tray = new Tray(iconPath);

  const contextMenu = Menu.buildFromTemplate([
    { label: 'Open App', click: () => { mainWindow.show(); } },
    { label: 'Toggle DevTools', click: () => { mainWindow.webContents.toggleDevTools(); } },
    { type: 'separator' },
    { label: 'Quit', click: () => { app.quit(); } }
  ]);

  tray.setToolTip('My Electron Tray App');
  tray.setContextMenu(contextMenu);

  tray.on('click', () => {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
  });
});

app.on('before-quit', () => {
  // Clean up tray icon before quitting to prevent memory leaks
  if (tray) tray.destroy();
});

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the dock icon is clicked
  if (mainWindow === null) createWindow();
});

// For apps with tray icons, you might not want to quit when all windows are closed
// app.on('window-all-closed', () => {
//   if (process.platform !== 'darwin') app.quit(); 
// });

Menu Types Check

You've learned about different types of native menus in Electron.

Which of the following statements about Electron menus is TRUE?

Menus: Key Takeaways

Well done! You've learned how to integrate native menus into your Electron applications.

  • Use the Menu module to create application, context, and tray menus.
  • Define menu structures using menu templates (arrays of objects).
  • Leverage menu item roles for standard functionality and platform consistency.
  • Application menus are for the main window bar, context menus for dynamic right-click options, and tray menus for system tray/dock icons.
  • Always use Menu.buildFromTemplate() and Menu.setApplicationMenu() for the main app menu.

These native touches greatly improve the user experience of your desktop app!

الأسئلة الشائعة

هل درس «القوائم الأصلية وقوائم السياق» مجاني؟

نعم — نص درس «القوائم الأصلية وقوائم السياق» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Electron Desktop App Development، انتقل إلى CoddyKit PRO. تتضمن دورة Electron Desktop App Development 4 دروس في المجموع.

ماذا ستتعلم في «القوائم الأصلية وقوائم السياق»؟

طبّق قوائم مخصّصة للتطبيق وقوائم سياق وقوائم شريط النظام لتوفير تنقّل وخيارات مألوفة للمستخدمين تتمرن على Electron Desktop App Development مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Electron Desktop App Development؟

لا تُشترط خبرة سابقة. Electron Desktop App Development على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «القوائم الأصلية وقوائم السياق»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Electron Desktop App Development هذا؟

نعم. كل درس في Electron Desktop App Development يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. القوائم الأصلية وقوائم السياق
  2. مربعات الحوار والإشعارات
  3. التكامل مع الصدفة
  4. الاختصارات العامة والوصول إلى الحافظة
← العودة إلى Electron Desktop App Development