2015-10-19 76 views
1

我正在使用UIAutomation的C封装来侦听事件。UIAutomation - 事件处理程序中的解除绑定事件

具体而言,我正在寻找焦点活动。当焦点事件发生时,我只需登录到控制台并解除事件。

问题是 - 该程序似乎在automation.RemoveAllEventHandlers()调用中失去/“死”。下面这行永远不会被执行(不打印到控制台,断点不会被击中。)

我的猜测是这是一个线程问题 - automation是在一个线程上创建的,但事件在一个线程上被调用不同的线程,然后出现一个大问题。这是问题吗?如果是这样/如果不是 - 我该如何修复它?

下面是代码:

public class FocusListener 
    { 
     private readonly CUIAutomation _automation; 

     public FocusListener() 
     { 
      _automation = new CUIAutomation(); 

      _automation.AddFocusChangedEventHandler(null, new FocusChangeHandler(this)); 
      Console.WriteLine("Added a focus event!"); 
     } 

     public void On_WindowClicked() 
     { 
      Console.WriteLine("Window clicked!"); 
      _automation.RemoveAllEventHandlers(); // program seems to die right here.. 
      Console.WriteLine("Focus event removed"); // this line never gets executed.. 
     } 
    } 

    public class FocusChangeHandler : IUIAutomationFocusChangedEventHandler 
    { 
     private readonly FocusListener _listener; 

     public FocusChangeHandler(FocusListener listener) 
     { 
      _listener = listener; 
     } 

     public void HandleFocusChangedEvent(IUIAutomationElement sender) 
     { 
      if (sender.CurrentControlType == UIA_ControlTypeIds.UIA_WindowControlTypeId) 
      { 
       _listener.On_WindowClicked(); 
      } 
     } 
    } 

回答

0

据:https://msdn.microsoft.com/en-us/library/windows/desktop/ee671692%28v=vs.85%29.aspx

它是安全的,使UI自动化UI自动化事件处理程序调用,>因为事件处理程序都要调用的一个非UI线程。但是,当订阅可能来自客户端应用程序UI的事件时,必须在非UI线程(也应该是MTA线程)上调用IUIAutomation :: AddAutomationEventHandler或相关的方法。在同一个线程上移除事件>处理程序。