Create a gist now

Instantly share code, notes, and snippets.

Monitoring context menu opened (UI Automation)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Automation;
class ContextMenuObserverUIA : Form
{
[STAThread]
public static void Main()
{
Application.Run(new ContextMenuObserverUIA());
}
private AutomationEventHandler _menuOpenEventHandler;
private Label _result;
ContextMenuObserverUIA()
{
_menuOpenEventHandler = new AutomationEventHandler(OnMenuOpenedEvent);
Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, TreeScope.Descendants, _menuOpenEventHandler);
_result = new Label();
_result.AutoSize = true;
_result.Location = new Point(10, 10);
Controls.AddRange(new Control[] { _result });
this.TopMost = true;
this.AutoSize = true;
this.MinimizeBox = false;
this.MaximizeBox = false;
this.Text = "ContextMenu Observer UIA";
}
protected override void OnClosed(EventArgs e)
{
Automation.RemoveAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, _menuOpenEventHandler);
base.OnClosed(e);
}
private void OnMenuOpenedEvent(object src, AutomationEventArgs args)
{
var element = src as AutomationElement;
if (element == null)
{
return;
}
var children = element.FindAll(TreeScope.Descendants, Condition.TrueCondition).Cast<AutomationElement>();
_result.Text = string.Join("\n\n", children.Where(x => x.Current.ControlType == ControlType.MenuItem).Select(x => x.Current.Name));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment