2010-01-05 48 views
4

我想用UI自動化來實現一個右鍵單擊上下文菜單。由於UI自動化沒有原生的右鍵單擊模式,我將一個ExpandCollapse提供程序添加到列表視圖的AutomationPeer類中,並將展開和摺疊映射爲打開和關閉上下文菜單。使用UI自動化以編程方式打開上下文菜單?

我的問題,是否有更好的方法來調用上下文菜單,不涉及試圖用私有構造函數實例化一個類?我不能在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; 

    } 

回答

0

我也是用了同樣的問題掙扎。作爲解決方案,我使用user_32.dll的mouse_event函數,並在獲取可點擊區域的X,Y座標後執行右鍵單擊。

這不是一個好方法,因爲屏幕的X,Y座標隨屏幕分辨率而變化。

相關問題