System windows forms notifyicon

Последнее обновление: 31.10.2015

Элемент NotifyIcon позволяет задать значок, который будет отображаться при запуске приложения в панели задач.

Рассмотрим основные его свойства:

  • BallonTipIcon: иконка, которая будет использоваться на всплывающей подсказке. Это свойство может иметь следующие значения:
    None, Info, Warning, Error.

  • BalloonTipText: текст, отображаемый во всплывающей подсказке

  • BalloonTipTitle: загаловок всплывающей подсказки

  • ContextMenuStrip: устанавливает контекстное меню для объекта NotifyIcon

  • Icon: задает значок, который будет отображаться в системном трее

  • Text: устанавливает текст всплывающей подсказки, которая появляется при нахождении указателя мыши над значком

  • Visible: устанавливает видимость значка в системном трее

Чтобы добавить на форму NotifyIcon, перенесем данный элемент на форму с панели инструментов. После этого добавленный компонент NotifyIcon
отобразится внизу дизайнера формы.

Затем зададим у NotifyIcon для свойства Icon какую-нибудь иконку в формате .ico. И также установим для свойства Visible
значение true.

Далее также зададим у NotifyIcon для свойства Text какой-нибудь текст, например, «Показать форму». Этот текст отобразится при прохождении указателя мыши над
значком NotifyIcon в системном трее.

Чтобы можно было открыть форму по клику на значок в трее, надо обработать событие Click у NotifyIcon. Поэтому в коде формы определим обработчик для
этого события:

public partial class Form1 : Form
{   
    public Form1()
    {
        InitializeComponent();
		
        this.ShowInTaskbar = false;
		notifyIcon1.Click += notifyIcon1_Click;
    }

    void notifyIcon1_Click(object sender, EventArgs e)
    {
        this.WindowState = FormWindowState.Normal;
    }
}

В обработчике просто переводим форму из минимизированного состояния в обычное.

И кроме того, чтобы форма не отображалась на панели задач, у нее задаем свойство ShowInTaskbar = false.

В итоге после запуска приложения в трее будет отображаться значок NotifyIcon, нажав на который при свернутой форме, мы ее можем заново открыть.

Теперь используем всплывающую подсказку. Для этого изменим конструктор формы:

public partial class Form1 : Form
{   
    public Form1()
    {
        InitializeComponent();
		
        this.ShowInTaskbar = false;
		notifyIcon1.Click += notifyIcon1_Click;
		
		// задаем иконку всплывающей подсказки
		notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
		// задаем текст подсказки
        notifyIcon1.BalloonTipText = "Нажмите, чтобы отобразить окно";
		// устанавливаем зголовк
        notifyIcon1.BalloonTipTitle = "Подсказка";
		// отображаем подсказку 12 секунд
        notifyIcon1.ShowBalloonTip(12);
    }

    void notifyIcon1_Click(object sender, EventArgs e)
    {
        this.WindowState = FormWindowState.Normal;
    }
}

И при запуске отобразится всплывающая подсказка:

  • Print
Details
Written by David Corrales
Last Updated: 15 June 2016
Created: 08 May 2012
Hits: 19467

NotifyIcon [System.Windows.Forms.NotifyIcon]

Specifies a component that creates an icon in the notification area of the Window’s taskbar.

Default Event: MouseDoubleClick

Why use a NotifyIcon control?

Use the NotifyIcon control, to alert users of special events, such as when a task is completed. Typically this control is used for informational purposes, but it can also be used as a source for user interaction.

Note: When you add a NotifyIcon it will appear at the bottom of the Designer:

Important Properties:

BalloonTipText

This property sets the text associated with the balloon ToolTip. Use this property to display a message in the Balloon Tooltip.

Setting the BalloonTipText in the script editor:

$NotifyIcon.BalloonTipText ="This is the balloon text"

BalloonTipTitle

This property sets the title of the balloon ToolTip.
The title text is displayed above the balloon text.

BalloonTipIcon

This property sets the icon to associate with the balloon Tooltip. In other words, the icon displayed inside the tooltip itself.
Note: The BalloonTipTitle property must be set in order to view the balloon icon.

Values (Default: None):

None
No icon is displayed.

Info
An information icon.

Warning
A warning icon.

Error
An error icon.

Icon

This property sets the icon to display in the system tray.

Important: This property must be set; otherwise the tooltip balloon will not show!

