Почему элемент управления PasswordBox аварийно завершает работу моего приложения WPF? - PullRequest
4 голосов
/ 11 января 2012

Я провел хороший день, пытаясь понять, почему PasswordBox вызывает у меня столько проблем.
У меня есть приложение, которое работает на каждой машине, на которой я его тестировал. Теперь он установлен на других машинах и падает, когда я нажимаю внутри PasswordBox.
Я даже сделал тестовое приложение с элементами управления TextBox и PasswordBox, чтобы посмотреть, был ли сбой вызван каким-либо базовым кодом в моем приложении, но оказалось, что это не так. Я нажимаю на TextBox, и он отлично работает. Позволяет мне печатать текст внутри него. Но как только я нажимаю на PasswordBox, приложение вылетает.

Я настроил эти события на перехват любых необработанных исключений:

  • Application.Current.DispatcherUnhandledException
  • AppDomain.CurrentDomain.UnhandledException
  • AppDomain.CurrentDomain.FirstChanceException

Теперь это должно показать мне MessageBox, если возникнут какие-либо ошибки. Хуже всего то, что эти события не выдают никаких ошибок.
Я настроил запись в своем приложении и получил исключения, такие как:

  • Ссылка на объект не установлена ​​для экземпляра объекта
  • Попытка чтения или записи в защищенную память. Это часто указывает на то, что другая память повреждена.

Я установил событие для PasswordBox, чтобы проверить, получил ли он фокус перед тем, как произошел сбой, и я не думаю, что исключение Ссылка на объект ссылается на элемент управления PasswordBox.
Я искал везде, чтобы найти, если кто-то еще имел эти проблемы и видел только проблемы с элементом управления TextBox и его проблемы с фокусом, которые должны быть исправлены в .NET 4.0

Oh! и это напоминает мне Я использую WPF .NET 4.0.

Любая помощь будет принята с благодарностью.

Тестовый код:

private void Application_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    Application.Current.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler((x, y) => { ShowError(x, y); });  

    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((x, y) => { ShowError(x, y); });
    AppDomain.CurrentDomain.FirstChanceException += new EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs>((x, y) => { ShowError(x, y); });
}

private void ShowError(object sender, object o)
{
    Exception ex = null;
    if (o.GetType() == typeof(FirstChanceExceptionEventArgs))
    {
        ex = ((FirstChanceExceptionEventArgs)o).Exception;
    }
    else if (o.GetType() == typeof(DispatcherUnhandledExceptionEventArgs))
    {
        ex = ((DispatcherUnhandledExceptionEventArgs)o).Exception;
    }
    else if (o.GetType() == typeof(UnhandledExceptionEventArgs))
    {
        ex = (Exception)((UnhandledExceptionEventArgs)o).ExceptionObject;
    }
    MessageBox.Show(ex.Message + "\n\r" + ex.StackTrace, "Error at: " + ex.Source, MessageBoxButton.OK, MessageBoxImage.Error);
}

И Xaml:

<Window x:Class="WPF_Control_Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="200" Width="300">
    <Grid>
        <StackPanel Orientation="Vertical" HorizontalAlignment="Left">
            <StackPanel Orientation="Horizontal" Width="260">
                <TextBlock Text="TextBox: " TextAlignment="Right" Width="80" Height="Auto" VerticalAlignment="Center" />
                <TextBox Name="textBox" Width="120" VerticalAlignment="Center" />
            </StackPanel>
            <StackPanel Orientation="Horizontal" Width="260">
                <TextBlock Text="PasswordBox: " TextAlignment="Right" Width="80" Height="Auto" VerticalAlignment="Center" />
                <PasswordBox Name="passwordBoxTest" Width="120" VerticalAlignment="Center" />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

Просмотр событий

Вот исключение из Просмотрщика событий на машине:

