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

NCa*_*ell 5 c# automation contextmenu routedevent

我正在尝试使用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;

    }
Run Code Online (Sandbox Code Playgroud)

小智 0

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

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