Click here to Skip to main content
15,893,588 members
Articles / Programming Languages / C#

.NET DUMeter clone

Rate me:
Please Sign up or sign in to vote.
4.86/5 (47 votes)
10 Feb 2003BSD4 min read 345.5K   7.4K   111  
A DUMeter clone, but with some better/different reporting features.
//#define WIP

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Threading;

namespace MyDUMeter
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class MainForm : System.Windows.Forms.Form
	{
      private System.Windows.Forms.Timer timer1;
      private System.ComponentModel.IContainer components;
      private System.Diagnostics.PerformanceCounter performanceCounter1;
      private System.Diagnostics.PerformanceCounter performanceCounter2;
      private System.Diagnostics.PerformanceCounter performanceCounter3;
      private System.Windows.Forms.PictureBox pictureBox1;
      private System.Windows.Forms.ContextMenu contextMenu1;
      private System.Windows.Forms.NotifyIcon notifyIcon1;
      private System.Windows.Forms.MenuItem menuItem5;
      private System.Windows.Forms.MenuItem menuItem6;
      private System.Windows.Forms.MenuItem menuItem7;
      private System.Windows.Forms.MenuItem menuItem8;
      private System.Windows.Forms.MenuItem menuItem1;
      private MyDUMeter.Log log1;
      private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1;
      private System.Data.OleDb.OleDbConnection oleDbConnection1;
      private System.Data.OleDb.OleDbCommand oleDbSelectCommand1;
      private System.Data.OleDb.OleDbCommand oleDbInsertCommand1;
      private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1;
      private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1;
 
      Bitmap bit;
      int linespeed = 16 * 1024;
      private System.Windows.Forms.MenuItem menuItem2;
      private System.Windows.Forms.MenuItem menuItem3;
      private System.Windows.Forms.MenuItem menuItem4;
      private System.Windows.Forms.MenuItem menuItem9;
      private System.Windows.Forms.MenuItem menuItem10;
      private System.Windows.Forms.MenuItem menuItem11;
      private System.Windows.Forms.MenuItem menuItem12;
      //Bitmap icon;

      ControlOptions options;
      
		public MainForm()
		{
			InitializeComponent();

         options = new ControlOptions();

         if (!(File.Exists("log.mdb")))
         {
            Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyDUMeter.log.mdb");
            Stream r = File.Create("log.mdb");
            int len = 8192;
            byte[] buffer = new byte[len];
            while (len > 0)
            {
               len = s.Read(buffer, 0, len);
               r.Write(buffer, 0, len);
            }
            r.Close();
            s.Close();
         }          
#if(DEBUG)
#else
         oleDbConnection1.ConnectionString = 
            "Provider=Microsoft.Jet.OLEDB.4.0;Password=\"\";User ID=Admin;Data Source=" + 
            "log.mdb;Mode=Share Deny None;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Database Password=\"\";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False";
#endif
         Application.ApplicationExit += new EventHandler(this.AppExit);
         bit = new Bitmap(pictureBox1.Width, pictureBox1.Height);
         notifyIcon1.Icon = Icon;
         //icon = Icon.ToBitmap();
         //any more and it sucks too much CPU
         timer1.Interval = 500;
         recvallq = new FixedSizeQueue(Screen.PrimaryScreen.Bounds.Width);
         sendallq = new FixedSizeQueue(Screen.PrimaryScreen.Bounds.Width);
		}


		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
            StopPing();
            up.Dispose();
            down.Dispose();
            both.Dispose();
            h.Dispose();
            //icon.Dispose();

				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.components = new System.ComponentModel.Container();
         System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
         this.timer1 = new System.Windows.Forms.Timer(this.components);
         this.performanceCounter1 = new System.Diagnostics.PerformanceCounter();
         this.performanceCounter2 = new System.Diagnostics.PerformanceCounter();
         this.performanceCounter3 = new System.Diagnostics.PerformanceCounter();
         this.pictureBox1 = new System.Windows.Forms.PictureBox();
         this.contextMenu1 = new System.Windows.Forms.ContextMenu();
         this.menuItem5 = new System.Windows.Forms.MenuItem();
         this.menuItem6 = new System.Windows.Forms.MenuItem();
         this.menuItem2 = new System.Windows.Forms.MenuItem();
         this.menuItem3 = new System.Windows.Forms.MenuItem();
         this.menuItem10 = new System.Windows.Forms.MenuItem();
         this.menuItem11 = new System.Windows.Forms.MenuItem();
         this.menuItem4 = new System.Windows.Forms.MenuItem();
         this.menuItem9 = new System.Windows.Forms.MenuItem();
         this.menuItem1 = new System.Windows.Forms.MenuItem();
         this.menuItem12 = new System.Windows.Forms.MenuItem();
         this.menuItem7 = new System.Windows.Forms.MenuItem();
         this.menuItem8 = new System.Windows.Forms.MenuItem();
         this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
         this.log1 = new MyDUMeter.Log();
         this.oleDbDataAdapter1 = new System.Data.OleDb.OleDbDataAdapter();
         this.oleDbDeleteCommand1 = new System.Data.OleDb.OleDbCommand();
         this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
         this.oleDbInsertCommand1 = new System.Data.OleDb.OleDbCommand();
         this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
         this.oleDbUpdateCommand1 = new System.Data.OleDb.OleDbCommand();
         ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
         ((System.ComponentModel.ISupportInitialize)(this.performanceCounter2)).BeginInit();
         ((System.ComponentModel.ISupportInitialize)(this.performanceCounter3)).BeginInit();
         ((System.ComponentModel.ISupportInitialize)(this.log1)).BeginInit();
         this.SuspendLayout();
         // 
         // timer1
         // 
         this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
         // 
         // performanceCounter1
         // 
         this.performanceCounter1.CategoryName = "Network Interface";
         this.performanceCounter1.CounterName = "Bytes Received/sec";
         // 
         // performanceCounter2
         // 
         this.performanceCounter2.CategoryName = "Network Interface";
         this.performanceCounter2.CounterName = "Bytes Sent/sec";
         // 
         // performanceCounter3
         // 
         this.performanceCounter3.CategoryName = "Processor";
         this.performanceCounter3.CounterName = "% Processor Time";
         // 
         // pictureBox1
         // 
         this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
         this.pictureBox1.ContextMenu = this.contextMenu1;
         this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
         this.pictureBox1.Name = "pictureBox1";
         this.pictureBox1.Size = new System.Drawing.Size(180, 60);
         this.pictureBox1.TabIndex = 0;
         this.pictureBox1.TabStop = false;
         this.pictureBox1.Resize += new System.EventHandler(this.pictureBox1_Resize);
         this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
         this.pictureBox1.MouseHover += new System.EventHandler(this.pictureBox1_MouseHover);
         this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
         this.pictureBox1.DoubleClick += new System.EventHandler(this.pictureBox1_DoubleClick);
         this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);
         this.pictureBox1.MouseLeave += new System.EventHandler(this.pictureBox1_MouseLeave);
         this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
         // 
         // contextMenu1
         // 
         this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                     this.menuItem5,
                                                                                     this.menuItem6,
                                                                                     this.menuItem2,
                                                                                     this.menuItem1,
                                                                                     this.menuItem12,
                                                                                     this.menuItem7,
                                                                                     this.menuItem8});
         // 
         // menuItem5
         // 
         this.menuItem5.Index = 0;
         this.menuItem5.Text = "Options";
         this.menuItem5.Click += new System.EventHandler(this.menuItem1_Click);
         // 
         // menuItem6
         // 
         this.menuItem6.Index = 1;
         this.menuItem6.Text = "Hide";
         this.menuItem6.Click += new System.EventHandler(this.menuItem2_Click);
         // 
         // menuItem2
         // 
         this.menuItem2.Index = 2;
         this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                  this.menuItem3,
                                                                                  this.menuItem10,
                                                                                  this.menuItem11,
                                                                                  this.menuItem4,
                                                                                  this.menuItem9});
         this.menuItem2.Text = "Reports";
         // 
         // menuItem3
         // 
         this.menuItem3.Index = 0;
         this.menuItem3.Text = "Last Hour";
         this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click_1);
         // 
         // menuItem10
         // 
         this.menuItem10.Index = 1;
         this.menuItem10.Text = "Last 3 hours";
         this.menuItem10.Click += new System.EventHandler(this.menuItem10_Click_1);
         // 
         // menuItem11
         // 
         this.menuItem11.Index = 2;
         this.menuItem11.Text = "Last 6 hours";
         this.menuItem11.Click += new System.EventHandler(this.menuItem11_Click);
         // 
         // menuItem4
         // 
         this.menuItem4.Index = 3;
         this.menuItem4.Text = "Last 12 hours";
         this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click_1);
         // 
         // menuItem9
         // 
         this.menuItem9.Index = 4;
         this.menuItem9.Text = "Last 24 hours";
         this.menuItem9.Click += new System.EventHandler(this.menuItem9_Click);
         // 
         // menuItem1
         // 
         this.menuItem1.Index = 3;
         this.menuItem1.Text = "Show Text";
         this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click_1);
         // 
         // menuItem12
         // 
         this.menuItem12.Index = 4;
         this.menuItem12.RadioCheck = true;
         this.menuItem12.Text = "Start Ping";
         this.menuItem12.Click += new System.EventHandler(this.menuItem12_Click);
         // 
         // menuItem7
         // 
         this.menuItem7.Index = 5;
         this.menuItem7.Text = "About";
         this.menuItem7.Click += new System.EventHandler(this.menuItem4_Click);
         // 
         // menuItem8
         // 
         this.menuItem8.Index = 6;
         this.menuItem8.Text = "Exit";
         this.menuItem8.Click += new System.EventHandler(this.menuItem3_Click);
         // 
         // notifyIcon1
         // 
         this.notifyIcon1.Text = "";
         this.notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click);
         // 
         // log1
         // 
         this.log1.DataSetName = "Log";
         this.log1.Locale = new System.Globalization.CultureInfo("en-ZA");
         this.log1.Namespace = "http://www.tempuri.org/Log.xsd";
         // 
         // oleDbDataAdapter1
         // 
         this.oleDbDataAdapter1.DeleteCommand = this.oleDbDeleteCommand1;
         this.oleDbDataAdapter1.InsertCommand = this.oleDbInsertCommand1;
         this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
         this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
                                                                                                    new System.Data.Common.DataTableMapping("Table", "RateLog", new System.Data.Common.DataColumnMapping[] {
                                                                                                                                                                                                              new System.Data.Common.DataColumnMapping("ID", "ID"),
                                                                                                                                                                                                              new System.Data.Common.DataColumnMapping("Recv", "Recv"),
                                                                                                                                                                                                              new System.Data.Common.DataColumnMapping("Send", "Send")})});
         this.oleDbDataAdapter1.UpdateCommand = this.oleDbUpdateCommand1;
         // 
         // oleDbDeleteCommand1
         // 
         this.oleDbDeleteCommand1.CommandText = "DELETE FROM RateLog WHERE (ID = ?)";
         this.oleDbDeleteCommand1.Connection = this.oleDbConnection1;
         this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ID", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ID", System.Data.DataRowVersion.Original, null));
         // 
         // oleDbConnection1
         // 
         this.oleDbConnection1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=D:\dev\MyDUMeter\MyDUMeter\bin\Release\log.mdb;Mode=Share Deny None;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False";
         // 
         // oleDbInsertCommand1
         // 
         this.oleDbInsertCommand1.CommandText = "INSERT INTO RateLog (Recv, Send) VALUES (?, ?)";
         this.oleDbInsertCommand1.Connection = this.oleDbConnection1;
         this.oleDbInsertCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Recv", System.Data.OleDb.OleDbType.Single, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(7)), ((System.Byte)(0)), "Recv", System.Data.DataRowVersion.Current, null));
         this.oleDbInsertCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Send", System.Data.OleDb.OleDbType.Single, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(7)), ((System.Byte)(0)), "Send", System.Data.DataRowVersion.Current, null));
         // 
         // oleDbSelectCommand1
         // 
         this.oleDbSelectCommand1.CommandText = "SELECT ID, Recv, Send FROM RateLog WHERE (ID > ?)";
         this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
         this.oleDbSelectCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("ID", System.Data.OleDb.OleDbType.DBDate, 0, "ID"));
         // 
         // oleDbUpdateCommand1
         // 
         this.oleDbUpdateCommand1.CommandText = "UPDATE RateLog SET ID = ?, Recv = ?, Send = ? WHERE (ID = ?)";
         this.oleDbUpdateCommand1.Connection = this.oleDbConnection1;
         this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("ID", System.Data.OleDb.OleDbType.Integer, 0, "ID"));
         this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Recv", System.Data.OleDb.OleDbType.Single, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(7)), ((System.Byte)(0)), "Recv", System.Data.DataRowVersion.Current, null));
         this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Send", System.Data.OleDb.OleDbType.Single, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(7)), ((System.Byte)(0)), "Send", System.Data.DataRowVersion.Current, null));
         this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ID", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ID", System.Data.DataRowVersion.Original, null));
         // 
         // MainForm
         // 
         this.AutoScaleBaseSize = new System.Drawing.Size(18, 39);
         this.ClientSize = new System.Drawing.Size(180, 60);
         this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                      this.pictureBox1});
         this.Font = new System.Drawing.Font("Tahoma", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
         this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
         this.HelpButton = true;
         this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
         this.Name = "MainForm";
         this.ShowInTaskbar = false;
         this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
         this.Text = "MyDUMeter";
         this.TopMost = true;
         this.Load += new System.EventHandler(this.Form1_Load);
         this.Move += new System.EventHandler(this.Form1_Move);
         ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
         ((System.ComponentModel.ISupportInitialize)(this.performanceCounter2)).EndInit();
         ((System.ComponentModel.ISupportInitialize)(this.performanceCounter3)).EndInit();
         ((System.ComponentModel.ISupportInitialize)(this.log1)).EndInit();
         this.ResumeLayout(false);

      }
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new MainForm());
		}

      private void timer1_Tick(object sender, System.EventArgs e)
      {
          LogData();
      }
 
      static ArrayList rl = new ArrayList();
      static ArrayList sl = new ArrayList();

      private float GetAvg(ArrayList log)
      {
         float tot = 0;
         foreach (float n in log)
            tot += n;
         float avg = tot/log.Count;
         log.Clear();
         return avg;
      }

      static int logcounter = 0;

      Queue recvallq;
      Queue sendallq;

      private void LogData()
      {
         
         if (logcounter < 1000/timer1.Interval)
         {
            try 
            {
               rl.Add( performanceCounter1.NextValue());
               sl.Add( performanceCounter2.NextValue());
               logcounter++;
            } 
            catch (System.InvalidOperationException){}
            catch (Exception ex)
            {
               Console.WriteLine(ex);
            }
         }
         else 
         {
            DrawGraph();
            logcounter = 0;
            LogData();
         }
      }

      Pen up;
      Pen down;
      Pen both;
      Pen h;
      Brush textc;

      int minutec = 0;

      private float GetLastValues(Queue queue, int count)
      {
         object[] x = queue.ToArray();
         float total = 0;
         for (int i = (x.Length > count) ? x.Length - count : 0 ; i < x.Length; i++)
         {
            total += (float)x[i];
         }
         return total;
      }

      private class FixedSizeQueue : Queue 
      {
         int maxcap;
         public FixedSizeQueue(int maxcap):base(maxcap)
         {
            this.maxcap = maxcap;
         }
         public override void Enqueue(object obj)
         {
            if (Count == maxcap)
               this.Dequeue();
            base.Enqueue(obj);
         }
      }

      int hidecounter = 0;

      private void DrawGraph()
      {
         Graphics g = Graphics.FromImage(bit);
         g.Clear(options.Background);
         
         float recv = GetAvg(rl)/linespeed;
         float send = GetAvg(sl)/linespeed;

         recvallq.Enqueue(recv);
         sendallq.Enqueue(send);
         
         if (options.HideWhenIdle)
         {
            if (GetLastValues(sendallq, 10) == 0 & GetLastValues(recvallq, 10) == 0 & hidecounter++ >= 10)
            {
               HideForm(false);
            }
            else ShowForm();
         }

         if (minutec == 59)
         {
            oleDbInsertCommand1.Parameters["Recv"].Value = GetLastValues(recvallq, 60) * linespeed;
            oleDbInsertCommand1.Parameters["Send"].Value = GetLastValues(sendallq, 60) * linespeed;

            oleDbConnection1.Open();
            oleDbInsertCommand1.ExecuteNonQuery();
            oleDbConnection1.Close();

            minutec = 0;
         }
         else 
         {
            minutec++;
         }

         Text = "Down: " + (recv*linespeed/1024).ToString("f1") + " Up: " + 
            (send*linespeed/1024).ToString("f1");
         notifyIcon1.Text = Text;

         object[] rf = recvallq.ToArray();
         object[] sf = sendallq.ToArray();

         for (int i = 0; i < bit.Width & i < rf.Length; i++)
         { 
            float recv2 = (float)rf[rf.Length - (1 + i)];
            float send2 = (float)sf[sf.Length - (1 + i)];
            float maxr = recv2;
            float minr = send2;
            Pen p = down;
            if (recv2 < send2)
            {
               p = up;
               maxr = send2;
               minr = recv2;
            }
         
            Pen s = both;

            int max = Convert.ToInt32(bit.Height - (maxr * bit.Height / (1 + options.Overflow)));
            int min = Convert.ToInt32(bit.Height - (minr * bit.Height  / (1 + options.Overflow)));

            if (max < 0)
               max = 0;
            if (min < 0)
               min = 0;

            g.DrawLine(p,
               bit.Width - i - 1, bit.Height, 
               bit.Width - i - 1, max);
         
            g.DrawLine(s,
               bit.Width - i - 1, bit.Height, 
               bit.Width - i - 1, min);
         }

         pictureBox1.Image = bit; 
#if(WIP)
         //notify icon stuff
         icon = notifyIcon1.Icon.ToBitmap();
         Graphics g2 = Graphics.FromImage(icon);
         g2.Clear(Color.DimGray);
         //g2.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
         g2.FillRectangle(up.Brush, 0, icon.Height, icon.Width/2F, icon.Height * (1 - recv));
         g2.FillRectangle(down.Brush, icon.Width/2F, icon.Height, icon.Width, icon.Height * (1 - send));
         Font f = new Font(Font.FontFamily, 8, GraphicsUnit.Pixel);
         g2.DrawString((recv*linespeed/1024).ToString("f1"), 
            f, 
            Brushes.White, 0, 0);
         notifyIcon1.Icon = Icon.FromHandle(icon.GetHicon());

         
         g2.Dispose();
         f.Dispose();
#endif
         g.Dispose();
         
      }

      private void pictureBox1_Resize(object sender, System.EventArgs e)
      {
         bit = new Bitmap(bit, pictureBox1.Size);
         options.Size = Size;
      }

      bool mousedown = false;
      Point mousept;

      private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
      {
         switch (e.Button)
         {
            case MouseButtons.Left:
               Cursor = Cursors.SizeAll;
               mousept = new Point(e.X, e.Y);
               mousedown = true;
               break;
          }
         //clear the counter so it wont hide so quick
         hidecounter = 0;
      }

      private void pictureBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
      {
         if (mousedown)
         {
            Opacity = options.Transparency - 0.3F;
            Location = new Point(Location.X - (mousept.X - e.X), Location.Y - (mousept.Y - e.Y)); 
         }
      }

      private void pictureBox1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
      {      
         if (e.Button == MouseButtons.Left)
         {
            Cursor = Cursors.Default;
            mousedown = false;
            Opacity = options.Transparency;
         }
      }

      private void menuItem1_Click(object sender, System.EventArgs e)
      {
         ShowOptions();
      }

      private void ShowOptions()
      {
         OptionForm opt = new OptionForm(options);
         opt.ShowDialog(this);
         opt.Dispose();
         if (options.Interface == "")
            ShowOptions();
         else 
         {
            Options.Save("MyDUMeter.config", options);
            ReApplyOptions();
         }
      }

      private void ReApplyOptions()
      {
         performanceCounter1.InstanceName = options.Interface;
         performanceCounter2.InstanceName = options.Interface;
         performanceCounter1.MachineName = options.MachineName;
         performanceCounter2.MachineName = options.MachineName;
         linespeed = (int)options.LineSpeed/8;
         Opacity = options.Transparency;
         Location = options.Location;
         if (options.AlwaysShowText)
            menuItem1.Text = "Hide Text";
         else
            menuItem1.Text = "Show Text";
         Size = options.Size;
         if (up != null) up.Dispose();
         if (down != null) down.Dispose();
         if (both != null) both.Dispose();
         if (textc != null) textc.Dispose();
         if (h != null) h.Dispose();
         up = new Pen(options.Up);
         down = new Pen(options.Down);
         both = new Pen(options.Both);
         textc = new SolidBrush(options.Text);
         h = new Pen(options.Lines);
      }

      private void menuItem3_Click(object sender, System.EventArgs e)
      {
         Application.Exit();
      }

      private void AppExit(object sender, EventArgs e)
      {
         Options.Save("MyDUMeter.config", options);
      }

      private void Form1_Move(object sender, System.EventArgs e)
      {
         options.Location = Location;
      }

      private void Form1_Load(object sender, System.EventArgs e)
      {
         try 
         {
            Options.Load("MyDUMeter.config", options);
            ReApplyOptions();
         }
         catch (System.IO.FileNotFoundException)
         {
            ShowOptions();
         }
         finally
         {
            timer1.Start();
         }       
      }

      private void menuItem4_Click(object sender, System.EventArgs e)
      {
         MessageBox.Show(this, "MyDUMeter by leppie (c)2003\nllewellyn@pritchard.org", "About...",
            MessageBoxButtons.OK, MessageBoxIcon.Information);
      }

      private void menuItem2_Click(object sender, System.EventArgs e)
      {
         HideForm(true);
      }

      private void HideForm(bool force)
      {
         if (Visible)
         {
            if (force) hidecounter = 10;
            notifyIcon1.Visible = true;
            this.Hide();
         }
      }

      private void ShowForm()
      {
         if (!Visible)
         {
            hidecounter = 0;
            notifyIcon1.Visible = false;
            this.Show();
         }
      }

      private void notifyIcon1_Click(object sender, System.EventArgs e)
      {
         ShowForm();
      }

      private void pictureBox1_DoubleClick(object sender, System.EventArgs e)
      {
         if (FormBorderStyle != FormBorderStyle.SizableToolWindow)
            FormBorderStyle = FormBorderStyle.SizableToolWindow;
         else 
            FormBorderStyle = FormBorderStyle.None;
      }

      static bool hover = false;

      private void pictureBox1_MouseHover(object sender, System.EventArgs e)
      {
         hover = true;
      }

      private void pictureBox1_MouseLeave(object sender, System.EventArgs e)
      {
         hover = false;
      }

      private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
      {
         h.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
         e.Graphics.DrawLine(h,
            0, Convert.ToInt32(bit.Height * (options.Overflow)),
            bit.Width, Convert.ToInt32(bit.Height * (options.Overflow))
            );

         h.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
         for (int i = 0; i < bit.Width; i+=60)
         {
            e.Graphics.DrawLine(h,
               bit.Width - i, 0 , bit.Width - i, bit.Height);
         }

         if (hover | options.AlwaysShowText)
         {
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            
            SizeF s = e.Graphics.MeasureString(Text, Font);

            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            Font font = new Font(Font.FontFamily, Font.Size*(e.ClipRectangle.Width/s.Width));
            e.Graphics.DrawString(Text, 
               font,
               textc, e.ClipRectangle, sf);
            if (pinging)
            {
               sf.LineAlignment = StringAlignment.Far;

               e.Graphics.DrawString(lastping + "ms", 
                  font,
                  textc, e.ClipRectangle, sf);
            }
            sf.Dispose();
            font.Dispose();
         }
      }

      private void menuItem1_Click_1(object sender, System.EventArgs e)
      {
         if (options.AlwaysShowText)
         {
            options.AlwaysShowText = false;
            menuItem1.Text = "Show Text";
         }
         else 
         {
            options.AlwaysShowText = true;
            menuItem1.Text = "Hide Text";
         }
      }

      private void menuItem3_Click_1(object sender, System.EventArgs e)
      {
         MakeReport(1);
      }

      private void MakeReport(int from)
      {
         oleDbSelectCommand1.Parameters["ID"].Value = DateTime.Now.AddHours(-from);
         int res = oleDbDataAdapter1.Fill(log1.RateLog);
         ReportForm report = new ReportForm(from, log1.RateLog, linespeed);
         report.Show();
      }

      private void menuItem4_Click_1(object sender, System.EventArgs e)
      {
         MakeReport(12);
      }

      private void menuItem9_Click(object sender, System.EventArgs e)
      {
         MakeReport(24);
      }

      private void menuItem10_Click(object sender, System.EventArgs e)
      {
         MakeReport(72);
      }

      private void menuItem10_Click_1(object sender, System.EventArgs e)
      {
         MakeReport(3);
      }

      private void menuItem11_Click(object sender, System.EventArgs e)
      {
         MakeReport(6);
      }

      Thread thread;
      bool pinging = false;

      private void StopPing()
      {
         if (pinging)
         {
            SaurabhPing.Ping.PingReply -= new SaurabhPing.Ping.PingEventHandler(OnPing);
            thread.Abort();
            thread = null;
            menuItem12.Text = "Start ping";
            pinging = false;
         }
      }

      private void StartPing()
      {
         if (thread == null)
            InitThread();

         SaurabhPing.Ping.PingReply += new SaurabhPing.Ping.PingEventHandler(OnPing);
         menuItem12.Text = "Stop ping";
         pinging = true;
         thread.Start();
      }

      int lastping = 0;

      private void StartPingThread()
      {
         while(true)
         {
            Thread.Sleep(options.PingInterval);
            ThreadPool.QueueUserWorkItem(  
               new WaitCallback(SaurabhPing.Ping.PingHost), options.PingEndPoint);
         }
      }

      private void OnPing(System.Net.EndPoint ep, int ms, int bytes)
      {
         lastping = ms;
      }

      private void menuItem12_Click(object sender, System.EventArgs e)
      {
         if (pinging)
            StopPing();
         else
            StartPing();
      }

      private void InitThread()
      {
         thread = new Thread(new ThreadStart(StartPingThread));
         thread.Name = "Pinger";
         thread.ApartmentState = ApartmentState.STA;
      }
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions