Thursday, August 23, 2012

NotifyIcon with WPF applications

NotifyIcon is an utility form System.Windows.Forms which can be used by any application to invoke the default notification from the system tray. As per my latest requirement, I have to create an application that runs on system tray and occationally shows notification using the system tray default notifications. While working with it, I have wasted a considerable amount of time, and thought it would be worth mentioning the same in a blog.



Steps :

1. Start a WPF Application and add Reference to System.Windows.Forms and System.Drawing to the project.
2. Create an instance of NotifyIcon on the Code behind of the WPF application.
3. Specify the Icon property for the NotifyIcon.
Remember, you should specify the Icon property as it is a mandatory before you can show notifyIcons from the application.
4. Make the NotifyIcon visible.
5. Call ShowBallonTip after minimizing the window to System Tray.

In my sample application, I have just created one button on the Window and when it is clicked, I show up a notifyIcon on the system tray.


<Window x:Class="NotifyIconSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Click="Button_Click" Content="Click to Open" />
    </Grid>
</Window>



Code :


 NotifyIcon nIcon = new NotifyIcon();
        public MainWindow()
        {
            InitializeComponent();
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
            this.nIcon.Icon = new Icon(@"../../Cartman-General.ico");
            this.nIcon.ShowBalloonTip(5000, "Hi""This is a BallonTip from Windows Notification"ToolTipIcon.Info);
            
        }


Note : I have wasted lot of time just to ensure that the Icon property is mandatory for the NotifyIcon to work on. So it is important to note that you must specify it before using it.

No comments:

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!