Приложение: WPF Control Test.exe
Версия Framework: v4.0.30319
Описание: приложение запросило завершение процесса через System.Environment.FailFast (строковое сообщение).
Сообщение: неисправимая системная ошибка.
Стек:
в System.Environment.FailFast (System.String)
в MS.Internal.Invariant.FailFast (System.String, System.String)
в System.Windows.Media.FontFamily.get_FirstFontFamily ()
в System.Windows.Documents.TextSelection.CalculateCaretRectangle (System.Windows.Documents.ITextSelection, System.Windows.Documents.ITextPointer)
в System.Windows.Documents.TextSelection.UpdateCaretStateWorker (System.Object)
в System.Windows.Documents.TextSelection.UpdateCaretState (System.Windows.Documents.CaretScrollMethod)
в System.Windows.Documents.TextSelection.EnsureCaret (Boolean, System.Windows.Documents.CaretScrollMethod)
в System.Windows.Documents.TextSelection.System.Windows.Documents.ITextSelection.UpdateCaretAndHighlight ()
в System.Windows.Documents.TextEditor.OnGotKeyboardFocus (System.Object, System.Windows.Input.KeyboardFocusChangedEventArgs)
в System.Windows.Controls.PasswordBox.OnGotKeyboardFocus (System.Windows.Input.KeyboardFocusChangedEventArgs)
в System.Windows.UIElement.OnGotKeyboardFocusThunk (System.Object, System.Windows.Input.KeyboardFocusChangedEventArgs)
в System.Windows.Input.KeyboardFocusChangedEventArgs.InvokeEventHandler (System.Delegate, System.Object)
в System.Windows.RoutedEventArgs.InvokeHandler (System.Delegate, System.Object)
в System.Windows.RoutedEventHandlerInfo.InvokeHandler (System.Object, System.Windows.RoutedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl (System.Object, System.Windows.RoutedEventArgs, Boolean)
в System.Windows.UIElement.RaiseEventImpl (System.Windows.DependencyObject, System.Windows.RoutedEventArgs)
в System.Windows.UIElement.RaiseTrustedEvent (System.Windows.RoutedEventArgs)
в System.Windows.UIElement.RaiseEvent (System.Windows.RoutedEventArgs, Boolean)
в System.Windows.Input.InputManager.ProcessStagingArea ()
в System.Windows.Input.InputManager.ProcessInput (System.Windows.Input.InputEventArgs)
в System.Windows.Input.KeyboardDevice.ChangeFocus (System.Windows.DependencyObject, Int32)
в System.Windows.Input.KeyboardDevice.TryChangeFocus (System.Windows.DependencyObject, System.Windows.Input.IKeyboardInputProvider, Boolean, Boolean, Boolean)
в System.Windows.Input.KeyboardDevice.Focus (System.Windows.DependencyObject, Boolean, Boolean, Boolean)
в System.Windows.Input.KeyboardDevice.Focus (System.Windows.IInputElement)
в System.Windows.UIElement.Focus ()
в System.Windows.Documents.TextEditorMouse.MoveFocusToUiScope (System.Windows.Documents.TextEditor)
в System.Windows.Documents.TextEditorMouse.OnMouseDown (System.Object, System.Windows.Input.MouseButtonEventArgs)
в System.Windows.Controls.PasswordBox.OnMouseDown (System.Windows.Input.MouseButtonEventArgs)
в System.Windows.UIElement.OnMouseDownThunk (System.Object, System.Windows.Input.MouseButtonEventArgs)
в System.Windows.Input.MouseButtonEventHventSystem.Delegate, System.Object)
в System.Windows.RoutedEventArgs.InvokeHandler (System.Delegate, System.Object)
в System.Windows.RoutedEventHandlerInfo.InvokeHandler (System.Object, System.Windows.RoutedEventArgs)
в System.Windows.EventRoute.InvokeHandlersImpl (System.Object, System.Windows.RoutedEventArgs, Boolean)
в System.Windows.UIElement.RaiseEventImpl (System.Windows.DependencyObject, System.Windows.RoutedEvent)* в System.Windows.UIElement.RaiseTrustedEvent (System.Windows.RoutedEventArgs)
в System.Windows.UIElement.RaiseEvent (System.Windows.RoutedEventArgs, Boolean)
в System.Windows.Input.InputManager.ProcessStagingArea ()
в System.Windows.Input.InputManager.ProcessInput (System.Windows.Input.InputEventArgs)
в System.Windows.Input.InputProviderSite.ReportInput (System.Windows.Input.InputReport)
в System.Windows.Interop.HwndMouseInputProvider.ReportInput (IntPtr, System.Windows.Input.InputMode, Int32,System.Windows.Input.RawMouseActions, Int32, Int32, Int32)
в System.Windows.Interop.HwndMouseInputProvider.FilterMessage (IntPtr, MS.Internal.Interop.WindowMessage, IntPtr, IntPtr, Boolean ByRef)
.Windows.Interop.HwndSource.InputFilterMessage (IntPtr, Int32, IntPtr, IntPtr, логическое значение ByRef)
в MS.Win32.HwndWrapper.WndProc (IntPtr, Int32, IntPtr, IntPtr, логическое значение 8 * в MSR).HwndSubclass.DispatcherCallbackOperation (System.Object)
в System.Windows.Threading.ExceptionWrapper.InternalRealCall (System.Delegate, System.Object, Int32)
в MS.Internal.Threading.ExceptionFilterHelper.TryCatchWject (, System.Delegate, System.Object, Int32, System.Delegate)
в System.Windows.Threading.Dispatcher.InvokeImpl (System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
в MS.Win32.HwndSubclass.SubclassWndProc (IntPtr, Int32, IntPtr, IntPtr)
в MS.WNM.DispatchMessage (System.Windows.Interop.MSG ByRef)
в System.Windows.Threading.Dispatcher.PushFrameImpl (System.Windows.Threading.DispatcherFrame)
в System.Windows.Threading.Dispatcher.PushFrame (System.Windows).Threading.DispatcherFrame)
в System.Windows.Application.RunDispatcher (System.Object)
в System.Windows.Application.RunInternal (System.Windows.Window)
в System.Windows.Application.Run(System.Windows.Window)
в System.Windows.Application.Run ()
в WPF_Control_Test.App.Main ()

Ответы [ 2 ]

3 голосов
/ 11 января 2012

Похоже, что .Net Framework не может найти подходящий шрифт по умолчанию. Я не знаю, почему это происходит, но следующие строки внутреннего кода из FontFamily включают строку, в которой выдается исключение:

fontFamily = this.FindFirstFontFamilyAndFace(
    ref normal, ref normal2, ref normal3);
if (fontFamily == null)
{
    // NullFontFamilyCanonicalName
    //  = CanonicalFontFamilyReference.Create(null, "#ARIAL");
    fontFamily = FontFamily.LookupFontFamily(
        FontFamily.NullFontFamilyCanonicalName);
    Invariant.Assert(fontFamily != null); // <- Your exception
}

Очевидно, что если вы не укажете шрифт, он будет искать шрифт на основе Arial, который не может быть найден на этом компьютере, поэтому вы исключение.

1 голос
/ 27 февраля 2014

У меня была такая же проблема на коробке Windows Embedded 7, и, как упоминалось в ссылке в комментариях;

http://social.msdn.microsoft.com/Forums/ar/wpf/thread/fc2c9a54-8f66-4f1a-82be-cb40ada5fba5

Я просто скопировал следующие шрифты в "c": \ windows \ fonts "и проблема была решена;

  • Arial (TrueType)
  • Courier New (TrueType)
  • Times New Roman (TrueType)
...