OP:
I am looking for a way to click a button programatically (Winform).
Button1 and Button2 are in two different process. I am not supposed to make any changes to the code containing button1.
Sure, the easiest thing to do that does not require any changes to the target app is to use Windows UI Automation. UIA essentially allows you to automate another app from the GUI perspective (instead of say behind the scenes via COM/Ole Automation) regardless of whether you just want to drive another app, say click a button, or perform full-on automation testing in QA.
MSDN:
Microsoft UI Automation is an accessibility framework that enables Windows applications to provide and consume programmatic information about user interfaces (UIs). more...
...and:
UIA can be used to automate native windows applications , WPF applications as well as Silverlight applications. more...
This code will click a button containing the text "Click Me" in a window captioned "Target Demo". Note I do not make any reference to any particular object type; callback or GUI technology (this works for native; WinForms; WPF and web)
//
// This is the handler in the ButtonClicker app, the app that is doing the clicking
//
private void go_Click(object sender, EventArgs e)
{
// Look for a top-level window/application called "Target Demo"
var root = AutomationElement.RootElement;
var condition1 = new PropertyCondition(AutomationElement.NameProperty, "Target Demo");
var treeWalker = new TreeWalker(condition1);
AutomationElement element = treeWalker.GetFirstChild(root);
if (element == null)
{
// not found
return;
}
// great! window found
var window = element;
// now look for a button with the text "Click Me"
var buttonElement =window.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.NameProperty, "Click Me"));
if (buttonElement == null)
{
// not found
return;
}
// great! now click the button
var invokePattern = buttonElement.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
invokePattern?.Invoke();
}
Benefits
- Zero changes required to target app
- No mucking about finding window handles
- No mucking about trying to send BN_CLICK notifications to an app's message pump fingers crossed in hoping that it works
- works on c++ apps; WinForms; WPF; web