Link to home
Create AccountLog in
Avatar of MaKaVeLi_Da_DoN
MaKaVeLi_Da_DoN

asked on

VB .NET Problem

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.

Code:

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()
            MyBase.New()
            If m_vb6FormDefInstance Is Nothing Then
                  If m_InitializingDefInstance Then
                        m_vb6FormDefInstance = Me
                  Else
                        Try
                              '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
                        Catch
                        End Try
                  End If
            End If
            'This call is required by the Windows Form Designer.
            InitializeComponent()
      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
                        components.Dispose()
                  End If
            End If
            MyBase.Dispose(Disposing)
      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"
            Me.Controls.Add(List1)
            Me.Controls.Add(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
            Get
                  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
            Set
                  m_vb6FormDefInstance = Value
            End Set
      End Property
#End Region
      
      Private Const WTS_CURRENT_SERVER_HANDLE As Short = 0
      
      Private Enum WTS_CONNECTSTATE_CLASS
            WTSActive
            WTSConnected
            WTSConnectQuery
            WTSShadow
            WTSDisconnected
            WTSIdle
            WTSListen
            WTSReset
            WTSDown
            WTSInit
      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))
            Marshal.FreeHGlobal(p_objTarget)


                  WTSFreeMemory(lpBuffer)
                  
            Else
                  ' 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))
                  List1.Items.Add(("***********"))
                  
                  
                  '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
Avatar of ptakja
ptakja
Flag of United States of America image

Hard to tell off hand.  I would enable Option STRICT and then look at that section of code to see what the IDE ( I'm assuming you are using Visual Studio) underlines.  An invalid cast simply means that you are trying to use a variable in a method in which it can't be used.  In other words, if you are passing an Integer pointer into a function that expects a float pointer.  The compiler can't cast an integer into a float.
Avatar of MaKaVeLi_Da_DoN
MaKaVeLi_Da_DoN

ASKER

Ok
In the following piece of code i get the error.
The problem is that I am a beginner and i don't know what to do.

code:

            p_objTarget = Marshal.AllocHGlobal(Marshal.SizeOf(arrSessionInfo(0)))
            CopyMemory(p_objTarget, p, pCount * Marshal.SizeOf(arrSessionInfo(0)))
at "p_objTarget" I get - Option Strict On disallows implicit conversions from 'System.Object' to 'System.IntPtr'.
at "p" I get - Option Strict On disallows implicit conversions from 'System.Object' to 'Integer'.
            Marshal.PtrToStructure(p_objTarget, arrSessionInfo(0))
            Marshal.FreeHGlobal(p_objTarget)
            WTSFreeMemory(ppSessionInfo)
at "ppSessionInfo" - Option Strict On disallows implicit conversions from 'System.Object' to 'Integer'.

I don't know how to correct this and what "System.Object" is.
I am kind if stupid, you know.
I dind't noticed that "System.Object" is a type.
However when converting from object to integer the CopyMemory function fails, and I don't know why
ASKER CERTIFIED SOLUTION
Avatar of ptakja
ptakja
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer