我正在尝试使用 AutomationElement 访问 wpf 控件,但有时它会抛出异常。下面是代码:
if (automationElement.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
{
ValuePattern valuePattern = pattern as ValuePattern;
valuePattern.SetValue(valueToBeSet);
}
我一直到这里,这会触发 MS.Win32.UnsafeNativeMethods 中的一些方法调用,然后给出异常。
来自事件日志的堆栈跟踪:
Exception Messages:
Win32Exception : The parameter is incorrect
Type : System.ComponentModel.Win32Exception, System, Version=4.0.0.0, Culture=neutral
Message : The parameter is incorrect
Source : WindowsBase
NativeErrorCode: 87
ErrorCode : -2147467259
TargetSite : Int32 GetWindowText(System.Runtime.InteropServices.HandleRef, System.Text.StringBuilder, Int32)
Stack Trace : at MS.Win32.UnsafeNativeMethods.GetWindowText(HandleRef hWnd, StringBuilder lpString, Int32 nMaxCount)
at System.Windows.Automation.Peers.WindowAutomationPeer.GetNameCore()
at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
at System.Windows.ContextLayoutManager.fireAutomationEvents()
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.AnimatedRenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
WPF 控件是标准的 WPF 控件(无自定义)。我无法导致此错误。我相信是窗口句柄不正确(GetWindowText 的参数),但不知道如何检查?如果是其他事情,请告诉。