Visual styles related operation resulted in an error

Hi there,
  • Hi there,

    On the author’s website:
    http://blogs.msdn.com/markrideout/archive/2006/01/08/510700.aspx

    one of the comments contains the fix you need (someone else realized it requires styles, and wrote a check in case they’re not available).  In case that blog ever disappears, here is the relevant code:

    in «TreeGridView.cs» delete the followin’ two lines:

    ——8<——

    internal VisualStyleRenderer rOpen = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Opened);

    internal VisualStyleRenderer rClosed = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Closed);

    ——8<——

    in «TreeGridCell.cs» find the line «if (node.HasChildren || node._grid.VirtualNodes)» and change it so that it looks like that:

    ——8<——

               if (node.HasChildren || node._grid.VirtualNodes)

               {

                   // Ensure that visual styles are supported.

                   if (Application.RenderWithVisualStyles)

                   {

                       VisualStyleRenderer rOpen = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Opened);

                       VisualStyleRenderer rClosed = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Closed);

                       // Paint node glyphs

                       if (node.IsExpanded)

                           //node._grid.rOpen.DrawBackground(graphics,
    new Rectangle(glyphRect.X, glyphRect.Y + (glyphRect.Height / 2) — 4,
    10, 10));

                           rOpen.DrawBackground(graphics, new
    Rectangle(glyphRect.X, glyphRect.Y + (glyphRect.Height / 2) — 4, 10,
    10));

                       else

                         
     //node._grid.rClosed.DrawBackground(graphics, new
    Rectangle(glyphRect.X, glyphRect.Y + (glyphRect.Height / 2) — 4, 10,
    10));

                           rClosed.DrawBackground(graphics, new
    Rectangle(glyphRect.X, glyphRect.Y + (glyphRect.Height / 2) — 4, 10,
    10));

                   }

                   else

                   {

                       int h = 8;

                       int w = 8;

                       int x = glyphRect.X;

                       int y = glyphRect.Y + (glyphRect.Height / 2) — 4;

                       //MessageBox.Show(«x = » + x.ToString() + «, y= » + y.ToString());

                       graphics.DrawRectangle(new Pen(SystemBrushes.ControlDark), x, y, w, h);

                       graphics.FillRectangle(new SolidBrush(Color.White), x + 1, y + 1, w — 1, h — 1);

                       graphics.DrawLine(new Pen(new SolidBrush(Color.Black)), x + 2, y + 4, x + w — 2, y + 4);

                       if (!node.IsExpanded)

                           graphics.DrawLine(new Pen(new SolidBrush(Color.Black)), x + 4, y + 2, x + 4, y + h — 2);

                   }

               }

    ——8<——

  • Uswer

    1644 / 1147 / 292

    Регистрация: 26.06.2017

    Сообщений: 3,110

    1

    03.02.2021, 22:14. Показов 2709. Ответов 6

    Метки нет (Все метки)


    Добрый день.

    Создаю собственную прорисовку ComboBox (см. код ниже), взято отсюда. Однако при добавлении элемента UserControl1 на форму возникает сообщение: Visual Styles-related operation resulted in an error because no visual style is currently active. (Операция с Visual Styles привела к ошибке, поскольку сейчас нет активных стилей отображения.). Никак не соображу, что делаю не так. Проблема исчезает при комментировании SetStyle, но тогда не вызывается OnPaint. В чём проблема?

    Кликните здесь для просмотра всего текста

    VB.NET
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    
    Imports System.ComponentModel
    Imports System.Windows.Forms.VisualStyles
     
    Public Class UserControl1
        Inherits ComboBox
     
        Private Sub InitializeMe()
            Font = New Font("Lato", 10)
            ForeColor = Color.FromArgb(105, 203, 242)
            'DropDownStyle = ComboBoxStyle.DropDownList
            'Me.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable
     
            SetStyle(ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer Or ControlStyles.AllPaintingInWmPaint, True)
     
            Me.PerformLayout()
        End Sub
     
        Public Sub New()
            MyBase.New()
            InitializeComponent()
            InitializeMe()
        End Sub
     
        Private _textFormatFlags As TextFormatFlags = TextFormatFlags.VerticalCenter Or TextFormatFlags.Left
     
        Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
            Dim ctrlRectangle As Rectangle = Me.ClientRectangle
            Dim buttonW As Integer = 15
            Dim border As Integer = 5
            Dim textRectange As Rectangle = ctrlRectangle
            textRectange.Width -= buttonW
            textRectange.Width -= border
            Dim buttonRectangle As Rectangle = Rectangle.FromLTRB(textRectange.Right + border, textRectange.Top, ctrlRectangle.Right, textRectange.Bottom)
            Using br As Brush = New SolidBrush(BackColor)
                e.Graphics.FillRectangle(br, ctrlRectangle)
            End Using
            Dim sf As StringFormat = New StringFormat(StringFormatFlags.NoWrap)
            sf.LineAlignment = StringAlignment.Center
            Using br As Brush = New SolidBrush(ForeColor)
                e.Graphics.DrawString("OKiOkiText", Font, br, textRectange, sf)
            End Using
            Me.DropDownWidth = GetDropDownWidth()
            ComboBoxRenderer.DrawDropDownButton(e.Graphics, buttonRectangle, ComboBoxState.Normal)
        End Sub
     
        Public Function GetDropDownWidth() As Integer
            Dim w As Integer = ClientRectangle.Width
            For Each s As Object In Items
                Dim curW As Integer = TextRenderer.MeasureText(s.ToString(), Font).Width
                If curW > w Then
                    w = curW
                End If
            Next
            Return w
        End Function
     
        Protected Overrides Sub OnDrawItem(ByVal e As DrawItemEventArgs)
            If e.Index < 0 OrElse e.State = DrawItemState.ComboBoxEdit Then
                Return
            End If
            Dim g As Graphics = e.Graphics
            Dim ctrlRectangle As Rectangle = e.Bounds
            Dim buttonW As Integer = 0
            Dim border As Integer = 0
            Dim textRectange As Rectangle = ctrlRectangle
            textRectange.Width -= buttonW
            textRectange.Width -= border
            Dim textToPaint As String = ""
            Using br As Brush = New SolidBrush(e.BackColor)
                g.FillRectangle(br, ctrlRectangle)
            End Using
            Dim drawColor As Color = ColorDeactiveItem
            If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
                drawColor = ColorActiveItem
            End If
            Using br As Brush = New SolidBrush(drawColor)
                g.FillRectangle(br, textRectange)
            End Using
            If e.Index <> -1 AndAlso Items.Count > 0 Then
                textToPaint = GetItemText(Items(e.Index))
                    Using br As Brush = New SolidBrush(e.ForeColor)
                        e.Graphics.DrawString(textToPaint, e.Font, br, textRectange)
                    End Using
            End If
        End Sub
     
    End Class



    0



    ovva

    4212 / 3361 / 817

    Регистрация: 02.02.2013

    Сообщений: 3,259

    Записей в блоге: 2

    04.02.2021, 17:31

    2

    Думаю, что если убрать InitializeComponent, все благополучно разрешиться.
    Ну и, наверное, нужно определить

    VB.NET
    1
    2
    
    Public Property ColorDeactiveItem As Color = Color.LightGray
    Public Property ColorActiveItem As Color = Color.Black

    Изображения

     



    1



    1644 / 1147 / 292

    Регистрация: 26.06.2017

    Сообщений: 3,110

    04.02.2021, 18:21

     [ТС]

    3

    ovva, увы но не выходит.



    0



    4212 / 3361 / 817

    Регистрация: 02.02.2013

    Сообщений: 3,259

    Записей в блоге: 2

    04.02.2021, 19:55

    4

    Цитата
    Сообщение от Uswer
    Посмотреть сообщение

    Однако при добавлении элемента UserControl1 на форму возникает сообщение

    Такой проблемы не наблюдается. Это никакой не UserControl, а обычный класс, наследуемый от ComboBox. Для получения картинки выше использовался ваш код лишь слегка подредактированный.

    Цитата
    Сообщение от Uswer
    Посмотреть сообщение

    увы но не выходит

    Вы бы пояснили, какого эффекта вы ожидаете.



    0



    1644 / 1147 / 292

    Регистрация: 26.06.2017

    Сообщений: 3,110

    04.02.2021, 22:01

     [ТС]

    5

    Цитата
    Сообщение от ovva
    Посмотреть сообщение

    Вы бы пояснили, какого эффекта вы ожидаете.

    Хочу такого эффекта как у Вас, а имею вот что (см. картинку).

    Миниатюры

    Операция с Visual Styles привела к ошибке, поскольку сейчас нет активных стилей отображения
     



    0



    ovva

    4212 / 3361 / 817

    Регистрация: 02.02.2013

    Сообщений: 3,259

    Записей в блоге: 2

    04.02.2021, 22:29

    6

    Цитата
    Сообщение от Uswer
    Посмотреть сообщение

    такого эффекта как у Вас

    Вот код соответствующий приложенной картинке

    Кликните здесь для просмотра всего текста

    VB.NET
    1
    2
    3
    4
    5
    6
    
    Public Class Form1
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            'UCB добавленный на форму UserComboBox
            UCB.Items.AddRange({"1111", "2222", "3333"})
        End Sub
    End Class

    Сам класс, вообщем то мало отличающийся от вашего кода.

    VB.NET
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    
    Imports System.ComponentModel
    Imports System.Windows.Forms.VisualStyles
    Public Class UserComboBox
        Inherits ComboBox
        Private Sub InitializeMe()
            Font = New Font("Lato", 10)
            ForeColor = Color.FromArgb(105, 203, 242)
            DropDownStyle = ComboBoxStyle.DropDownList
            Me.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable
            SetStyle(ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer Or ControlStyles.AllPaintingInWmPaint, True)
            Me.PerformLayout()
        End Sub
     
        Public Sub New()
            MyBase.New()
            InitializeMe()
        End Sub
     
        Public Property ColorDeactiveItem As Color = Color.LightGray
        Public Property ColorActiveItem As Color = Color.Black
     
        Private _textFormatFlags As TextFormatFlags = TextFormatFlags.VerticalCenter Or TextFormatFlags.Left
     
        Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
            Dim ctrlRectangle As Rectangle = Me.ClientRectangle
            Dim buttonW As Integer = 15
            Dim border As Integer = 5
            Dim textRectange As Rectangle = ctrlRectangle
            textRectange.Width -= buttonW
            textRectange.Width -= border
            Dim buttonRectangle As Rectangle = Rectangle.FromLTRB(textRectange.Right + border, textRectange.Top, ctrlRectangle.Right, textRectange.Bottom)
            Using br As Brush = New SolidBrush(BackColor)
                e.Graphics.FillRectangle(br, ctrlRectangle)
            End Using
            Dim sf As StringFormat = New StringFormat(StringFormatFlags.NoWrap)
            sf.LineAlignment = StringAlignment.Center
            Using br As Brush = New SolidBrush(ForeColor)
                e.Graphics.DrawString("OKiOkiText", Font, br, textRectange, sf)
            End Using
            Me.DropDownWidth = GetDropDownWidth()
            ComboBoxRenderer.DrawDropDownButton(e.Graphics, buttonRectangle, ComboBoxState.Normal)
        End Sub
     
        Public Function GetDropDownWidth() As Integer
            Dim w As Integer = ClientRectangle.Width
            For Each s As Object In Items
                Dim curW As Integer = TextRenderer.MeasureText(s.ToString(), Font).Width
                If curW > w Then
                    w = curW
                End If
            Next
            Return w
        End Function
     
        Protected Overrides Sub OnDrawItem(ByVal e As DrawItemEventArgs)
            If e.Index < 0 OrElse e.State = DrawItemState.ComboBoxEdit Then
                Return
            End If
            Dim g As Graphics = e.Graphics
            Dim ctrlRectangle As Rectangle = e.Bounds
            Dim buttonW As Integer = 0
            Dim border As Integer = 0
            Dim textRectange As Rectangle = ctrlRectangle
            textRectange.Width -= buttonW
            textRectange.Width -= border
            Dim textToPaint As String = ""
            Using br As Brush = New SolidBrush(e.BackColor)
                g.FillRectangle(br, ctrlRectangle)
            End Using
            Dim drawColor As Color = _ColorDeactiveItem
            If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
                drawColor = _ColorActiveItem
            End If
            Using br As Brush = New SolidBrush(drawColor)
                g.FillRectangle(br, textRectange)
            End Using
            If e.Index <> -1 AndAlso Items.Count > 0 Then
                textToPaint = GetItemText(Items(e.Index))
                Using br As Brush = New SolidBrush(e.ForeColor)
                    e.Graphics.DrawString(textToPaint, e.Font, br, textRectange)
                End Using
            End If
        End Sub
    End Class

    PS. Среда:
    — VS2010 Ultimate, а у вас, как я понял, версия Express
    — NET 4.0 Client, м.б. попробовать поставить полную версию NET 4.0



    0



    Uswer

    1644 / 1147 / 292

    Регистрация: 26.06.2017

    Сообщений: 3,110

    04.02.2021, 23:01

     [ТС]

    7

    Решено.
    ovva, спасибо за помощь. Кому будет интересно почему у меня (и возможно у Вас) так, то внимательно читаем ms-доки . Дело в стиле темы оформления операционной системы, если включен классический стиль, то имеем InvalidOperationException при вызове методов класса ComboBoxRenderer.

    Ну и в догонку как правильно решить задачку:

    VB.NET
    1
    2
    3
    4
    5
    
    If Not ComboBoxRenderer.IsSupported Then
        ControlPaint.DrawComboButton(e.Graphics, buttonRectangle, ButtonState.Normal)
    Else
        ComboBoxRenderer.DrawDropDownButton(e.Graphics, buttonRectangle, ComboBoxState.Normal)
    End If

    P.S. Для меня остаётся загадкой почему ComboBoxRenderer не реализует отрисовку элементов для классического стиля.



    1



    IT_Exp

    Эксперт

    87844 / 49110 / 22898

    Регистрация: 17.06.2006

    Сообщений: 92,604

    04.02.2021, 23:01

    Помогаю со студенческими работами здесь

    Сообщение об ошибке: «Не удалось запустить приложение, поскольку его параллельная конфигурация неправильная»
    Всех приветствую. Пожалуйста помогите разобраться с проблемой:cry:. Вот только сегодня установил…

    Операция горизонтального отображения прямоугольной матрицы
    Можете помочь?
    Нужно написать функцию для операции горизонтального отображения прямоугольной…

    Очередь: операция удаления и отображения текущего состояния
    2. Розробити програму роботи з чергою, яка реалізує операції додавання, видалення елементів з черги…

    Стек: операция удаления и отображения текущего состояния
    1. Розробити програму роботи зі стеком, яка реалізує операції додавання, видалення елементів зі…

    Visual Studio 2013: С# Debug — не может начать отладку, поскольку цель отладки отсутствует
    Всем привет!
    У меня такая проблема, вообщем я установил визуал студио 2013, и начал учить С#,…

    Visual studio 2015 Не удалось запустить приложение, поскольку его параллельная конфигурация неправильная
    Здравствуйте.

    Установила приложение visual studio 2015 и выдает такую ошибку : Не удалось…

    Искать еще темы с ответами

    Или воспользуйтесь поиском по форуму:

    7

    While I look at my code, I wanted to provide the complete exception and the look at the TabControl after I click «Continue» on the exception dialog:

    See the end of this message for details on invoking

    just-in-time (JIT) debugging instead of this dialog box.

     

    ************** Exception Text **************

    System.InvalidOperationException: Visual Styles-related operation resulted in an error because no visual style is currently active.

       at System.Windows.Forms.VisualStyles.VisualStyleRenderer.IsCombinationDefined(String className, Int32 part)

       at System.Windows.Forms.VisualStyles.VisualStyleRenderer..ctor(String className, Int32 part, Int32 state)

       at System.Windows.Forms.VisualStyles.VisualStyleRenderer..ctor(VisualStyleElement element)

       at TabContol2.CustomTabControl.DrawControl(Graphics g)

       at TabContol2.CustomTabControl.OnPaint(PaintEventArgs e)

       at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)

       at System.Windows.Forms.Control.WmPaint(Message& m)

       at System.Windows.Forms.Control.WndProc(Message& m)

       at System.Windows.Forms.TabControl.WndProc(Message& m)

       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)

       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)

       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

     

     

    ************** Loaded Assemblies **************

    mscorlib

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll

    —————————————-

    DeliveryDispatch

        Assembly Version: 1.0.3810.17731

        Win32 Version: 1.0.3810.17731

        CodeBase: file:///C:/Exit41/DeliveryDispatch/Program/DeliveryDispatch.exe

    —————————————-

    System

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll

    —————————————-

    System.Windows.Forms

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll

    —————————————-

    System.Drawing

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll

    —————————————-

    Microsoft.VisualBasic

        Assembly Version: 8.0.0.0

        Win32 Version: 8.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/Microsoft.VisualBasic/8.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.dll

    —————————————-

    PizzaPilotRuntime

        Assembly Version: 1.0.0.0

        Win32 Version: 1.0.0.0

        CodeBase: file:///C:/Exit41/DeliveryDispatch/Program/PizzaPilotRuntime.DLL

    —————————————-

    System.Data

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_32/System.Data/2.0.0.0__b77a5c561934e089/System.Data.dll

    —————————————-

    System.Transactions

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_32/System.Transactions/2.0.0.0__b77a5c561934e089/System.Transactions.dll

    —————————————-

    System.EnterpriseServices

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_32/System.EnterpriseServices/2.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll

    —————————————-

    System.Configuration

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll

    —————————————-

    System.Xml

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll

    —————————————-

    System.Web.Services

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Web.Services/2.0.0.0__b03f5f7f11d50a3a/System.Web.Services.dll

    —————————————-

    DeliveryDispatch.XmlSerializers

        Assembly Version: 1.0.3810.17731

        Win32 Version: 1.0.3810.17731

        CodeBase: file:///C:/Exit41/DeliveryDispatch/Program/DeliveryDispatch.XmlSerializers.DLL

    —————————————-

    DDClientRuntime

        Assembly Version: 1.0.0.0

        Win32 Version: 1.0.0.0

        CodeBase: file:///C:/Exit41/DeliveryDispatch/Program/DDClientRuntime.DLL

    —————————————-

    DDClientCommon

        Assembly Version: 1.0.0.0

        Win32 Version: 1.0.0.0

        CodeBase: file:///C:/Exit41/DeliveryDispatch/Program/DDClientCommon.DLL

    —————————————-

    log4net

        Assembly Version: 1.2.10.0

        Win32 Version: 1.2.10.0

        CodeBase: file:///C:/Exit41/DeliveryDispatch/Program/log4net.DLL

    —————————————-

    -vxbr1yj

        Assembly Version: 1.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll

    —————————————-

    DDClientLib

        Assembly Version: 1.0.0.0

        Win32 Version: 1.0.0.0

        CodeBase: file:///C:/Exit41/DeliveryDispatch/Program/DDClientLib.DLL

    —————————————-

    System.Messaging

        Assembly Version: 2.0.0.0

        Win32 Version: 2.0.50727.42 (RTM.050727-4200)

        CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Messaging/2.0.0.0__b03f5f7f11d50a3a/System.Messaging.dll

    —————————————-

     

    ************** JIT Debugging **************

    To enable just-in-time (JIT) debugging, the .config file for this

    application or computer (machine.config) must have the

    jitDebugging value set in the system.windows.forms section.

    The application must also be compiled with debugging

    enabled.

     

    For example:

     

    <configuration>

        <system.windows.forms jitDebugging=»true» />

    </configuration>

     

    When JIT debugging is enabled, any unhandled exception

    will be sent to the JIT debugger registered on the computer

    rather than be handled by this dialog box.

    VisualStylesException.png

      I got this error on my (normally stable) application after it had been running overnight.  Attached is a stack trace.   Could it be a bug in the toolbar?

    System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.InvalidOperationException: Visual Styles-related operation resulted in an error because no visual style is currently active.
       at System.Windows.Forms.VisualStyles.VisualStyleRenderer.IsCombinationDefined(String className, Int32 part)
       at System.Windows.Forms.VisualStyles.VisualStyleRenderer..ctor(String className, Int32 part, Int32 state)
       at System.Windows.Forms.VisualStyles.VisualStyleRenderer..ctor(VisualStyleElement element)
       at Infragistics.Win.FormattedLinkLabel.PositionElementsCache.MeasureTextGDIOrThemed(String text, Font font, TextFormatFlags textFormatFlags)
       at Infragistics.Win.FormattedLinkLabel.PositionElementsCache.MeasureCharacterRangesGDI(String text, Font font, TextFormatFlags textFormatFlags, CharacterRange[] ranges)
       at Infragistics.Win.FormattedLinkLabel.PositionElementsCache.ReMeasureParts(String text, Int32[] parts, Single[] widths, Int32 partStartIndex, Int32 partEndIndex, Font font, Single& lineHeight)
       at Infragistics.Win.FormattedLinkLabel.PositionElementsCache.MeasureParts(String text, Int32[] parts, Font font, Single& lineHeight)
       at Infragistics.Win.FormattedLinkLabel.NodeText.TextLayoutInfo.Measure(PositionElementsInfo& info)
       at Infragistics.Win.FormattedLinkLabel.NodeText.PositionSelf(PositionElementsInfo& info)
       at Infragistics.Win.FormattedLinkLabel.NodeBase.PositionHelper(PositionElementsInfo& info)
       at Infragistics.Win.FormattedLinkLabel.NodeBase.Position(PositionElementsInfo& info)
       at Infragistics.Win.FormattedLinkLabel.NodeBase.PositionChildNodes(PositionElementsInfo& info)
       at Infragistics.Win.FormattedLinkLabel.NodeBlock.PositionChildNodes(PositionElementsInfo& info)
       at Infragistics.Win.FormattedLinkLabel.NodeBase.PositionHelper(PositionElementsInfo& info)
       at Infragistics.Win.FormattedLinkLabel.NodeBase.Position(PositionElementsInfo& info)
       at Infragistics.Win.FormattedLinkLabel.NodeBase.CalcSize(IFormattedLinkLabelOwner owner, Graphics graphics, Int32 maxWidth)
       at Infragistics.Win.FormattedLinkLabel.ParsedFormattedTextValue.CalcSize(Graphics graphics, Font baseFont, AppearanceData& defaultAppearance, Int32 widthConstraint, DefaultableBoolean wrapText, GdiDrawStringFlags gdiDrawStringFlags)
       at Infragistics.Win.UltraWinToolbars.Ribbon.RibbonMetrics.CalculateCaptionAreaHeight()
       at Infragistics.Win.UltraWinToolbars.Ribbon.RibbonMetrics.get_CaptionAreaHeight()
       at Infragistics.Win.UltraWinToolbars.Ribbon.RibbonMetrics.get_RibbonHeight()
       at Infragistics.Win.UltraWinToolbars.UltraToolbarsDockArea.RefreshDockAreaSize(Size& currentSize)
       at Infragistics.Win.UltraWinToolbars.UltraToolbarsDockArea.RefreshDockAreaSize()
       at Infragistics.Win.UltraWinToolbars.UltraToolbarsDockArea.DirtyChildElements()
       at Infragistics.Win.UltraWinToolbars.UltraToolbarsManager.DirtyChildElements(Boolean delegateToMdiParent)
       at Infragistics.Win.UltraWinToolbars.UltraToolbarsManager.DirtyChildElements()
       at Infragistics.Win.UltraWinToolbars.UltraToolbarsManager.DirtyAllElements()
       at Infragistics.Win.UltraWinToolbars.UltraToolbarsManagerRole.OnStyleChanged()
       at Infragistics.Win.AppStyling.ComponentRole.ClearCache(Boolean notifyOwner)
       at Infragistics.Win.AppStyling.ComponentRole.OnAppStyleChanged(Object sender, StyleChangedEventArgs e)
       — End of inner exception stack trace —
       at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at Infragistics.Win.WeakReferenceMulticastDelegate`1.WeakReferenceProxyEventHandler.OnEventFired(Object sender, EventArgsType e, Type delegateType)
       at Infragistics.Win.WeakReferenceMulticastDelegate`1.Invoke(Object sender, EventArgsType e)
       at Infragistics.Win.AppStyling.StyleManager.NotifyThemeChanged()
       at Infragistics.Win.XPThemes.OnThemeChangeMessage(Object sender, EventArgs e)
       at Infragistics.Win.XPThemes.ThemeManagerForm.OnThemeChanged(EventArgs e)
       at Infragistics.Win.XPThemes.ThemeManagerForm.OnNotifyMessage(Message m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.PeekMessage(MSG& msg, HandleRef hwnd, Int32 msgMin, Int32 msgMax, Int32 remove)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)

    Понравилась статья? Поделить с друзьями:
  • Visual studio ошибка c4996
  • Visual studio неизвестная ошибка при установке
  • Visual studio как изменить цветовую схему
  • Visual studio как изменить цвет кнопки
  • Visual studio как изменить горячие клавиши