troubleshooting Question

VB .NET Problem

Avatar of MaKaVeLi_Da_DoN
MaKaVeLi_Da_DoN asked on
4 Comments1 Solution997 ViewsLast Modified:
I have converted a VB6 code to VB .NET with a help from some guy here, but the code gives me errors.

Search for "new code" in the following code to find the changed vb6 to vb .net code.
after running it gives me this error. Which is:
An unhandled exception of type 'System.InvalidCastException' occurred in TSQ.exe
Additional information: Specified cast is not valid.


Option Strict Off
Option Explicit On
Imports System.Runtime.InteropServices
Friend Class Form1
      Inherits System.Windows.Forms.Form
#Region "Windows Form Designer generated code "
      Public Sub New()
            If m_vb6FormDefInstance Is Nothing Then
                  If m_InitializingDefInstance Then
                        m_vb6FormDefInstance = Me
                              'For the start-up form, the first instance created is the default instance.
                              If System.Reflection.Assembly.GetExecutingAssembly.EntryPoint.DeclaringType Is Me.GetType Then
                                    m_vb6FormDefInstance = Me
                              End If
                        End Try
                  End If
            End If
            'This call is required by the Windows Form Designer.
      End Sub
      'Form overrides dispose to clean up the component list.
      Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
            If Disposing Then
                  If Not components Is Nothing Then
                  End If
            End If
      End Sub
      'Required by the Windows Form Designer
      Private components As System.ComponentModel.IContainer
      Public ToolTip1 As System.Windows.Forms.ToolTip
      Public WithEvents List1 As System.Windows.Forms.ListBox
      Public WithEvents Command1 As System.Windows.Forms.Button
      '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()
            Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
            Me.components = New System.ComponentModel.Container()
            Me.ToolTip1 = New System.Windows.Forms.ToolTip(components)
            Me.ToolTip1.Active = True
            Me.List1 = New System.Windows.Forms.ListBox
            Me.Command1 = New System.Windows.Forms.Button
            Me.Text = "TSQ"
            Me.ClientSize = New System.Drawing.Size(424, 317)
            Me.Location = New System.Drawing.Point(4, 23)
            Me.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.BackColor = System.Drawing.SystemColors.Control
            Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable
            Me.ControlBox = True
            Me.Enabled = True
            Me.KeyPreview = False
            Me.MaximizeBox = True
            Me.MinimizeBox = True
            Me.Cursor = System.Windows.Forms.Cursors.Default
            Me.RightToLeft = System.Windows.Forms.RightToLeft.No
            Me.ShowInTaskbar = True
            Me.HelpButton = False
            Me.WindowState = System.Windows.Forms.FormWindowState.Normal
            Me.Name = "Form1"
            Me.List1.Size = New System.Drawing.Size(369, 202)
            Me.List1.Location = New System.Drawing.Point(24, 24)
            Me.List1.TabIndex = 1
            Me.List1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.List1.BackColor = System.Drawing.SystemColors.Window
            Me.List1.CausesValidation = True
            Me.List1.Enabled = True
            Me.List1.ForeColor = System.Drawing.SystemColors.WindowText
            Me.List1.IntegralHeight = True
            Me.List1.Cursor = System.Windows.Forms.Cursors.Default
            Me.List1.SelectionMode = System.Windows.Forms.SelectionMode.One
            Me.List1.RightToLeft = System.Windows.Forms.RightToLeft.No
            Me.List1.Sorted = False
            Me.List1.TabStop = True
            Me.List1.Visible = True
            Me.List1.MultiColumn = False
            Me.List1.Name = "List1"
            Me.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
            Me.Command1.Text = "Command1"
            Me.Command1.Size = New System.Drawing.Size(97, 49)
            Me.Command1.Location = New System.Drawing.Point(8, 256)
            Me.Command1.TabIndex = 0
            Me.Command1.BackColor = System.Drawing.SystemColors.Control
            Me.Command1.CausesValidation = True
            Me.Command1.Enabled = True
            Me.Command1.ForeColor = System.Drawing.SystemColors.ControlText
            Me.Command1.Cursor = System.Windows.Forms.Cursors.Default
            Me.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No
            Me.Command1.TabStop = True
            Me.Command1.Name = "Command1"
      End Sub