The designer will allow you to browse and select an icon to display when the tooltip is shown.

Click on the browse button in the Property Panel:

Or use the menu in the designer:

Next select the Icon file

Finally the Icon will be displayed in the system tray:

Note: If a “phantom” icon remains in the system tray after closing the form, then it is recommended set the Visible property to False in order to clear the icon before closing form.

ContextMenuStrip

This property sets the shortcut menu to show when the user right-clicks the icon.
Set this property to an existing ContextMenuStrip in order to assign a menu to the system tray icon. See Spotlight on the ContextMenuStrip Control for more details.

Visible

This property indicates whether the icon is visible in the notification area of the taskbar.

Values (Default: True):

True / False

Important Events:

BalloonTipClicked

This event occurs when the balloon tip is clicked. Use this event to react to user clicks in the ToolTip balloon.

$notifyicon1_BalloonTipClicked={
    Write-Host'The Balloon Tip was Clicked'
}

Clicked & DoubleClicked

These events occur when the system tray icon is clicked. If you need more information such as which mouse button was used, then it is recommended to use the MouseClick events (See below).

MouseClick

This event occurs when a user clicks on the system tray icon.

[System.Windows.Forms.LabelEditEventHandler]

Properties Description
Button Gets which mouse button was pressed.
Clicks Gets the number of times the mouse button was pressed and released.
Delta (Not applicable)
Location Gets the location of the mouse during the generating mouse event.
X Gets the x-coordinate of the mouse during the generating mouse event.
Y Gets the y-coordinate of the mouse during the generating mouse event.
$notifyicon1_MouseClick=[System.Windows.Forms.MouseEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.MouseEventArgs]Write-Host"System Tray Icon Mouse Click: $($_.Button) Clicks: $($_.Clicks)"
}

MouseDoubleClick

These events occur when a user double clicks on a system tray icon. This event has the same arguments as the MouseClick event.

$notifyicon1_MouseDoubleClick=[System.Windows.Forms.MouseEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.MouseEventArgs]Write-Host"System Tray Icon Mouse Double Click: $($_.Button) Clicks: $($_.Clicks)"
}

Important Methods:

ShowBalloonTip

This method displays a balloon tip in the taskbar for the specified time period.

[void] ShowBalloonTip([int] timeout)

Note: The method uses the properties of the NotifyIcon to display the balloon tip. Therefore they must be set before calling this method.

$NotifyIcon.ShowBalloonTip(0)

[void] ShowBalloonTip([int] timeout, [string] tipTitle, [string] tipText, [ToolTipIcon] tipIcon)

Note: This variation, displays a balloon tip with the specified title, text, and icon in the taskbar for the specified time period. You need not set the NotifyIcon’s properties if you use this method variation.

$NotifyIcon.ShowBalloonTip($Timeout, $BalloonTipTitle, $BalloonTipText, $BalloonTipIcon)

Helper Function:

The following is a helper function that allows you to display the NotifyIcon. The help function also assigns the calling executable’s icon, if the NotifyIcon’s Icon property hasn’t been assigned.

functionShow-NotifyIcon
{
<#
    .SYNOPSIS
        Displays a NotifyIcon's balloon tip message in the taskbar's notification area.
    
    .DESCRIPTION
        Displays a NotifyIcon's a balloon tip message in the taskbar's notification area.
        
    .PARAMETER NotifyIcon
         The NotifyIcon control that will be displayed.
    
    .PARAMETER BalloonTipText
         Sets the text to display in the balloon tip.
    
    .PARAMETER BalloonTipTitle
        Sets the Title to display in the balloon tip.
    
    .PARAMETER BalloonTipIcon    
        The icon to display in the ballon tip.
    
    .PARAMETER Timeout    
        The time the ToolTip Balloon will remain visible in milliseconds. 
        Default: 0 - Uses windows default.
#>
    param(
      [Parameter(Mandatory =$true, Position =0)]
      [ValidateNotNull()]
      [System.Windows.Forms.NotifyIcon]$NotifyIcon,
      [Parameter(Mandatory =$true, Position =1)]
      [ValidateNotNullOrEmpty()]
      [String]$BalloonTipText,
      [Parameter(Position =2)]
      [String]$BalloonTipTitle='',
      [Parameter(Position =3)]
      [System.Windows.Forms.ToolTipIcon]$BalloonTipIcon='None',
      [Parameter(Position =4)]
      [int]$Timeout=0
     )
    
    if($NotifyIcon.Icon -eq$null)
    {
        #Set a Default Icon otherwise the balloon will not show$NotifyIcon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon([System.Windows.Forms.Application]::ExecutablePath)
    }
    
    $NotifyIcon.ShowBalloonTip($Timeout, $BalloonTipTitle, $BalloonTipText, $BalloonTipIcon)
}

