ICanSpy

A Windows Forms Spy app! Dynamically binds to an assembly and lets you spy on which events are being raised. The .zip file includes an .exe and source.

C# (86.3 KB)
 
 
 
 
 
(0)
2,833 times
Add to favorites
3/1/2011
E-mail Twitter del.icio.us Digg Facebook
using System;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Threading;

namespace EventTestDriver
{
	public class FormMain : System.Windows.Forms.Form
	{
        private System.Windows.Forms.MainMenu mainMenu1;
        private System.Windows.Forms.MenuItem menuFile;
        private System.Windows.Forms.MenuItem menuSelectForm;
        private System.Windows.Forms.MenuItem menuSelectEvents;
        private System.Windows.Forms.MenuItem menuLoggingOptions;
        private System.Windows.Forms.MenuItem menuLoggingStatus;
        private System.Windows.Forms.MenuItem menuClearLogList;
        private System.Windows.Forms.MenuItem menuFileExit;
        private System.Windows.Forms.MenuItem menuHelp;
        private System.Windows.Forms.MenuItem menuHelpAbout;

        private Form _formTest;
        private TreeView _tvEvents;
        private bool _orderByControl;
		private bool _listening;
		private bool _log;
		private bool _appendLog;
        private bool _logFileOpened;
		private string _logFilename;
		private string _logHeader;
        private System.Windows.Forms.ToolBar tb;
        private System.Windows.Forms.ToolBarButton tbbSelectForm;
        private System.Windows.Forms.ToolBarButton tbbLoggingOptions;
        private System.Windows.Forms.ToolBarButton tbbLoggingStatus;
        private System.Windows.Forms.ToolBarButton tbbSelectEvents;
        private System.Windows.Forms.ToolBarButton tbbClearLogList;
        private System.Windows.Forms.ListView lvReportedEvents;
        private System.Windows.Forms.ColumnHeader chEventName;
        private System.Windows.Forms.ColumnHeader chControlName;
        private System.Windows.Forms.ColumnHeader chEventType;
        private System.Windows.Forms.ImageList ilToolbar;
        private System.ComponentModel.IContainer components;