#End Region
#Region "Upgrade Support "
      Private Shared m_vb6FormDefInstance As Form1
      Private Shared m_InitializingDefInstance As Boolean
      Public Shared Property DefInstance() As Form1
                  If m_vb6FormDefInstance Is Nothing OrElse m_vb6FormDefInstance.IsDisposed Then
                        m_InitializingDefInstance = True
                        m_vb6FormDefInstance = New Form1()
                        m_InitializingDefInstance = False
                  End If
                  DefInstance = m_vb6FormDefInstance
            End Get
                  m_vb6FormDefInstance = Value
            End Set
      End Property
#End Region
      Private Const WTS_CURRENT_SERVER_HANDLE As Short = 0
      End Enum
      Private Structure WTS_SESSION_INFO
            Dim SessionID As Integer
            Dim pWinStationName As Integer
            Dim state As Form1.WTS_CONNECTSTATE_CLASS
      End Structure
      Private Declare Function WTSEnumerateSessions Lib "wtsapi32.dll"  Alias "WTSEnumerateSessionsA"(ByVal hServer As Integer, ByVal Reserved As Integer, ByVal Version As Integer, ByRef ppSessionInfo As Integer, ByRef pCount As Integer) As Integer
      Private Declare Sub WTSFreeMemory Lib "wtsapi32.dll" (ByVal pMemory As Integer)
      'UPGRADE_ISSUE: Declaring a parameter 'As Any' is not supported. Click for more: 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="vbup1016"'
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef Destination As Object, ByRef Source As Object, ByVal length As Integer)
      Private Declare Function lstrlenA Lib "kernel32" (ByVal lpString As String) As Integer
      Private Declare Function lstrcpy Lib "kernel32"  Alias "lstrcpyA"(ByVal lpString1 As String, ByVal lpString2 As Integer) As Integer
      Private arrWTSSessions() As Form1.WTS_SESSION_INFO
      Private Function GetWTSSessions() As Form1.WTS_SESSION_INFO()
            Dim RetVal As Integer
            Dim lpBuffer As Integer
            Dim Count As Integer
            Dim p As Integer
            Dim arrSessionInfo() As Form1.WTS_SESSION_INFO
            RetVal = WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, lpBuffer, Count)
            If RetVal Then
                  ' WTSEnumerateProcesses was successful.
                  p = lpBuffer
            ReDim arrSessionInfo(Count - 1)

            'Old code
                  'UPGRADE_ISSUE: LenB function is not supported. Click for more: 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="vbup1040"'
                  'UPGRADE_WARNING: Couldn't resolve default property of object arrSessionInfo(). Click for more: 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="vbup1037"'
            'CopyMemory(arrSessionInfo(0), p, Count * LenB(arrSessionInfo(0)))
            ' Free the memory buffer.

            'New code
            Dim p_objTarget As IntPtr
            p_objTarget = Marshal.AllocHGlobal(Marshal.SizeOf(arrSessionInfo(0)))
            CopyMemory(p_objTarget, p, Count * Marshal.SizeOf(arrSessionInfo(0)))
            Marshal.PtrToStructure(p_objTarget, arrSessionInfo(0))

                  ' Error occurred calling WTSEnumerateProcesses.
                  ' Check Err.LastDllError for error code.
                  MsgBox("An error occurred calling WTSEnumerateProcesses.  " & "Check the Platform SDK error codes in the MSDN Documentation " & "for more information.", MsgBoxStyle.Critical, "ERROR " & Err.LastDllError)
            End If
            GetWTSSessions = VB6.CopyArray(arrSessionInfo)
      End Function
      Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click
            Dim i As Short
            arrWTSSessions = VB6.CopyArray(GetWTSSessions)
            For i = LBound(arrWTSSessions) To UBound(arrWTSSessions)
                  List1.Items.Add(("Session ID: " & arrWTSSessions(i).SessionID))
                  List1.Items.Add(("Machine Name: " & PointerToStringA(arrWTSSessions(i).pWinStationName)))
                  List1.Items.Add(("Connect State: " & arrWTSSessions(i).state))
                  'Debug.Print "Session ID: " & arrWTSSessions(i).SessionID
                  'Debug.Print "Machine Name: " & PointerToStringA (arrWTSSessions(i).pWinStationName)
                  'Debug.Print "Connect State: " & arrWTSSessions(i).state
                  'Debug.Print "***********"
            Next i
      End Sub
      Public Function PointerToStringA(ByVal lpStringA As Integer) As String
            Dim nLen As Integer
            Dim sTemp As String
            If lpStringA Then
                  nLen = lstrlenA(CStr(lpStringA))
                  If nLen Then
                        sTemp = New String(vbNullChar, nLen)
                        lstrcpy(sTemp, lpStringA)
                        PointerToStringA = sTemp
                  End If
            End If
      End Function
End Class
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros