Using the Microsoft UI Automation framework, I've setup an example where if I press a hotkey, it registers an event handler for the AutomationElement under the cursor (typically a button).
However when I press the button, the event handler doesn't get called.
I've used this example from the official docs to subscribe to the event.
Interestingly, the code below works for Win32 apps (tested with Notepad++) but not for WinForms (.NET) apps. Any idea how to get this working for a target .NET app?
Code:
public partial class FormAuto : Form
{
//...
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.F8)
{
Thread trd = new Thread(new ThreadStart(this.ThreadTask));
trd.IsBackground = true;
trd.Start();
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void ThreadTask()
{
System.Windows.Point point = new System.Windows.Point(Cursor.Position.X, Cursor.Position.Y);
AutomationElement element = AutomationElement.FromPoint(point);
Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, element,
TreeScope.Element, new AutomationEventHandler(OnUIAutomationEvent));
while(true)
Thread.Sleep(100);
}
private void OnUIAutomationEvent(object src, AutomationEventArgs e)
{
AutomationElement sourceElement = src as AutomationElement; //doesn't get called
}
}