Programmatically open context menu using UI automation?

徘徊边缘 提交于 2019-12-21 17:00:02

问题


I'm trying to implement a right click context menu using UI automation. Since UI automation does not have a native right click pattern I am adding an ExpandCollapse provider to the listview's AutomationPeer class and mapping the expand and collapse to opening and closing the context menu.

My question, is there a better method of invoking the context menu that doesn't involve trying to instantiate a class with a private constructor? I can't use SendKeys with Shift-F10. I'd like to use the PopupControlService but that is tagged as internal.

My awful workaround:

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;

    }

回答1:


I too am struggling with the same issue. As a work around i am using the mouse_event function using user32.dll and performing the right click after getting the X, Y coordinates of the clickable area.

This is not a good method as the X , Y coordinates of screen vary with the screen resolution.



来源:https://stackoverflow.com/questions/2008399/programmatically-open-context-menu-using-ui-automation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!