I have a .NET VB winforms program that open the service database, after convert from .NET v2 to v4 this stopped working. Function openscmanager from advapi32.dll returns invalid handle when called from VB .NET v4 and above.
All works OK compiled for .NET v2 to v3.5, but fails when compiled for .NET V4 and above on same machine
Using Visual Studio V2013 or V2015 on Windows Server 2012 R2 with .NET 4.5.1 and 4.6.1 installed Interesting enough the same code works fine under Windows 7 64 bit also with same framework versions installed
Stripped down code:
Imports System.Runtime.InteropServices
Public Class Form1
Const SC_MANAGER_CREATE_SERVICE As Int32 = &H2
Dim scHandle As Int32 = 0
Declare Function OpenSCManager Lib "advapi32.dll" Alias "OpenSCManagerA" _
(ByVal lpMachineName As String, _
ByVal lpDatabaseName As String, _
ByVal dwDesiredAccess As Integer) As Int32
Declare Function CloseServiceHandle Lib "advapi32.dll" Alias "CloseServiceHandle" _
(ByVal hSCObject As IntPtr) As Boolean
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
scHandle = OpenSCManager(".", Nothing, SC_MANAGER_CREATE_SERVICE)
scHandle = CloseServiceHandle(scHandle)
MsgBox(New System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).ToString)
End Sub
End Class
Compiled under .NET v2 returns:
"System.ComponentModel.Win32Exception: The operation completed successfully"
Compiled under .NET v4 returns:
"System.ComponentModel.Win32Exception (0x80004005): The handle is invalid"
Any ideas about how to come around this ?
OK I got it. Changing Int32 to UInt64 does the trick. After this change programs compiled to "anycpu" under .Net V4 and above works with all windows versions and I have tested both 32 and 64 bit versions.
Case closed.