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

Windows 窗体 NotifyIcon 组件在任务栏的状态通知区域中显示单个图标。 若要在状态区域中显示多个图标,窗体上必须有多个 NotifyIcon 组件。 若要设置控件的显示图标,请使用 Icon 属性。 还可以在 DoubleClick 事件处理程序中编写代码,以便在用户双击图标时有所反应。 例如,可以为用户显示一个对话框以配置图标表示的后台进程。

注意

NotifyIcon 组件仅用于通知,以提醒用户发生了某个操作或事件,或者某种状态发生了更改。 应使用菜单、工具栏和其他用户界面元素,与应用程序进行标准交互。

设置图标

  1. Icon 属性赋值。 该值必须是 System.Drawing.Icon 类型,并且可以从 .ico 文件加载。 可以在代码中指定图标文件,也可以通过单击“属性”窗口中的 Icon 属性旁边的省略号按钮 (The Ellipsis button (...) in the Properties window of Visual Studio.),然后在显示的“打开”对话框中选择该文件。

  2. Visible 属性设置为 true

  3. Text 属性设置为适当的 ToolTip 字符串。

    在下面的代码示例中,为图标位置设置的路径是 My Documents 文件夹。 使用此位置是因为大多数运行 Windows 操作系统的计算机都包含此文件夹。 选择此位置还使得系统访问级别最低的用户能够安全运行应用程序。 以下示例需要一个已添加 NotifyIcon 控件的窗体。 还需要一个名为 Icon.ico 的图标文件。

    ' You should replace the bold icon in the sample below
    ' with an icon of your own choosing.
    NotifyIcon1.Icon = New _
       System.Drawing.Icon(System.Environment.GetFolderPath _
       (System.Environment.SpecialFolder.Personal) _
       & "\Icon.ico")
    NotifyIcon1.Visible = True
    NotifyIcon1.Text = "Antivirus program"
    
    // You should replace the bold icon in the sample below
    // with an icon of your own choosing.
    // Note the escape character used (@) when specifying the path.
    notifyIcon1.Icon =
       new System.Drawing.Icon (System.Environment.GetFolderPath
       (System.Environment.SpecialFolder.Personal)
       + @"\Icon.ico");
    notifyIcon1.Visible = true;
    notifyIcon1.Text = "Antivirus program";
    
    // You should replace the bold icon in the sample below
    // with an icon of your own choosing.
    notifyIcon1->Icon = gcnew
       System::Drawing::Icon(String::Concat
       (System::Environment::GetFolderPath
       (System::Environment::SpecialFolder::Personal),
       "\\Icon.ico"));
    notifyIcon1->Visible = true;
    notifyIcon1->Text = "Antivirus program";
    

另请参阅