Example Use:

Show-NotifyIcon-NotifyIcon$notifyicon1-BalloonTipText$textboxText.Text `-BalloonTipTitle$textboxTitle.Text -BalloonTipIcon$combobox1.SelectedItem

You can download the NotifyIcon Sample.

Материал из .Net Framework эксперт

Перейти к: навигация, поиск

NotifyIcon Sample

using System;        
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace NotifyIconExample
{
  /// <summary>
  /// Summary description for NotifyIconForm.
  /// </summary>
  public class NotifyIconForm : System.Windows.Forms.Form
  {
    private System.Windows.Forms.NotifyIcon notifyIcon1;
    private System.Windows.Forms.Button button1;
    private System.ruponentModel.IContainer components;
    public NotifyIconForm()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
      //
      // TODO: Add any constructor code after InitializeComponent call
      //
      this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
    }
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }
    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.ruponents = new System.ruponentModel.Container();
      this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.ruponents);
      this.button1 = new System.Windows.Forms.Button();
      this.SuspendLayout();
      // 
      // notifyIcon1
      // 
      this.notifyIcon1.Icon = new Icon("yourIcon.ico");
      this.notifyIcon1.Text = "Hello from NotifyIconExample";
      // 
      // button1
      // 
      this.button1.Location = new System.Drawing.Point(109, 122);
      this.button1.Name = "button1";
      this.button1.TabIndex = 0;
      this.button1.Text = "Hide in tray";
      this.button1.Click += new System.EventHandler(this.button1_Click);
      // 
      // NotifyIconForm
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 266);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.button1});
      this.Name = "NotifyIconForm";
      this.Text = "NotifyIconForm";
      this.ResumeLayout(false);
    }
    #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new NotifyIconForm());
    }
    private void button1_Click(object sender, System.EventArgs e)
    {
      notifyIcon1.Visible = true;
      this.Visible = false;
    }
    private void notifyIcon1_DoubleClick(object sender, System.EventArgs e)
    {
      notifyIcon1.Visible = false;
      this.Visible = true;
    }
  }
}

Use Timer to update NotifyIcon

using System;
using System.Drawing;
using System.Windows.Forms;
public class NotifyIconTimerUpdate : Form
{
    private Icon[] images = new Icon[8];
    int index = 0;
    public NotifyIconTimerUpdate()
    {
        InitializeComponent();
        images[0] = new Icon("1.ico");
        images[1] = new Icon("2.ico");
        images[2] = new Icon("3.ico");
        images[3] = new Icon("4.ico");
        images[4] = new Icon("5.ico");
        images[5] = new Icon("1.ico");
        images[6] = new Icon("2.ico");
        images[7] = new Icon("3.ico");
    }
    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        notifyIcon.Icon = images[index];
        index++;
        if (index > 7) 
           index = 0;
    }
    [STAThread]
    public static void Main(string[] args)
    {
        Application.Run(new NotifyIconTimerUpdate());
    }
    private System.Windows.Forms.NotifyIcon notifyIcon;
    private System.Timers.Timer timer;
    
    private System.ruponentModel.IContainer components = null;
    private void InitializeComponent()
    {
        this.ruponents = new System.ruponentModel.Container();
        this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.ruponents);
        this.timer = new System.Timers.Timer();
        ((System.ruponentModel.ISupportInitialize)(this.timer)).BeginInit();
        this.SuspendLayout();
        // 
        // notifyIcon
        // 
        this.notifyIcon.Text = "notifyIcon1";
        this.notifyIcon.Visible = true;
        // 
        // timer
        // 
        this.timer.Enabled = true;
        this.timer.Interval = 1000;
        this.timer.SynchronizingObject = this;
        this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
        // 
        // NotifyIconTimerUpdate
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(340, 174);
        ((System.ruponentModel.ISupportInitialize)(this.timer)).EndInit();
        this.ResumeLayout(false);
    }
}

Use Timer to update User interface: NotifyIcon

using System;
using System.Drawing;
using System.Windows.Forms;
public class NotifyIconTimerUpdate : Form
{
    private Icon[] images = new Icon[8];
    int index = 0;
    public NotifyIconTimerUpdate()
    {
        InitializeComponent();
        images[0] = new Icon("1.ico");
        images[1] = new Icon("2.ico");
        images[2] = new Icon("3.ico");
        images[3] = new Icon("4.ico");
        images[4] = new Icon("5.ico");
        images[5] = new Icon("1.ico");
        images[6] = new Icon("2.ico");
        images[7] = new Icon("3.ico");
    }
    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        notifyIcon.Icon = images[index];
        index++;
        if (index > 7) 
           index = 0;
    }
    [STAThread]
    public static void Main(string[] args)
    {
        Application.Run(new NotifyIconTimerUpdate());
    }
    private System.Windows.Forms.NotifyIcon notifyIcon;
    private System.Timers.Timer timer;
    
    private System.ruponentModel.IContainer components = null;
    private void InitializeComponent()
    {
        this.ruponents = new System.ruponentModel.Container();
        this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.ruponents);
        this.timer = new System.Timers.Timer();
        ((System.ruponentModel.ISupportInitialize)(this.timer)).BeginInit();
        this.SuspendLayout();
        // 
        // notifyIcon
        // 
        this.notifyIcon.Text = "notifyIcon1";
        this.notifyIcon.Visible = true;
        // 
        // timer
        // 
        this.timer.Enabled = true;
        this.timer.Interval = 1000;
        this.timer.SynchronizingObject = this;
        this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
        // 
        // NotifyIconTimerUpdate
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(340, 174);
        ((System.ruponentModel.ISupportInitialize)(this.timer)).EndInit();
        this.ResumeLayout(false);
    }
}

Содержание

  • 1 Change icon for NotifyIcon
  • 2 Make NotifyIcon visible
  • 3 NotifyIcon double click event
  • 4 NotifyIcon with Popup Menu

Change icon for NotifyIcon

Imports System.Windows.Forms
Imports System.Drawing
Imports System.Drawing.Drawing2D
public class ChangeNotifyIcon
   public Shared Sub Main
        Application.Run(New Form1)
   End Sub
End class
Public Class Form1
    Private Sub radStop_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles radStop.Click
        nicStatus.Icon = New Icon("1.ico")
    End Sub
    Private Sub radGo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles radGo.Click
        nicStatus.Icon = New Icon("2.ico")
    End Sub
End Class

<Global.Microsoft.VisualBasic.rupilerServices.DesignerGenerated()> _
Partial Public Class Form1
    Inherits System.Windows.Forms.Form
    "Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub
    "Required by the Windows Form Designer
    Private components As System.ruponentModel.IContainer
    "NOTE: The following procedure is required by the Windows Form Designer
    "It can be modified using the Windows Form Designer.  
    "Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.ruponents = New System.ruponentModel.Container
        Me.nicStatus = New System.Windows.Forms.NotifyIcon(Me.ruponents)
        Me.radStop = New System.Windows.Forms.RadioButton
        Me.radGo = New System.Windows.Forms.RadioButton
        Me.SuspendLayout()
        "
        "nicStatus
        "
        Me.nicStatus.Text = "NotifyIcon1"
        Me.nicStatus.Visible = True
        "
        "radStop
        "
        Me.radStop.AutoSize = True
        Me.radStop.Checked = True
        Me.radStop.Location = New System.Drawing.Point(16, 16)
        Me.radStop.Name = "radStop"
        Me.radStop.Size = New System.Drawing.Size(43, 17)
        Me.radStop.TabIndex = 0
        Me.radStop.Text = "Stop"
        "
        "radGo
        "
        Me.radGo.AutoSize = True
        Me.radGo.Location = New System.Drawing.Point(112, 16)
        Me.radGo.Name = "radGo"
        Me.radGo.Size = New System.Drawing.Size(35, 17)
        Me.radGo.TabIndex = 1
        Me.radGo.TabStop = False
        Me.radGo.Text = "Go"
        "
        "Form1
        "
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.radGo)
        Me.Controls.Add(Me.radStop)
        Me.Name = "Form1"
        Me.Text = "UseNotifyIcon"
        Me.ResumeLayout(False)
        Me.PerformLayout()
    End Sub
    Friend WithEvents nicStatus As System.Windows.Forms.NotifyIcon
    Friend WithEvents radStop As System.Windows.Forms.RadioButton
    Friend WithEvents radGo As System.Windows.Forms.RadioButton
End Class

Make NotifyIcon visible

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
public class NotifyIconVisibleDoubleClick
   public Shared Sub Main
        Application.Run(New Form1)
   End Sub
End class
Public Class Form1
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        "This call is required by the Windows Form Designer.
        InitializeComponent()
        "Add any initialization after the InitializeComponent() call
    End Sub
    "Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    "Required by the Windows Form Designer
    Private components As System.ruponentModel.IContainer
    "NOTE: The following procedure is required by the Windows Form Designer
    "It can be modified using the Windows Form Designer.  
    "Do not modify it using the code editor.
    Friend WithEvents NotifyIcon1 As System.Windows.Forms.NotifyIcon
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.ruponents = New System.ruponentModel.Container
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
        Me.NotifyIcon1 = New System.Windows.Forms.NotifyIcon(Me.ruponents)
        Me.Button1 = New System.Windows.Forms.Button
        Me.Label1 = New System.Windows.Forms.Label
        Me.SuspendLayout()
        "
        "NotifyIcon1
        "
        Me.NotifyIcon1.Icon = new System.Drawing.Icon("i.ico")
        Me.NotifyIcon1.Text = "NotifyIcon1"
        "
        "Button1
        "
        Me.Button1.Location = New System.Drawing.Point(88, 88)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(112, 24)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Click Me"
        "
        "Label1
        "
        Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 24.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.Location = New System.Drawing.Point(0, 0)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(216, 48)
        Me.Label1.TabIndex = 1
        Me.Label1.Text = "Notify Icons"
        "
        "Form1
        "
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)
    End Sub
#End Region
    Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick
        MsgBox("You double clicked the notify icon.")
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        NotifyIcon1.Visible = True
    End Sub
End Class

NotifyIcon double click event

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
public class NotifyIconVisibleDoubleClick
   public Shared Sub Main
        Application.Run(New Form1)
   End Sub
End class
Public Class Form1
    Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        "This call is required by the Windows Form Designer.
        InitializeComponent()
        "Add any initialization after the InitializeComponent() call
    End Sub
    "Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    "Required by the Windows Form Designer
    Private components As System.ruponentModel.IContainer
    "NOTE: The following procedure is required by the Windows Form Designer
    "It can be modified using the Windows Form Designer.  
    "Do not modify it using the code editor.
    Friend WithEvents NotifyIcon1 As System.Windows.Forms.NotifyIcon
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.ruponents = New System.ruponentModel.Container
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
        Me.NotifyIcon1 = New System.Windows.Forms.NotifyIcon(Me.ruponents)
        Me.Button1 = New System.Windows.Forms.Button
        Me.Label1 = New System.Windows.Forms.Label
        Me.SuspendLayout()
        "
        "NotifyIcon1
        "
        Me.NotifyIcon1.Icon = new System.Drawing.Icon("i.ico")
        Me.NotifyIcon1.Text = "NotifyIcon1"
        "
        "Button1
        "
        Me.Button1.Location = New System.Drawing.Point(88, 88)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(112, 24)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Click Me"
        "
        "Label1
        "
        Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 24.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.Location = New System.Drawing.Point(0, 0)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(216, 48)
        Me.Label1.TabIndex = 1
        Me.Label1.Text = "Notify Icons"
        "
        "Form1
        "
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)
    End Sub
#End Region
    Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick
        MsgBox("You double clicked the notify icon.")
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        NotifyIcon1.Visible = True
    End Sub
End Class

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
public class NotifyIconWithContextMenu
   public Shared Sub Main
        Application.Run(New Form1)
   End Sub
End class
Public Class Form1
    Inherits System.Windows.Forms.Form
    Public Sub New()
        MyBase.New()
        InitializeComponent()
    End Sub
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    Private components As System.ruponentModel.IContainer
    Friend WithEvents ContextMenu1 As System.Windows.Forms.ContextMenu
    Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem3 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem4 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem5 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem6 As System.Windows.Forms.MenuItem
    Private WithEvents NotifyIcon1 As System.Windows.Forms.NotifyIcon
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.ruponents = New System.ruponentModel.Container
        Me.ContextMenu1 = New System.Windows.Forms.ContextMenu
        Me.NotifyIcon1 = New System.Windows.Forms.NotifyIcon(Me.ruponents)
        Me.MenuItem1 = New System.Windows.Forms.MenuItem
        Me.MenuItem2 = New System.Windows.Forms.MenuItem
        Me.MenuItem3 = New System.Windows.Forms.MenuItem
        Me.MenuItem4 = New System.Windows.Forms.MenuItem
        Me.MenuItem5 = New System.Windows.Forms.MenuItem
        Me.MenuItem6 = New System.Windows.Forms.MenuItem
        "
        "ContextMenu1
        "
        Me.ContextMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem1, Me.MenuItem2, Me.MenuItem3})
        "
        "NotifyIcon1
        "
        Me.NotifyIcon1.ContextMenu = Me.ContextMenu1
        Me.NotifyIcon1.Icon = new System.Drawing.Icon("1.ico")
        Me.NotifyIcon1.Text = "NotifyIcon1"
        Me.NotifyIcon1.Visible = True
        "
        "MenuItem1
        "
        Me.MenuItem1.Index = 0
        Me.MenuItem1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem4, Me.MenuItem5, Me.MenuItem6})
        Me.MenuItem1.Text = "A"
        "
        "MenuItem2
        "
        Me.MenuItem2.Index = 1
        Me.MenuItem2.Text = "B"
        "
        "MenuItem3
        "
        Me.MenuItem3.Index = 2
        Me.MenuItem3.Text = "C"
        "
        "MenuItem4
        "
        Me.MenuItem4.Index = 0
        Me.MenuItem4.Text = "D"
        "
        "MenuItem5
        "
        Me.MenuItem5.Index = 1
        Me.MenuItem5.Text = "E"
        "
        "MenuItem6
        "
        Me.MenuItem6.Index = 2
        Me.MenuItem6.Text = "F"
        "
        "Form1
        "
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
    End Sub

End Class

This C# tutorial shows how to use the NotifyIcon control in Windows Forms.

NotifyIcon. A notification icon notifies the user.

In Windows there is a Notification Icons section—typically in the bottom right corner. With the NotifyIcon control in Windows Forms, you can add an icon of your own there and hook C# code up to it.

Example. First, please add the NotifyIcon control to your program by double-clicking on the NotifyIcon entry in the Toolbox in Visual Studio. Right click on the notifyIcon1 icon and select Properties.

And: There you can add the MouseDoubleClick event handler, and set some properties such as BalloonTipText and Text.

Example that demonstrates NotifyIcon: C#

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
	    // When the program begins, show the balloon on the icon for one second.
	    notifyIcon1.ShowBalloonTip(1000);
	}

	private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
	{
	    // When icon is double-clicked, show this message.
	    MessageBox.Show("Doing something important on double-click...");
	    // Then, hide the icon.
	    notifyIcon1.Visible = false;
	}
    }
}

Calling ShowBalloonTip. This example uses the Load event on the enclosing form to show a balloon tip. This means that when the program starts up, the balloon will automatically show.

Note: Balloons are more prominent notifications but don’t interrupt the workflow of the user as much as dialogs.

MouseDoubleClick event handler. In this program, when you double-click on the logo in the bottom right, you will get a dialog box. Then, the icon will vanish from the screen, never to be seen again.

Icon. How can you change the icon? Simply go into Properties and then click on the Icon entry. You need to use an .ico file. If you do not have this kind of file format, you can make one with favicon converters on the Internet.

Tip: Search Google for «favicon generator» and then send in your PNG or GIF file.

Balloons. When the ShowBalloon method is invoked, the balloon will appear on the screen. At this time, you should have already set the BalloonTipText and BalloonTipTitle properties in Visual Studio.

Also: The BalloonTipIcon property gives you the ability to render an icon on the balloon.

Text. Another useful property you can set on the NotifyIcon is the Text property. This is rendered as a tooltip. When you hover the mouse over the icon, the string from the Text property will appear.

Text

Summary. For programs that require ongoing notifications, NotifyIcon can help integrate into the operating system with this functionality. By combining the NotifyIcon with the balloon, you can introduce attention-grabbing warnings or messages.


Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows movie maker характеристика программы
  • Как на windows 10 сменить пользователя на администратора
  • Можно ли мышку apple подключить к windows
  • Как сделать выключение пк по таймеру windows 10
  • Установка домена active directory в windows server 2019