		public FormMain()
		{
			InitializeComponent();

            Utils.FormsDelegate = new Utils.ReportDelegate(this.ReportEvent);
            _orderByControl = true;
			_listening = false;
			_log = false;
			_appendLog = true;
			_logFilename = string.Empty;
			_logHeader = string.Empty;

            UpdateMenusStatus();
		}

		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.components = new System.ComponentModel.Container();
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FormMain));
            this.mainMenu1 = new System.Windows.Forms.MainMenu();
            this.menuFile = new System.Windows.Forms.MenuItem();
            this.menuSelectForm = new System.Windows.Forms.MenuItem();
            this.menuSelectEvents = new System.Windows.Forms.MenuItem();
            this.menuLoggingOptions = new System.Windows.Forms.MenuItem();
            this.menuLoggingStatus = new System.Windows.Forms.MenuItem();
            this.menuClearLogList = new System.Windows.Forms.MenuItem();
            this.menuFileExit = new System.Windows.Forms.MenuItem();
            this.menuHelp = new System.Windows.Forms.MenuItem();
            this.menuHelpAbout = new System.Windows.Forms.MenuItem();
            this.tb = new System.Windows.Forms.ToolBar();
            this.tbbSelectForm = new System.Windows.Forms.ToolBarButton();
            this.tbbSelectEvents = new System.Windows.Forms.ToolBarButton();
            this.tbbLoggingOptions = new System.Windows.Forms.ToolBarButton();
            this.tbbLoggingStatus = new System.Windows.Forms.ToolBarButton();
            this.tbbClearLogList = new System.Windows.Forms.ToolBarButton();
            this.ilToolbar = new System.Windows.Forms.ImageList(this.components);
            this.lvReportedEvents = new System.Windows.Forms.ListView();
            this.chEventName = new System.Windows.Forms.ColumnHeader();
            this.chControlName = new System.Windows.Forms.ColumnHeader();
            this.chEventType = new System.Windows.Forms.ColumnHeader();
            this.SuspendLayout();
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                      this.menuFile,
                                                                                      this.menuHelp});
            // 
            // menuFile
            // 
            this.menuFile.Index = 0;
            this.menuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                     this.menuSelectForm,
                                                                                     this.menuSelectEvents,
                                                                                     this.menuLoggingOptions,
                                                                                     this.menuLoggingStatus,
                                                                                     this.menuClearLogList,
                                                                                     this.menuFileExit});
            this.menuFile.Text = "&File";
            // 
            // menuSelectForm
            // 
            this.menuSelectForm.Index = 0;
            this.menuSelectForm.Text = "Select &Form...";
            this.menuSelectForm.Click += new System.EventHandler(this.menuSelectForm_Click);
            // 
            // menuSelectEvents
            // 
            this.menuSelectEvents.Enabled = false;
            this.menuSelectEvents.Index = 1;
            this.menuSelectEvents.Text = "Select E&vents...";
            this.menuSelectEvents.Click += new System.EventHandler(this.menuSelectEvents_Click);
            // 
            // menuLoggingOptions
            // 
            this.menuLoggingOptions.Index = 2;
            this.menuLoggingOptions.Text = "Logging &Options...";
            this.menuLoggingOptions.Click += new System.EventHandler(this.menuLoggingOptions_Click);
            // 
            // menuLoggingStatus
            // 
            this.menuLoggingStatus.Enabled = false;
            this.menuLoggingStatus.Index = 3;
            this.menuLoggingStatus.Text = "Start &Logging";
            this.menuLoggingStatus.Click += new System.EventHandler(this.menuLoggingStatus_Click);
            // 
            // menuClearLogList
            // 
            this.menuClearLogList.Index = 4;
            this.menuClearLogList.Text = "Clea&r Log List";
            this.menuClearLogList.Click += new System.EventHandler(this.menuClearLogList_Click);
            // 
            // menuFileExit
            // 
            this.menuFileExit.Index = 5;
            this.menuFileExit.Text = "E&xit";
            this.menuFileExit.Click += new System.EventHandler(this.menuFileExit_Click);
            // 
            // menuHelp
            // 
            this.menuHelp.Index = 1;
            this.menuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                     this.menuHelpAbout});
            this.menuHelp.Text = "&Help";
            // 
            // menuHelpAbout
            // 
            this.menuHelpAbout.Index = 0;
            this.menuHelpAbout.Text = "&About...";
            this.menuHelpAbout.Click += new System.EventHandler(this.menuHelpAbout_Click);
            // 
            // tb
            // 
            this.tb.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
                                                                                  this.tbbSelectForm,
                                                                                  this.tbbSelectEvents,
                                                                                  this.tbbLoggingOptions,
                                                                                  this.tbbLoggingStatus,
                                                                                  this.tbbClearLogList});
            this.tb.DropDownArrows = true;
            this.tb.ImageList = this.ilToolbar;
            this.tb.Name = "tb";
            this.tb.ShowToolTips = true;
            this.tb.Size = new System.Drawing.Size(352, 25);
            this.tb.TabIndex = 0;
            this.tb.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.tb_ButtonClick);
            // 
            // tbbSelectForm
            // 
            this.tbbSelectForm.ImageIndex = 0;
            this.tbbSelectForm.Tag = "1";
            this.tbbSelectForm.ToolTipText = "Select .NET Windows Forms Form";
            // 
            // tbbSelectEvents
            // 
            this.tbbSelectEvents.ImageIndex = 1;
            this.tbbSelectEvents.Tag = "2";
            this.tbbSelectEvents.ToolTipText = "Select Events";
            // 
            // tbbLoggingOptions
            // 
            this.tbbLoggingOptions.ImageIndex = 2;
            this.tbbLoggingOptions.Tag = "3";
            this.tbbLoggingOptions.ToolTipText = "Logging Options";
            // 
            // tbbLoggingStatus
            // 
            this.tbbLoggingStatus.ImageIndex = 3;
            this.tbbLoggingStatus.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
            this.tbbLoggingStatus.Tag = "4";
            this.tbbLoggingStatus.ToolTipText = "Start/Stop Logging";
            // 
            // tbbClearLogList
            // 
            this.tbbClearLogList.ImageIndex = 5;
            this.tbbClearLogList.Tag = "5";
            this.tbbClearLogList.ToolTipText = "Clear Events Listview";
            // 
            // ilToolbar
            // 
            this.ilToolbar.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
            this.ilToolbar.ImageSize = new System.Drawing.Size(16, 16);
            this.ilToolbar.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilToolbar.ImageStream")));
            this.ilToolbar.TransparentColor = System.Drawing.Color.Blue;
            // 
            // lvReportedEvents
            // 
            this.lvReportedEvents.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.lvReportedEvents.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
                                                                                               this.chEventName,
                                                                                               this.chControlName,
                                                                                               this.chEventType});
            this.lvReportedEvents.FullRowSelect = true;
            this.lvReportedEvents.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
            this.lvReportedEvents.HideSelection = false;
            this.lvReportedEvents.Location = new System.Drawing.Point(8, 32);
            this.lvReportedEvents.Name = "lvReportedEvents";
            this.lvReportedEvents.Size = new System.Drawing.Size(336, 232);
            this.lvReportedEvents.TabIndex = 1;
            this.lvReportedEvents.View = System.Windows.Forms.View.Details;
            // 
            // chEventName
            // 
            this.chEventName.Text = "Event Name";
            this.chEventName.Width = 90;
            // 
            // chControlName
            // 
            this.chControlName.Text = "Control Name";
            this.chControlName.Width = 90;
            // 
            // chEventType
            // 
            this.chEventType.Text = "Event Type";
            this.chEventType.Width = 130;
            // 
            // FormMain
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(352, 273);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.lvReportedEvents,
                                                                          this.tb});
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mainMenu1;
            this.Name = "FormMain";
            this.Text = "ICanSpy - .NET Windows Forms Event Test Driver";
            this.ResumeLayout(false);

        }
		#endregion

		[STAThread]
		static void Main() 
		{
            try
            {
                CustomExceptionHandler eh = new CustomExceptionHandler();
                Application.ThreadException += new ThreadExceptionEventHandler(eh.OnThreadException);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "ICanSpy - Error occurred");
            }
 
            Application.Run(new FormMain());
		}

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

        private void menuSelectForm_Click(object sender, System.EventArgs e)
        {
            FormSelectForm frm = new FormSelectForm();
            if (frm.ShowDialog (this) == DialogResult.OK)
            {
                Type formType = frm.SelectedFormType;
                Object obj = System.Activator.CreateInstance(formType, true);
                Form formTest = (Form) obj;

                if (formTest != null)
                {
                    if (_formTest != null)
                    {
                        _formTest.Closed -= new System.EventHandler(this.FormTest_Closed);
                        _formTest.Close();
                    }		
                    _formTest = formTest;
                    _formTest.Closed += new System.EventHandler(this.FormTest_Closed);
                    _formTest.Show();
                    if (Screen.PrimaryScreen.WorkingArea.Width > this.Location.X + this.Width)
                    {
                        _formTest.Location = new Point(this.Location.X + this.Width, this.Location.Y);
                    }
                    else
                    {
                        _formTest.Location = new Point(this.Location.X, this.Location.Y + this.Height);
                    }
                    _tvEvents = new TreeView ();
                    Utils.FillEventsTreeViewFromForm(_orderByControl, _formTest, _tvEvents);
                    UpdateMenusStatus();
                }
            }
        }

        private void menuSelectEvents_Click(object sender, System.EventArgs e)
        {
            Debug.Assert(_tvEvents != null);
            FormSelectEvents formSelectEvents = new FormSelectEvents();
            formSelectEvents.FillEventsTreeView(_orderByControl, _tvEvents);
            if (formSelectEvents.ShowDialog (this) == DialogResult.OK)
            {
                formSelectEvents.ReadEventsTreeView(out _orderByControl, _tvEvents);
            }
			UpdateMenusStatus();
        }

		private void menuLoggingStatus_Click(object sender, System.EventArgs e)
		{
			if (_listening)
			{
				_listening = false;
				Utils.StopListening();
                if (_log && _logFileOpened)
                {
                    Utils.CloseLogFile();
                }
			}
			else
			{
				_listening = true;
                if (_log)
                {
                    _logFileOpened = Utils.OpenLogFile(_logFilename, _appendLog);
                    if (_logFileOpened && _logHeader.Length > 0)
                    {
                        Utils.WriteLogLine(_logHeader);
                    }
                }
                Utils.StartListening(_formTest, _tvEvents, _orderByControl);
			}
			UpdateMenusStatus();
		}

        private void menuHelpAbout_Click(object sender, System.EventArgs e)
        {
			FormAbout frmAbout = new FormAbout();
			frmAbout.ShowDialog(this);
        }

        private void menuClearLogList_Click(object sender, System.EventArgs e)
        {
            lvReportedEvents.Items.Clear();
        }

		private void menuLoggingOptions_Click(object sender, System.EventArgs e)
		{
			FormLoggingOptions frmLoggingOptions = new FormLoggingOptions();
			frmLoggingOptions.SetInitialValues(_log, _logFilename, _logHeader, _appendLog);
			if (frmLoggingOptions.ShowDialog(this) == DialogResult.OK)
			{
				_log = frmLoggingOptions.Log;
				_appendLog = frmLoggingOptions.AppendLog;
				_logFilename = frmLoggingOptions.LogFilename;
				_logHeader = frmLoggingOptions.LogHeader;
			}
		}

        private void tb_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
        {
            switch (e.Button.Tag.ToString())
            {
                case "1": //tbbSelectForm.Tag
                    menuSelectForm_Click(null, System.EventArgs.Empty);
                    break;
                case "2": //tbbSelectEvents.Tag
                    menuSelectEvents_Click(null, System.EventArgs.Empty);
                    break;
                case "3": //tbbLoggingOptions.Tag
                    menuLoggingOptions_Click(null, System.EventArgs.Empty);
                    break;
                case "4": //tbbLoggingStatus.Tag
                    menuLoggingStatus_Click(null, System.EventArgs.Empty);
                    break;
                case "5": //tbbClearLogList.Tag
                    menuClearLogList_Click(null, System.EventArgs.Empty);
                    break;
            }
        }

        private void UpdateMenusStatus()
        {
            if (_listening)
            {
                menuLoggingStatus.Enabled = true;
                menuLoggingStatus.Text = "Stop &Logging";
            }
            else
            {
                menuLoggingStatus.Enabled = 
                    (_formTest != null && _formTest.Visible && Utils.EventsTreeViewHasCheckedNode(_tvEvents));
                menuLoggingStatus.Text = "Start &Logging";
            }

            menuSelectForm.Enabled = !_listening;
            menuLoggingOptions.Enabled = !_listening;
            menuSelectEvents.Enabled = (_formTest != null && !_listening);
            menuClearLogList.Enabled = lvReportedEvents.Items.Count > 0;

            tbbSelectForm.Enabled = menuSelectForm.Enabled;
            tbbSelectEvents.Enabled = menuSelectEvents.Enabled;
            tbbLoggingOptions.Enabled = menuLoggingOptions.Enabled;
            tbbLoggingStatus.Enabled = menuLoggingStatus.Enabled;
            tbbLoggingStatus.Pushed = _listening;
            if (_listening)
            {
                tbbLoggingStatus.ImageIndex = 4;
            }
            else
            {
                tbbLoggingStatus.ImageIndex = 3;
            }
            tbbClearLogList.Enabled = menuClearLogList.Enabled;
        }

        private void FormTest_Closed(object sender, System.EventArgs e)
        {
            _formTest = null;
            menuLoggingStatus_Click(null, System.EventArgs.Empty);
        }

        public void ReportEvent(string eventName, object sender, System.EventArgs e)
        {
            if (_log && _logFileOpened)
            {
                Utils.WriteLogEvent(eventName, sender, e);
            }

            Control ctl = (Control) sender;
            ListViewItem lvi = new ListViewItem(eventName);
            lvi.SubItems.Add(ctl.Name);
            string shortTypeName, fullTypeName = e.GetType().FullName;
            StringBuilder sb = new StringBuilder();
            int index = fullTypeName.LastIndexOf('.');
            if (index > -1)
            {
                shortTypeName = fullTypeName.Substring(index+1);
            }
            else
            {
                shortTypeName = fullTypeName;
            }
            sb.AppendFormat("{0} ({1})", shortTypeName, fullTypeName);
            lvi.SubItems.Add(sb.ToString());
            lvReportedEvents.Items.Insert(0, lvi);
        }
    }

    internal class CustomExceptionHandler 
    {
        public void OnThreadException(object sender, ThreadExceptionEventArgs t)
        {
            DialogResult result = DialogResult.Cancel;
            try
            {
                result = this.ShowThreadExceptionDialog(t.Exception);
            }
            catch
            {
                try
                {
                    MessageBox.Show("Fatal Error", "ICanSpy - Error occurred", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
                }
                finally
                {
                    Application.Exit();
                }
            }

            // Exits the program when the user clicks Abort.
            if (result == DialogResult.Abort) 
                Application.Exit();
        }

        private DialogResult ShowThreadExceptionDialog(Exception e)
        {
            string errorMsg = "Error information:\n\n";
            errorMsg = errorMsg + e.Message + "\n\nStack Trace:\n" + e.StackTrace;
            return MessageBox.Show(errorMsg, "ICanSpy - Error occurred", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
        }
    }
}