ManagedSpy is acutally an example demonstrating the usage of ManagedSpyLib. ManagedSpyLib introduced a class, ControlProxy, with which we can get or set properties or subscribe to events of a System.Windows.Forms.Control in another process.
An introduction to ManagedSpy and the internal of ManagedSpyLib can be found in this MSDN article. The following is a testing program listed in the article for testing a WinForm application which has 2 textboxes accepting 2 integers and one button which multiply the 2 integers and shows the product in a third textobx. The lines of code in the blue color use the methods of ControlProxy. As you can see, the testing program programmatically accesses the three textbox controls and one button control in another WinForm program.
private void button1_Click(object sender, EventArgs e)
{
Process[] procs = Process.GetProcessesByName("Multiply");
if (procs.Length != 1) return;
ControlProxy proxy =
ControlProxy.FromHandle(procs[0].MainWindowHandle);
if (proxy == null) return;
//find the controls we are interested in...
if (cbutton1 == null)
{
foreach (ControlProxy child in proxy.Children)
{
if (child.GetComponentName() == "textBox1") {
textBox1 = child;
}
else if (child.GetComponentName() == "textBox2") {
textBox2 = child;
}
else if (child.GetComponentName() == "textBox3") {
textBox3 = child;
}
else if (child.GetComponentName() == "button1") {
cbutton1 = child;
}
}
//sync testchanged on textbox3 so we can tell if it has changed.
textBox1.SetValue("Text", "5");
textBox2.SetValue("Text", "7");
textBox3.SetValue("Text", "");
textBox3.EventFired +=
new ControlProxyEventHandler(textBox3_EventFired);
textBox3.SubscribeEvent("TextChanged");
}
else textBox3.SetValue("Text", "");
//now click on the button to start the test...
if (cbutton1 != null)
{
cbutton1.SendMessage(WM_LBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);
cbutton1.SendMessage(WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero);
Application.DoEvents();
}
if (result == 35) MessageBox.Show("Passed!");
else MessageBox.Show("Fail!");
}
void textBox3_EventFired(object sender, ProxyEventArgs ed)
{
int val;
if (int.TryParse((string)textBox3.GetValue("Text"), out val)
{
result = val;
}
}
No comments:
Post a Comment