使用UI自动化以编程方式打开上下文菜单

我正在尝试使用UI自动化实现右键单击上下文菜单。 由于UI自动化没有本机右键单击模式,因此我将ExpandCollapse提供程序添加到listview的AutomationPeer类,并将展开和折叠映射到打开和关闭上下文菜单。

我的问题是,是否有更好的方法来调用上下文菜单,而不涉及尝试使用私有构造函数实例化类? 我不能使用带Shift-F10的SendKeys。 我想使用PopupControlService,但标记为内部。

我糟糕的解决方法:

public class MyListViewAutomationPeer : ListViewAutomationPeer, IExpandCollapseProvider { public MyListViewAutomationPeer(MyListView owner) : base(owner){} public override object GetPattern(PatternInterface patternInterface) { if (patternInterface == PatternInterface.ExpandCollapse) { return this; } return base.GetPattern(patternInterface); } public void Expand() { MyListView owner = (MyListView)Owner; //********************** //Ouch!!! What a hack //********************** //ContextMenuEventArgs is a sealed class, with private constructors //Instantiate it anyway ... ContextMenuEventArgs cmea = (ContextMenuEventArgs)FormatterServices.GetUninitializedObject(typeof(ContextMenuEventArgs)); cmea.RoutedEvent = MyListView.ContextMenuOpeningEvent; cmea.Source = owner; //This will fire any developer code that is bound to the OpenContextMenuEvent owner.RaiseEvent(cmea); //The context menu didn't open because this is a hack, so force it open owner.ContextMenu.Placement = PlacementMode.Center; owner.ContextMenu.PlacementTarget = (UIElement)owner; owner.ContextMenu.IsOpen = true; } 

我也在努力解决同样的问题。 作为解决方法,我使用user32.dll使用mouse_event函数,并在获取可点击区域的X,Y坐标后执行右键单击。

这不是一个好方法,因为屏幕的X,Y坐标随屏幕分辨率而变化。