Почему управление паролем сбивает мое приложение WPF?

StackOverflow https://stackoverflow.com/questions/8821648

Вопрос

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

Я настроил эти события, чтобы поймать любые неразрушенные исключения:

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

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

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

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

Ой! И это напоминает мне. Я использую 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
Фтруктурная версия: v4.0.30319
Описание: Запрашиваемое приложением завершение процесса через system.environment.failfast (строковое сообщение).
Сообщение: невозможная системная ошибка.
Куча:
at System.Environment.FailFast (System.String)
в ms. internal.invariant.failfast (System.string, System.string)
at System.windows.Media.fontfamily.get_firstfontfamily ()
at System.windows.documents.textSelection.calculateCaretRectAng
at System.windows.documents.textSelection.updateCaretStateWorker (System.Object)
at System.windows.documents.textSelection.updateCaretState (System.windows.documents.caretscrollmethod)
at System.windows.documents.textSelection.ensureCaret (Boolean, System.windows.documents.caretscrollmethod)
at System.windows.documents.textselection.system.windows.documents.itextSelection.updateCaretandHighlight ()
at System.windows.documents.texteditor.ongotkeyboardfocus (System.object, System.windows.input.keyboardfocuschangedeventargs)
at System.windows.controls.passwordbox.ongotkeyboardfocus (System.windows.input.keyboardfocuschangeventeventargs)
at System.windows.ueelement.ongotkeyboardfocusthunk (System.Object, System.Windows.Input.KeyboardFocuschangeDeventArgs)
at System.windows.input.keyboardfocuschangeDeventargs.invokeeventhandler (System.Delegate, System.Object)
at System.Windows.RoutedEventargs.invokehandler (System.Delegate, System.Object)
at System.windows.routedeventhandlerinfo.invokehandler (System.object, System.Windows.RoutedEventargs)
at System.windows.eventroute.invokehandlersimpl (System.object, System.Windows.RoutedEventargs, Boolean)
at System.windows.ueelement.raiseeventimpl (System.windows.dependencyObject, System.Windows.RoutedEventargs)
at System.windows.ueelement.raisetrustedevent (System.windows.routedeventargs)
at System.windows.ueelement.raiseevent (System.windows.routedeventargs, Boolean)
at System.windows.input.inputmanager.processstagingarea ()
at System.windows.input.inputmanager.processInput (System.Windows.Input.InputeVentargs)
at System.windows.input.keyboarddevice.changeFocus (System.Windows.DependencyObject, Int32)
at System.windows.input.keyboarddevice.trichangeFocus (System.Windows.DependencyObject, System.Windows.Input.ikeyboardInputProvider, Boolean, Boolean, Boolean)
at System.windows.input.keyboarddevice.focus (System.Windows.DependencyObject, Boolean, Boolean, Boolean)
at System.windows.input.keyboarddevice.focus (System.Windows.IinputElement)
at System.windows.ueelement.focus ()
at System.windows.documents.texteMatorMouse.movefocustouiscope (System.windows.documents.texteditor)
at System.windows.documents.TextExtorMouse.onmouseDown (System.Object, System.Windows.input.MouseButtoneVentargs)
at System.windows.controls.passwordbox.onmousedown (System.windows.input.mouseButtoneVentargs)
at System.windows.ueelement.onmouseDownthunk (System.Object, System.Windows.Input.mouseButtoneVentargs)
at System.windows.input.mousebuttoneventargs.invokeeventhandler (System.delegate, System.object)
at System.Windows.RoutedEventargs.invokehandler (System.Delegate, System.Object)
at System.windows.routedeventhandlerinfo.invokehandler (System.object, System.Windows.RoutedEventargs)
at System.windows.eventroute.invokehandlersimpl (System.object, System.Windows.RoutedEventargs, Boolean)
at System.windows.ueelement.raiseeventimpl (System.windows.dependencyObject, System.Windows.RoutedEventargs)
at System.windows.ueelement.raisetrustedevent (System.windows.routedeventargs)
at System.windows.ueelement.raiseevent (System.windows.routedeventargs, Boolean)
at System.windows.input.inputmanager.processstagingarea ()
at System.windows.input.inputmanager.processInput (System.Windows.Input.InputeVentargs)
at System.windows.input.InputProviderSite.ReportInput (System.Windows.Input.InputReport)
at System.windows.interop.hwndmouseinputprovider.reportinput (intptr, system.windows.input.inputmode, int32, system.windows.input.rawmouseActions, int32, int32, int32)
at System.Windows.Interop.hwndmouseInputProvider.filtermessage (intptr, ms.internal.interop.windowmessage, intptr, intptr, boolean byref)
at System.windows.interop.hwndsource.inputFiltermessage (Intptr, Int32, Intptr, Intptr, Boolean Byref)
в Ms.win32.hwndwrapper.wndproc (Intptr, Int32, Intptr, Intptr, Boolean Byref)
at ms.win32.hwndsubclass.dispatchercallbackoperation (system.object)
at System.Windows.Threading.ExceptionWrapper.InternalRealLcall (System.Delegate, System.Object, Int32)
at ms. internal.threading.exceptionfilterhelper.trycatchwhen (System.object, System.Delegate, System.Object, Int32, System.Delegate)
at System.Windows.Threading.Dispatcher.invokeimpl (System.Windows.Threading.DispatcherPriority, System.Timespan, System.Delegate, System.Object, Int32)
at ms.win32.hwndsubclass.subclasswndproc (Intptr, Int32, Intptr, Intptr)
at ms.win32.unsafenativemethods.dispatchmessage (System.windows.interop.msg byref)
at System.Windows.Threading.Dispatcher.pushframeImpl (System.Windows.Threading.DispatcherFrame)
at System.Windows.Threading.Dispatcher.pushframe (System.Windows.Threading.DispatcherFrame)
at System.Windows.Application.Rundispatcher (System.Object)
at System.Windows.Application.Runinternal (System.Windows.Window)
at System.Windows.Application.Run (System.Windows.Window)
at System.windows.application.run ()
at wpf_control_test.app.main ()

Это было полезно?

Решение

Похоже, что .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
}

По -видимому, если вы не указаете шрифт, он будет искать шрифт на основе ариального, который он не сможет найти на этой машине, отсюда и ваше исключение.

Другие советы

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

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

Я просто скопировал следующие шрифты в каталог "C: Windows Fonts", и проблема была решена;

  • Arial (TrueType)
  • Курьер новый (TrueType)
  • Времена Новый Роман (TrueType)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top