Как заставить работать мою пользовательскую кнопку VB.NET? - PullRequest
0 голосов
/ 18 августа 2010

Я сделал пользовательскую кнопку для ввода нажатий клавиш:

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class KeyInputButton
    Inherits System.Windows.Forms.Button

    'UserControl1 overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        components = New System.ComponentModel.Container()
        ' Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
    End Sub

End Class

Public Class KeyInputButton
    Public Event KeyCombinationChanged(ByVal sender As System.Object, ByVal kc As TestControls.KeyCombination)

    Private _KeyCombination As TestControls.KeyCombination = Nothing
    Public Property KeyCombination() As TestControls.KeyCombination
        Get
            Return _KeyCombination
        End Get
        Set(ByVal kc As TestControls.KeyCombination)
            _KeyCombination = kc
            Text = _KeyCombination.toString
        End Set
    End Property

    Public Sub New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub

    Private Sub Me_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        KeyCombination = New TestControls.KeyCombination(e.Control, e.Alt, e.Shift, e.KeyValue)
        RaiseEvent KeyCombinationChanged(Me, KeyCombination)
    End Sub
End Class

Когда я помещаю KeyInputButton в форму и запускаю отладчик, я получаю следующее исключение (такое же исключение в VS2005 и VS2010):

"System.InvalidOperationException was unhandled
  Message="Er is een fout opgetreden bij het maken van het formulier. Zie ExceptionInnerException voor details. De fout is: De objectverwijzing is niet op een exemplaar van een object ingesteld."
  Source="WindowsApplication1"
  StackTrace:
       bij WindowsApplication1.My.MyProject.MyForms.Create__Instance__[T](T Instance) in 17d14f5c-a337-4978-8281-53493378c1071.vb:regel 190
       bij WindowsApplication1.My.MyProject.MyForms.get_Form1()
       bij WindowsApplication1.My.MyApplication.OnCreateMainForm() in C:\Documents and Settings\Tetra\Mijn documenten\Visual Studio 2005\Projects\TestControls\WindowsApplication1\My Project\Application.Designer.vb:regel 35
       bij Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       bij Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       bij Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       bij WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:regel 81
       bij System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       bij System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       bij Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       bij System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       bij System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       bij System.Threading.ThreadHelper.ThreadStart()

Понятия не имею, как это исправить, я пытался все восстановить.Надеюсь, кто-то может помочь мне с этим.

РЕДАКТИРОВАТЬ: Класс KeyCombination:

Public Class KeyCombination
    Public Control As Boolean
    Public Alt As Boolean
    Public Shift As Boolean
    Public Value As Integer

    Private Const MOD_ALT = 1
    Private Const MOD_CONTROL = 2
    Private Const MOD_SHIFT = 4
    Public ReadOnly Property modifiers() As Integer
        Get
            If Not control And Not alt And shift Then
                Return MOD_SHIFT
            End If
            If Not control And alt And Not shift Then
                Return MOD_ALT
            End If
            If Not control And alt And shift Then
                Return MOD_ALT Or MOD_SHIFT
            End If
            If control And Not alt And Not shift Then
                Return MOD_CONTROL
            End If
            If control And Not alt And shift Then
                Return MOD_CONTROL Or MOD_SHIFT
            End If
            If control And alt And Not shift Then
                Return MOD_CONTROL Or MOD_ALT
            End If
            If control And alt And shift Then
                Return MOD_CONTROL Or MOD_ALT Or MOD_SHIFT
            End If
        End Get
    End Property


    Public Sub New(ByVal c As Boolean, ByVal a As Boolean, ByVal s As Boolean, ByVal v As Integer)
        Shift = s
        Control = c
        Alt = a
        Value = v
    End Sub

    Public Overrides Function toString() As String
        Dim Ret = ""
        If control Then
            ret += "Control + "
        End If
        If alt Then
            ret += "Alt + "
        End If
        If shift Then
            ret += "Shift + "
        End If
        Return Ret & System.Windows.Forms.Keys.GetName(GetType(System.Windows.Forms.Keys), Value)
    End Function
End Class

Ответы [ 3 ]

1 голос
/ 18 августа 2010

Я думаю, что проблема может быть в вашем TestControls.KeyCombination объекте.

Я могу вставить весь ваш код в приложение Windows Form и безошибочно поместить элемент управления в форму - при условии, что я создаю фиктивный класс с именем TestControls.KeyCombination .... это заставляет меня сделать вывод где-то там!

Edit: Хорошо, это (класс KeyCombination) также работает (он отображает название клавиши, которую я нажимаю) ... Я запустил элемент управления в форме следующим образом:

Dim testControl As New KeyInputButton()

Me.Controls.Add(testControl)

Вы можете попробовать это?
Что-то должно быть повреждено где-то по пути, может быть, каким-то образом вы добавили это в форму?

Edit: Ошибка связана с тем, что ваш метод toString вызывается до инициализации класса _KeyCombination, замените строку:

Text = _KeyCombination.toString

с

If Not IsNothing(_KeyCombination) Then
    Text = _KeyCombination.toString
End If
0 голосов
/ 18 августа 2010

В конце концов, ошибка была в классе KeyInputButton.Форма пыталась установить для свойства KeyCombination KeyInputButton значение Nothing.Когда это свойство установлено, для Text устанавливается значение KeyCombination.toString.Я исправил это, проверив, является ли KeyCombination Nothing перед установкой текста:

Public Property KeyCombination() As TestControls.KeyCombination
        Get
            Return _KeyCombination
        End Get
        Set(ByVal kc As TestControls.KeyCombination)
            _KeyCombination = kc
            If _KeyCombination IsNot Nothing Then
                Text = _KeyCombination.ToString
            End If
        End Set
    End Property

Я рад, что это наконец решено, но я действительно не понимаю, почему Исключение ничего не говорит оKeyInputButton class.

0 голосов
/ 18 августа 2010

Какой-то объект кажется нулевым.Вы пробовали пройти через приложение?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...