如何:将快捷菜单与 Windows 窗体 NotifyIcon 组件关联

更新:2007 年 11 月

说明:

尽管 MenuStripContextMenuStrip 替换了早期版本的 MainMenuContextMenu 控件并添加了功能,但是也可选择保留 MainMenuContextMenu 以备向后兼容和将来使用。

NotifyIcon 组件在任务栏的状态通知区域中显示一个图标。通常,应用程序允许您右键单击此图标将命令发送到它表示的应用程序。将 ContextMenu 组件与 NotifyIcon 组件关联,便可以将此功能添加到应用程序中。

说明:

如果要让应用程序在启动时最小化,同时在任务栏中显示 NotifyIcon 组件的一个实例,可将主窗体的 WindowState 属性设置为 Minimized,并确保将 NotifyIcon 组件的 Visible 属性设置为 true。

在设计时将快捷菜单与 NotifyIcon 组件关联

  1. 向窗体添加 NotifyIcon 组件,并设置重要属性,如 IconVisible 属性。

    有关更多信息,请参见 如何:使用 Windows 窗体 NotifyIcon 组件向任务栏添加应用程序图标

  2. 向 Windows 窗体添加 ContextMenu 组件。

    向表示您希望在运行时使其可用的命令的快捷菜单添加菜单项。这也是向这些菜单项添加菜单增强功能的好时机,如访问键。

  3. NotifyIcon 组件的 ContextMenu 属性设置为您添加的快捷菜单。

    设置此属性后,单击任务栏上的图标时将显示快捷菜单。

以编程方式将快捷菜单与 NotifyIcon 组件关联

  1. 使用应用程序所需的任何属性设置(NotifyIcon 组件的 IconVisible 属性,ContextMenu 组件的菜单项),创建 NotifyIcon 类的一个实例和一个 ContextMenu 类。

  2. NotifyIcon 组件的 ContextMenu 属性设置为您添加的快捷菜单。

    设置此属性后,单击任务栏上的图标时将显示快捷菜单。

    说明:

    下面的代码示例可创建基本菜单结构。您需要将菜单选项自定义为适合正在开发的应用程序的菜单项。另外,您需要编写处理这些菜单项的 Click 事件的代码。

    Public ContextMenu1 As New ContextMenu
    Public NotifyIcon1 As New NotifyIcon
    
    Public Sub CreateIconMenuStructure()
       ' Add menu items to shortcut menu.
       ContextMenu1.MenuItems.Add("&Open Application")
       ContextMenu1.MenuItems.Add("S&uspend Application")
       ContextMenu1.MenuItems.Add("E&xit")
    
       ' Set properties of NotifyIcon component.
       NotifyIcon1.Icon = New System.Drawing.Icon _ 
          (System.Environment.GetFolderPath _ 
          (System.Environment.SpecialFolder.Personal)  _ 
          & "\Icon.ico")
       NotifyIcon1.Text = "Right-click me!"
       NotifyIcon1.Visible = True
       NotifyIcon1.ContextMenu = ContextMenu1
    End Sub
    

请参见

任务

如何:使用 Windows 窗体 NotifyIcon 组件向任务栏添加应用程序图标

参考

NotifyIcon 组件概述(Windows 窗体)

NotifyIcon

Icon

其他资源

NotifyIcon 组件(Windows 窗体)