I have a code in VB coded in Microsoft Visual Studio 2015 unfortunately I have an error when running the program.
Here's the error:
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\PC_6\Documents\Visual Studio 2015\Projects\Test\test\bin\Debug\Test.vshost.exe'.
Additional information: A call to PInvoke function 'Test!Test.Form1::InternetGetConnectedState' has unbalanced the stack.
Here's my code.
Imports System.Runtime.InteropServices
Public Class Form1
Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef conn As Long, ByVal val As Long) As Boolean
Private Sub btnPay_Click(sender As Object, e As EventArgs) Handles btnPay.Click
Select Case ListBox1.SelectedIndex
Case 0
MsgBox("Selected Payment is " + ListBox1.SelectedItem)
Case 1
MsgBox("Selected Payment is " + ListBox1.SelectedItem)
Case 2
btnPay.Text = ("Checking Connection")
Dim Out As Integer
If InternetGetConnectedState(Out, 0) = True Then
MsgBox("Connected!")
Else
MsgBox("No Connection!")
End If
Case Else
MsgBox("Please Select a Payment Type")
End Select
End Sub
End Class
The documentation for InternetGetConnectedState ( https://msdn.microsoft.com/en-us/library/windows/desktop/aa384702%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 ) shows it accepts LPDWORD and DWORD arguments, in .NET the equivalents are out UInt32 (or ref) and UInt32 respectively.
Change your signature to this:
Public Enum InternetConnection As UInt32
None = 0,
Configured = &H40,
Lan = &H02,
Modem = &H01,
ModemBusy = &H08,
Offline = &H20,
Proxy = &H04,
RasInstalled = &H10
End Enum
Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef flags As InternetConnection, ByVal reserved As UInt32) As Boolean
And called like so:
Dim result As Boolean
InternetConnection flags;
result = InternetGetConnectedState( flags, 0 );
If result = False Then
' TODO: Call GetLastError to eliminate other causes of failure before determining it is indeed due to a lack of an internet connection
End If
Related
I have a large vb.net x86 project that is running in VS2015 and .Net 4.5.2
When it is compiled and run in debug without optimization then it works ok. However if I compile and run it in Release mode with optimization turned on then I get a variety of exceptions at the same innocuous line of code. I have tried debugging it in release mode but the breakpoints are unreliable. Also the very act of debugging it seems to modify the exception. Also if I change the code (for example putting a MsgBox in to display information) then the problem can go away. For example I changed an Arraylist to a List(Of Control) and the problem no longer occurred where it did before but now moved elsewhere.
I have received all of the following at different times:
AccessViolationException,
NullReferenceException (somewhere deep within .Net classes)
and FatalExecutionEngineError
The exception detail in the AccessViolationException tells nothing except that "this is often an indication that other memory is corrupt". The stack trace is meaningless and there is no description of what it thought was at the invalid memory address.
I also cannot find any meaningful detail about what Optimization in the compiler actually does - one solution might be to turn Optimization off but I don't understand what the benefit / negative effect is of doing this.
Is the Optimization unreliable? How can one possibly try and ascertain what is happening?
The only unmanaged code we use is some calls to get Icons related to file extensions - which are then cloned into managed objects and the unmanaged memory destroyed. This is pretty standard and the same API has been used since 1.1 and through 4.5.2 for 10 years without this occurring before.
I cannot create a small project that reproduces the issue
Here's the code we use for extracting icons as it's the only potential cause I have right now. It was borrowed from elsewhere and I can't really tell whether it's as good as it should be:
Public Class IconExtractor
<Flags()> Private Enum SHGFI
SmallIcon = &H1
LargeIcon = &H0
Icon = &H100
DisplayName = &H200
Typename = &H400
SysIconIndex = &H4000
UseFileAttributes = &H10
End Enum
<StructLayout(LayoutKind.Sequential)>
Private Structure SHFILEINFO
Public hIcon As IntPtr
Public iIcon As Integer
Public dwAttributes As Integer
<MarshalAs(UnmanagedType.LPStr, SizeConst:=260)> Public szDisplayName As String
<MarshalAs(UnmanagedType.LPStr, SizeConst:=80)> Public szTypeName As String
Public Sub New(ByVal B As Boolean)
hIcon = IntPtr.Zero
iIcon = 0
dwAttributes = 0
szDisplayName = vbNullString
szTypeName = vbNullString
End Sub
End Structure
Private Declare Auto Function SHGetFileInfo Lib "shell32" (
ByVal pszPath As String, ByVal dwFileAttributes As Integer,
ByRef psfi As SHFILEINFO, ByVal cbFileInfo As Integer, ByVal uFlags As SHGFI) As Integer
<DllImport("user32.dll", SetLastError:=True)>
Private Shared Function DestroyIcon(ByVal hIcon As IntPtr) As Boolean
End Function
Public Shared Sub GetIconsForFile(ByVal rstrFileName As String, ByRef rzSmallIcon As Icon, ByRef rzLargeIcon As Icon)
Dim zFileInfo As New SHFILEINFO(True)
Dim cbSizeInfo As Integer = Marshal.SizeOf(zFileInfo)
Dim flags As SHGFI = SHGFI.Icon Or SHGFI.UseFileAttributes Or SHGFI.SmallIcon
SHGetFileInfo(rstrFileName, 256, zFileInfo, cbSizeInfo, flags)
' Use clone so we can destroy immediately
rzSmallIcon = DirectCast(Icon.FromHandle(zFileInfo.hIcon).Clone, Icon)
DestroyIcon(zFileInfo.hIcon)
zFileInfo = New SHFILEINFO(True)
cbSizeInfo = Marshal.SizeOf(zFileInfo)
flags = SHGFI.Icon Or SHGFI.UseFileAttributes Or SHGFI.LargeIcon
SHGetFileInfo(rstrFileName, 256, zFileInfo, cbSizeInfo, flags)
' Use clone so we can destroy immediately
rzLargeIcon = DirectCast(Icon.FromHandle(zFileInfo.hIcon).Clone, Icon)
DestroyIcon(zFileInfo.hIcon)
End Sub
End Class
I stumbled across the solution to this by chance.
I was reading this documentation of SHGETFILEINFO
https://msdn.microsoft.com/en-us/library/windows/desktop/bb762179(v=vs.85).aspx
and found that it said in the remarks: You should call this function from a background thread. Failure to do so could cause the UI to stop responding
It isn't clear why you should call it from a background thread nor is it clear what "stop responding" might actually manifest itself as.
However it seemed this was fairly likely what was causing the problem and so I refactored to execute the api call under a separate thread. This has certainly seemed to work. Many of the examples on the internet of SHGETFILEINFO do not seem to consider the separate thread requirement.
I reproduce the whole refactored code here:
Imports System.Drawing
Imports System.Runtime.InteropServices
Imports System.Threading
''' <summary>
''' Retrieves the small and large icons registered for a filename based on the file's extension
''' </summary>
Public Class FileIcons
Private mFileName As String
Private mSmallIconHandle As IntPtr
Private mSmallIcon As Icon
Private mLargeIconHandle As IntPtr
Private mLargeIcon As Icon
Public Sub New(ByVal rFileName As String)
mFileName = rFileName
Dim t As New Thread(AddressOf GetIconsForFile)
t.SetApartmentState(ApartmentState.STA)
t.Start()
t.Join()
' Use clone so we can destroy immediately
mSmallIcon = DirectCast(Icon.FromHandle(mSmallIconHandle).Clone, Icon)
DestroyIcon(mSmallIconHandle)
' Use clone so we can destroy immediately
mLargeIcon = DirectCast(Icon.FromHandle(mLargeIconHandle).Clone, Icon)
DestroyIcon(mLargeIconHandle)
End Sub
Public ReadOnly Property SmallIcon As Icon
Get
Return mSmallIcon
End Get
End Property
Public ReadOnly Property LargeIcon As Icon
Get
Return mLargeIcon
End Get
End Property
Private Sub GetIconsForFile()
' Go and extract the small and large icons
' Full filename must be < MAX_PATH - which is 260 chars in .Net (apparently) though a file path/length of 256 also causes an error.
' Otherwise SHGetFileInfo gets nothing, Icon.FromHandle then gives "System.ArgumentException: The Win32 handle you passed to Icon is invalid or of the wrong type."
' This needs to be stopped in the calling code, or the resulting error trapped
Dim zFileInfo As New SHFILEINFO(True)
Dim cbSizeInfo As Integer = Marshal.SizeOf(zFileInfo)
Dim flags As SHGFI = SHGFI.Icon Or SHGFI.UseFileAttributes Or SHGFI.SmallIcon
SHGetFileInfo(mFileName, 256, zFileInfo, cbSizeInfo, flags)
mSmallIconHandle = zFileInfo.hIcon
zFileInfo = New SHFILEINFO(True)
cbSizeInfo = Marshal.SizeOf(zFileInfo)
flags = SHGFI.Icon Or SHGFI.UseFileAttributes Or SHGFI.LargeIcon
SHGetFileInfo(mFileName, 256, zFileInfo, cbSizeInfo, flags)
mLargeIconHandle = zFileInfo.hIcon
End Sub
#Region "WinAPI"
<Flags()> Private Enum SHGFI
SmallIcon = &H1
LargeIcon = &H0
Icon = &H100
DisplayName = &H200
Typename = &H400
SysIconIndex = &H4000
UseFileAttributes = &H10
End Enum
<StructLayout(LayoutKind.Sequential)>
Private Structure SHFILEINFO
Public hIcon As IntPtr
Public iIcon As Integer
Public dwAttributes As Integer
<MarshalAs(UnmanagedType.LPStr, SizeConst:=260)> Public szDisplayName As String
<MarshalAs(UnmanagedType.LPStr, SizeConst:=80)> Public szTypeName As String
Public Sub New(ByVal B As Boolean)
hIcon = IntPtr.Zero
iIcon = 0
dwAttributes = 0
szDisplayName = vbNullString
szTypeName = vbNullString
End Sub
End Structure
Private Declare Auto Function SHGetFileInfo Lib "shell32" (
ByVal pszPath As String,
ByVal dwFileAttributes As Integer,
ByRef psfi As SHFILEINFO,
ByVal cbFileInfo As Integer,
ByVal uFlags As SHGFI) As Integer
<DllImport("user32.dll", SetLastError:=True)>
Private Shared Function DestroyIcon(ByVal hIcon As IntPtr) As Boolean
End Function
#End Region
End Class
I'm re-visiting a tool that I wrote in VB.Net for my helpdesk team a while back and want to add a couple of checkboxes to replicate the same function that Windows uses to show hidden files and folders / re-hide, as well as protected operating system files.
I know I can do this by editing a registry entry and restarting explorer.exe, but that closes all open Explorer Windows and I don't want that.
Does anyone know how Windows is able to do this by a simple click of a checkbox and how I may be able to code it in VB.net?
Any input on this is greatly appreciated in advance.
EDIT: So it looks like I have found a refresh method that works to refresh Windows Explorer / File Explorer which can be applied to Drarig's answer below but I am having trouble converting it to VB.net as the original example is in C#.
'Original at http://stackoverflow.com/questions/2488727/refresh-windows-explorer-in-win7
Private Sub refreshExplorer(ByVal explorerType As String)
Dim CLSID_ShellApplication As Guid = Guid.Parse("13709620-C279-11CE-A49E-444553540000")
Dim shellApplicationType As Type = Type.GetTypeFromCLSID(CLSID_ShellApplication, True)
Dim shellApplication As Object = Activator.CreateInstance(shellApplicationType)
Dim windows As Object = shellApplicationType.InvokeMember("Windows", Reflection.BindingFlags.InvokeMethod, Nothing, shellApplication, New Object() {})
Dim windowsType As Type = windows.GetType()
Dim count As Object = windowsType.InvokeMember("Count", Reflection.BindingFlags.GetProperty, Nothing, windows, Nothing)
For i As Integer = 0 To CType(count, Integer)
Dim item As Object = windowsType.InvokeMember("Item", Reflection.BindingFlags.InvokeMethod, Nothing, windows, New Object() {i})
Dim itemType As Type = item.GetType()
'Only fresh Windows explorer Windows
Dim itemName As String = CType(itemType.InvokeMember("Name", Reflection.BindingFlags.GetProperty, Nothing, item, Nothing), String)
If itemName = explorerType Then
itemType.InvokeMember("Refresh", Reflection.BindingFlags.InvokeMethod, Nothing, item, Nothing)
End If
Next
End Sub
I am getting an exception Object reference not set to an instance of an object when I set itemType as Type = item.GetType() above. I can't figure out which object isn't being created. When I step through the code it looks like windowsType contains an object for windows. Does anyone have any idea on this? Once this is worked out I can then apply it to Drarig's solution below.
Alright I wish I could have got this to you sooner, but busy lately at work. I took a little time today to figure this out as I love digging into something I have not done before. This is the whole class from a new project; didn't have time to wrap it up in a separate class. I am sure this will get you what you need. It was a little harder than I thought as getting the correct handle and then send the command, but I got it. I hope you find it useful.
P.S. Some of the things you can leave out, specifically the boolean used for loading, this was so I can pull the current value back on load and either check/uncheck the CheckBox.
Note: This is tried and tested on Windows 7, 8 and 10
Imports Microsoft.Win32
Imports System.Reflection
Imports System.Runtime.InteropServices
Public Class Form1
<Flags()> _
Public Enum KeyboardFlag As UInteger
KEYBOARDF_5 = &H74
End Enum
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetWindow(ByVal hl As Long, ByVal vm As Long) As IntPtr
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function PostMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Boolean
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
Private blnLoading As Boolean = False
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
Form1.HideFilesExtension(Me.CheckBox1.Checked)
If Not blnLoading Then NotifyFileAssociationChanged()
RefreshExplorer()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim name As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(name, False)
blnLoading = True
Me.CheckBox1.Checked = CBool(key.GetValue("Hidden"))
key.Close()
blnLoading = False
End Sub
Private Shared Sub HideFilesExtension(ByVal Hide As Boolean)
Dim name As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(name, True)
key.SetValue("Hidden", If(Hide, 1, 0))
key.Close()
End Sub
Public Shared Sub RefreshExplorer()
Dim clsid As New Guid("13709620-C279-11CE-A49E-444553540000")
Dim typeFromCLSID As Type = Type.GetTypeFromCLSID(clsid, True)
Dim objectValue As Object = Activator.CreateInstance(typeFromCLSID)
Dim obj4 As Object = typeFromCLSID.InvokeMember("Windows", BindingFlags.InvokeMethod, Nothing, objectValue, New Object(0 - 1) {})
Dim type1 As Type = obj4.GetType
Dim obj2 As Object = type1.InvokeMember("Count", BindingFlags.GetProperty, Nothing, obj4, Nothing)
If (CInt(obj2) <> 0) Then
Dim num2 As Integer = (CInt(obj2) - 1)
Dim i As Integer = 0
Do While (i <= num2)
Dim obj5 As Object = type1.InvokeMember("Item", BindingFlags.InvokeMethod, Nothing, obj4, New Object() {i})
Dim type3 As Type = obj5.GetType
Dim str As String = CStr(type3.InvokeMember("Name", BindingFlags.GetProperty, Nothing, obj5, Nothing))
If (str = "File Explorer") Then
type3.InvokeMember("Refresh", BindingFlags.InvokeMethod, Nothing, obj5, Nothing)
End If
i += 1
Loop
End If
End Sub
Public Shared Sub NotifyFileAssociationChanged()
'Find the actual window...
Dim hwnd As IntPtr = FindWindow("Progman", "Program Manager")
'Get the window handle and refresh option...
Dim j = GetWindow(hwnd, 3)
'Finally post the message...
PostMessage(j, 256, KeyboardFlag.KEYBOARDF_5, 3)
End Sub
End Class
Here's a solution for everything excepting the refreshing of the explorer.
I've translated the code, but I'm unable to find how to refresh the explorer/desktop without restarting it.
Const keyName As String = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Const Hidden As String = "Hidden"
Const SHidden As String = "ShowSuperHidden"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim St As Integer = GetRegValue(Hidden)
If St = 2 Then
SetRegValue(Hidden, 1)
SetRegValue(SHidden, 1)
Else
SetRegValue(Hidden, 2)
SetRegValue(SHidden, 0)
End If
End Sub
Private Function GetRegValue(valueName As String) As Integer
Return CInt(My.Computer.Registry.GetValue(keyName, valueName, 0))
End Function
Private Sub SetRegValue(valueName As String, value As Integer)
My.Computer.Registry.SetValue(keyName, valueName, value, Microsoft.Win32.RegistryValueKind.DWord)
End Sub
I have a few ideas to refresh the desktop :
Send a key to a running process. I tried this (source) :
Dim pp As Process() = Process.GetProcessesByName("explorer")
If pp.Length > 0 Then
For Each p In pp
AppActivate(p.Id)
SendKeys.SendWait("{F5}")
Next
End If
Refresh using SHChangeNotify (source),
Refresh broadcasting a WM_SETTINGCHANGE message (source),
etc.
I think you'll be forced to manually refresh or restart the explorer.
This question already has answers here:
VB.NET and sizeof
(3 answers)
Closed 8 years ago.
I am trying to convert the C# code given in this link. I got some errors after conversion, but i have corrected some. Still i get error for the line cbSize = sizeof(TOKEN_ELEVATION_TYPE)
The errors are:
'sizeof' is not declared. It may be inaccessible due to its protection level. D:\Desktop\WindowsApplication3\WindowsApplication3\Form1.vb 103 26 WindowsApplication3
'TOKEN_ELEVATION_TYPE' is a type and cannot be used as an expression. D:\Desktop\WindowsApplication3\WindowsApplication3\Form1.vb 103 33 WindowsApplication3
I tried using Len instead of sizeof, but the second error still exists. So can anyone help me to solve both errors. Below is the VB.NET code which has said error.
Imports System.Runtime.InteropServices
Imports System.Security.Principal
Imports System.ComponentModel
Public Class Form1
Public Const TOKEN_DUPLICATE As UInt32 = &H2
Public Const TOKEN_IMPERSONATE As UInt32 = &H4
Public Const TOKEN_QUERY As UInt32 = &H8
Public Declare Function GetTokenInformation Lib "advapi32.dll" ( _
ByVal TokenHandle As IntPtr, ByVal TokenInformationClass As TOKEN_INFORMATION_CLASS, _
ByVal TokenInformation As IntPtr, ByVal TokenInformationLength As System.UInt32, _
ByRef ReturnLength As System.UInt32) As Boolean
Declare Function DuplicateToken Lib "advapi32.dll" (ExistingTokenHandle As IntPtr, _
SECURITY_IMPERSONATION_LEVEL As Int16, ByRef DuplicateTokenHandle As IntPtr) _
As Boolean
Enum TOKEN_ELEVATION_TYPE
TokenElevationTypeDefault = 1
TokenElevationTypeFull
TokenElevationTypeLimited
End Enum
Public Enum TOKEN_INFORMATION_CLASS
TokenUser = 1
TokenGroups
TokenPrivileges
TokenOwner
TokenPrimaryGroup
TokenDefaultDacl
TokenSource
TokenType
TokenImpersonationLevel
TokenStatistics
TokenRestrictedSids
TokenSessionId
TokenGroupsAndPrivileges
TokenSessionReference
TokenSandBoxInert
TokenAuditPolicy
TokenOrigin
TokenElevationType
TokenLinkedToken
TokenElevation
TokenHasRestrictions
TokenAccessInformation
TokenVirtualizationAllowed
TokenVirtualizationEnabled
TokenIntegrityLevel
TokenUIAccess
TokenMandatoryPolicy
TokenLogonSid
MaxTokenInfoClass
' MaxTokenInfoClass should always be the last enum
End Enum
Public Enum SECURITY_IMPERSONATION_LEVEL
SecurityAnonymous
SecurityIdentification
SecurityImpersonation
SecurityDelegation
End Enum
Function IsAdmin() As Boolean
Dim identity = WindowsIdentity.GetCurrent()
Return (identity IsNot Nothing AndAlso New WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator))
End Function
''' <summary>
''' The function checks whether the primary access token of the process belongs
''' to user account that is a member of the local Administrators group, even if
''' it currently is not elevated.
''' </summary>
''' <returns>
''' Returns true if the primary access token of the process belongs to user
''' account that is a member of the local Administrators group. Returns false
''' if the token does not.
''' </returns>
Function CanBeAdmin() As Boolean
Dim fInAdminGroup As Boolean = False
Dim hToken As IntPtr = IntPtr.Zero
Dim hTokenToCheck As IntPtr = IntPtr.Zero
Dim pElevationType As IntPtr = IntPtr.Zero
Dim pLinkedToken As IntPtr = IntPtr.Zero
Dim cbSize As Integer = 0
If IsAdmin() Then
Return True
End If
Try
' Check the token for this user
hToken = WindowsIdentity.GetCurrent().Token
' Determine whether system is running Windows Vista or later operating
' systems (major version >= 6) because they support linked tokens, but
' previous versions (major version < 6) do not.
If Environment.OSVersion.Version.Major >= 6 Then
' Running Windows Vista or later (major version >= 6).
' Determine token type: limited, elevated, or default.
' Allocate a buffer for the elevation type information.
cbSize = sizeof(TOKEN_ELEVATION_TYPE)
Dim cbSizeuint As UInteger = Convert.ToUInt32(cbSize)
pElevationType = Marshal.AllocHGlobal(cbSize)
If pElevationType = IntPtr.Zero Then
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
' Retrieve token elevation type information.
If Not GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType, cbSizeuint, cbSizeuint) Then
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
' Marshal the TOKEN_ELEVATION_TYPE enum from native to .NET.
Dim elevType As TOKEN_ELEVATION_TYPE = CType(Marshal.ReadInt32(pElevationType), TOKEN_ELEVATION_TYPE)
' If limited, get the linked elevated token for further check.
If elevType = TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited Then
' Allocate a buffer for the linked token.
cbSize = IntPtr.Size
Dim cbSizeuint_ee As UInteger = Convert.ToUInt32(cbSize)
pLinkedToken = Marshal.AllocHGlobal(cbSize)
If pLinkedToken = IntPtr.Zero Then
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
' Get the linked token.
If Not GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken, cbSizeuint_ee, cbSizeuint_ee) Then
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
' Marshal the linked token value from native to .NET.
hTokenToCheck = Marshal.ReadIntPtr(pLinkedToken)
End If
End If
' CheckTokenMembership requires an impersonation token. If we just got
' a linked token, it already is an impersonation token. If we did not
' get a linked token, duplicate the original into an impersonation
' token for CheckTokenMembership.
If hTokenToCheck = IntPtr.Zero Then
If Not DuplicateToken(hToken, CInt(SECURITY_IMPERSONATION_LEVEL.SecurityIdentification), hTokenToCheck) Then
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
End If
' Check if the token to be checked contains admin SID.
Dim id As New WindowsIdentity(hTokenToCheck)
Dim principal As New WindowsPrincipal(id)
fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator)
Catch
Return False
Finally
' Centralized cleanup for all allocated resources.
If pElevationType <> IntPtr.Zero Then
Marshal.FreeHGlobal(pElevationType)
pElevationType = IntPtr.Zero
End If
If pLinkedToken <> IntPtr.Zero Then
Marshal.FreeHGlobal(pLinkedToken)
pLinkedToken = IntPtr.Zero
End If
End Try
Return fInAdminGroup
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs)
If CanBeAdmin() Then
MessageBox.Show("admin")
Else
MessageBox.Show("not admin")
End If
End Sub
End Class
You can get the effect of C# cbSize = sizeof(TOKEN_ELEVATION_TYPE) using Marshal.SizeOf to get the size of the underlying type.
Dim undertype As Type = [Enum].GetUnderlyingType(GetType(TOKEN_ELEVATION_TYPE))
cbSize = System.Runtime.InteropServices.Marshal.SizeOf(undertype)
When I ran it, undertype was System.Int32, and cbSize was 4.
I'm writing a code using vb.net that can get some information from a radar sensor connected to the computer through a device called CANcaseXL ,, I added the dll file reference corresponding to the CANcaseXL driver and in the manual there is a command that let me print the information that goes to the CANcaseXL to the console (the command is xlPrintRx(XLClass.xl_event receivedEvent)) and its a continuous real-time data going from the radar to the computer through the CANcaseXL.
Now I can see the data in the console but I need to extract it like print it to a textbox maybe then do the calculations but I don't know how.
I will appreciate any help !
this like the main code I have been working on, I got most of it using the XL Driver Library - .NET Wrapper Description >> http://www.labviewforum.de/attachment.php?aid=43764 and a ready made application.
Option Explicit On
Imports System
Imports System.Runtime.InteropServices
Imports System.Threading
Imports vxlapi_NET20
Imports System.IO
Public Class Main
Region "DLL_Import"
<DllImport("kernel32.dll", SetLastError:=True)> _
Shared Function WaitForSingleObject(ByVal handle As Integer, ByVal timeOut As Integer) As Integer
End Function
End Region
Region "GLOBALS"
Shared CANDemo_TxChannel As xlSingleChannelCAN_Port
Shared CANDemo_RxChannel As xlSingleChannelCAN_Port
Private RxThread As Thread
Private Enum WaitResults : int
WAIT_ABANDONED = &H80
WAIT_FAILED = &HFFFFFFF
WAIT_OBJECT_0 = &H0
WAIT_TIMEOUT = &H102
INFINITE = &HFFFF
End Enum
End Region
Declare Function AllocConsole Lib "kernel32" () As Int32
Declare Function FreeConsole Lib "kernel32" () As Int32
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AllocConsole()
ProgressBar1.Value = 0
Dim Max As Double
Dim Min As Double
Dim id As String
Dim dlc As String
Dim data As String
Max = Val(TextBox1.Text)
Min = Val(TextBox2.Text)
id = Val(TextBox3.Text)
dlc = Val(TextBox4.Text)
data = TextBox5.Text
If data = "" Then
data = 0
End If
Dim Max_hex As Double = Val("&H" & Max)
Dim Min_hex As Double = Val("&H" & Min)
If (Max < 1 Or Min < 0) Then
MsgBox("Please fill the range fields!!", MsgBoxStyle.Critical)
GoTo C
End If
CANDemo_TxChannel = New xlSingleChannelCAN_Port("xlCANdemo NET", Convert.ToUInt32(0))
CANDemo_RxChannel = New xlSingleChannelCAN_Port("xlCANdemo NET", Convert.ToUInt32(0))
If (CANDemo_TxChannel.xlCheckPort() And CANDemo_RxChannel.xlCheckPort()) Then
Label10.BackColor = Color.Green
Label11.Text = "CAN Connected ..."
' these two commands print the configuration for the CANcaseXL device
CANDemo_TxChannel.xlPrintConfig()
CANDemo_RxChannel.xlPrintConfig()
CANDemo_RxChannel.xlResetAcceptanceFilter()
CANDemo_RxChannel.xlCanAddAcceptanceRange(Convert.ToUInt32(Min_hex), Convert.ToUInt32(Max_hex))
CANDemo_TxChannel.xlActivate()
CANDemo_RxChannel.xlActivate()
Dim RxThread As New Thread(AddressOf RX_Thread)
RxThread.Start()
If MsgBox("Are you sure you wont to transmit ?", MsgBoxStyle.YesNo, "Transmission") = MsgBoxResult.Yes Then
CANDemo_TxChannel.xlTransmit(Convert.ToUInt32(id, 16), Convert.ToUInt16(dlc, 16), Convert.ToUInt64(data, 16))
ProgressBar1.Value = 100
MsgBox("Data Transmited!", MsgBoxStyle.Information, "Transmission")
Else
End If
Else
Label10.BackColor = Color.Red
Label11.Text = "CAN Disconnected!!"
MsgBox("Check the device connection!", MsgBoxStyle.Critical, "CAN disconnected")
CANDemo_TxChannel.xlClosePort()
CANDemo_RxChannel.xlClosePort()
End If
C:
End Sub
Region "EVENT THREAD (RX)"
Public Shared Sub RX_Thread()
Dim receivedEvent As XLClass.xl_event = New XLClass.xl_event
Dim xlStatus As XLClass.XLstatus = XLClass.XLstatus.XL_SUCCESS
Dim waitResult As WaitResults
While (True)
waitResult = WaitForSingleObject(CANDemo_RxChannel.eventHandle, 1000)
If (waitResult <> WaitResults.WAIT_TIMEOUT) Then
xlStatus = XLClass.XLstatus.XL_SUCCESS
While (xlStatus <> XLClass.XLstatus.XL_ERR_QUEUE_IS_EMPTY)
xlStatus = CANDemo_RxChannel.xlReceive(receivedEvent)
If (xlStatus = XLClass.XLstatus.XL_SUCCESS) Then
' this command let the coming results from the Radar printed to the console
CANDemo_RxChannel.xlPrintRx(receivedEvent)
End If
End While
End If
End While
End Sub
End Region
I am wanting to retrieve all the files in some directories. Here is my original code:
Private Function Search(path As String, Recursive As Boolean) As Boolean
Dim dirInfo As New IO.DirectoryInfo(path)
Dim fileObject As FileSystemInfo
If Recursive = True Then
For Each fileObject In dirInfo.GetFileSystemInfos()
If fileObject.Attributes = FileAttributes.Directory Then
Search(fileObject.FullName, Recursive)
Else
lstFiles.Items.Add(fileObject.FullName)
End If
Next
Else
For Each fileObject In dirInfo.GetFileSystemInfos()
lstFiles.Items.Add(fileObject.FullName)
Next
End If
Return True
End Function
This code works well, yet it returns some directories and I am wanting to only return files.
I tried this code:
Private Sub Search(ByVal path As String, ByVal Recursive As Boolean)
if not Directory.Exists(path) then Exit Sub
Dim initDirInfo As New DirectoryInfo(path)
For Each oFileInfo In initDirInfo.GetFiles
lstfiles.items.add(oFileInfo.Name)
Next
If Recursive Then
For Each oDirInfo In initDirInfo.GetDirectories
Search(oDirInfo.FullName, True)
Next
End If
End Sub
However, i get the following error:
Access to the path 'C:\Users\Simon\AppData\Local\Application Data\' is denied.
Can someone help me with my original code, or help me access these directories with my new code?
thanks
EDIT:
I have added this module to get it working:
Imports System.Security.Principal
Module VistaSecurity
'Declare API
Private Declare Ansi Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As String) As Integer
Private Const BCM_FIRST As Int32 = &H1600
Private Const BCM_SETSHIELD As Int32 = (BCM_FIRST + &HC)
Public Function IsVistaOrHigher() As Boolean
Return Environment.OSVersion.Version.Major < 6
End Function
' Checks if the process is elevated
Public Function IsAdmin() As Boolean
Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim p As WindowsPrincipal = New WindowsPrincipal(id)
Return p.IsInRole(WindowsBuiltInRole.Administrator)
End Function
' Add a shield icon to a button
Public Sub AddShieldToButton(ByRef b As Button)
b.FlatStyle = FlatStyle.System
SendMessage(b.Handle, BCM_SETSHIELD, 0, &HFFFFFFFF)
End Sub
' Restart the current process with administrator credentials
Public Sub RestartElevated()
Dim startInfo As ProcessStartInfo = New ProcessStartInfo()
startInfo.UseShellExecute = True
startInfo.WorkingDirectory = Environment.CurrentDirectory
startInfo.FileName = Application.ExecutablePath
startInfo.Verb = "runas"
Try
Dim p As Process = Process.Start(startInfo)
Catch ex As Exception
Return 'If cancelled, do nothing
End Try
Application.Exit()
End Sub
End Module
The access denied errors are occurring at Windows Libraries I think. I don't think there is any way to list the file in these libraries as they aren't actually folders.