Tuesday, October 14, 2008

Build Your Own Spy Utility



kick it on DotNetKicks.com
In support of my talk on Saturday, I wanted to publish another little bit of code that I have found extremely useful. There are a lot of spy utilities out there: Spy++, ManagedSpy, UISpy, etc. They all work OK, but I have found on many occasions that I wanted my spy utility to do X, Y or Z.

So, I built my own spy utility. Start with this form, and add any spy functionality that you need to it. Here is the code:
using System.Drawing;
using System.Windows.Forms;
namespace RecipeBox.Tests.GUI_Tests
{
public class Spy : Form
{
readonly SplitContainer _splitContainer = new SplitContainer {Dock = DockStyle.Fill};
readonly TreeView _controlTree = new TreeView {Dock = DockStyle.Fill};
readonly PropertyGrid _properties = new PropertyGrid {Dock = DockStyle.Fill};

public Spy()
{
Size = new Size(640, 480);

_splitContainer.Panel1.Controls.Add(_controlTree);
_splitContainer.Panel2.Controls.Add(_properties);
Controls.Add(_splitContainer);

_controlTree.NodeMouseClick += (sender, e) => _properties.SelectedObject = e.Node.Tag;
}

public Spy(Control rootControl) : this()
{
_controlTree.Nodes.Add(GetTreeNode(rootControl));
}

private static TreeNode GetTreeNode(Control control)
{
var node = new TreeNode(control + " (" + control.Name + ")") {Tag = control};

foreach (Control childControl in control.Controls)
node.Nodes.Add(GetTreeNode(childControl));

return node;
}
}
}
And here is how you might use the custom spy:
[Test, Explicit]
public void Spy_On_TestForm()
{
var testForm = new TestForm();
testForm.Show();

var spy = new Spy(testForm);
spy.Show();

while (true)
Application.DoEvents();
}
And this is what it looks like:


No comments: