Tuesday 17 April 2012

Notify Icon In WPF applications

   Notify icon has been a real serious issue for me when I migrated from windows forms to WPF. While creating Notify icon is so simple for Windows applications, it is not the same for a WPF application. Searches in net revealed the installation of some libraries, changing the Forms notify icon to suit WPF etc.. All these codes belong to the authors and we cannot simply use it for royalty free.

   So basically I figured out a simple one line code for using notify icon in WPF. And it greatly works for me. If this suit you feel free to use this technique, else just ignore this if you a genius already. So here we go.

  Create a System.Windows.Forms.NotifyIcon object and enable its visibility. This will give a notify icon we needed and that is simple. Now we should add a WPF context menu for this icon.



Adding  a WPF context menu can be much simpler too. First create the required wpf context menu in the XAML code behind as usual. And give a name to this context menu say contextmenu1. Now add the below kind of code to the notify icon's click event.



Now if we right click the notify icon the context menu of  WPF style will pop up. And if we right click again the context menu will disappear. But this would not be convenient to the users. The context menu should disappear like in usual cases. So that is why the line this.Activate();  is present in the above code. So we activate the WPF main form when the context menu opens. And when we main window gets deactivated we will close the context menu as below.

 


And hence we achieve a WPF with notify icon and context menu. Try this and let me know your comments.

1 comment:

  1. This was exactly the fix I was looking for! Thanks for posting this!!

    ReplyDelete