using System; using System.Net.NetworkInformation; using System.Diagnostics; using System.Windows.Forms; using SystemTrayApp.Properties; using System.Reflection; namespace SystemTrayApp { /// /// /// class ProcessIcon : IDisposable { /// /// The NotifyIcon object. /// NotifyIcon ni; /// /// Initializes a new instance of the class. /// public ProcessIcon() { // Instantiate the NotifyIcon object. ni = new NotifyIcon(); } /// /// Displays the icon in the system tray. /// /// public static void SetNotifyIconText(NotifyIcon ni, string text) { if (text.Length >= 128) throw new ArgumentOutOfRangeException("Text limited to 127 characters"); Type t = typeof(NotifyIcon); BindingFlags hidden = BindingFlags.NonPublic | BindingFlags.Instance; t.GetField("text", hidden).SetValue(ni, text); if ((bool)t.GetField("added", hidden).GetValue(ni)) t.GetMethod("UpdateIcon", hidden).Invoke(ni, new object[] { true }); } public void Display() { // Put the icon in the system tray and allow it react to mouse clicks. ni.MouseClick += new MouseEventHandler(ni_MouseClick); ni.Icon = Resources.SystemTrayApp; String IconDisplayText = null; IconDisplayText = System.Environment.MachineName + Environment.NewLine; IconDisplayText = IconDisplayText + Environment.OSVersion + Environment.NewLine; IconDisplayText = IconDisplayText + Environment.UserName + Environment.NewLine; SetNotifyIconText(ni, IconDisplayText); ni.Visible = true; // Attach a context menu. ni.ContextMenuStrip = new ContextMenus().Create(); } /// /// Releases unmanaged and - optionally - managed resources /// public void Dispose() { // When the application closes, this will remove the icon from the system tray immediately. ni.Dispose(); } /// /// Handles the MouseClick event of the ni control. /// /// The source of the event. /// The instance containing the event data. void ni_MouseClick(object sender, MouseEventArgs e) { // Handle mouse button clicks. if (e.Button == MouseButtons.Left) { // Start Windows Explorer. // Process.Start("explorer", null); } } } }