I've recreated some of the OpenNetCF components like PowerManagement and DeviceStatusMonitor. But since they never raised any events I suspected that something was wrong. My first thought was to check the P2PMessageQueue which they both depends on. And then BAM, the CreateMsgQueue returns IntPtr.Zero. Checking for the last Win32Error gives me an error code of value -2147467259 (minus).
Is this just another generic error code that doesn't provide any hints?
Any help would be appreciated.
(FYI: WinCE 5.0, CF 2.0)
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim lpName As String = "MyQueue"
Dim lpOptions As MSGQUEUEOPTIONS = New MSGQUEUEOPTIONS()
Dim hMsgQ As IntPtr = IntPtr.Zero
lpOptions.bReadAccess = True
lpOptions.dwMaxMessages = 0
lpOptions.cbMaxMessage = &H1000
lpOptions.dwFlags = MSGQUEUE_ALLOW_BROKEN
lpOptions.dwSize = Marshal.SizeOf(lpOptions)
hMsgQ = CreateMsgQueue(lpName, lpOptions)
If (hMsgQ = IntPtr.Zero) Then
Throw New Win32Exception(Marshal.GetLastWin32Error())
Else
CloseMsgQueue(hMsgQ)
End If
Catch ex As Win32Exception
MessageBox.Show(String.Format(String.Format("Win32Exception: {0}", ex.ErrorCode)))
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
<DllImport("coredll.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Private Shared Function CloseMsgQueue(ByVal hMsgQ As IntPtr) As Boolean
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Private Shared Function CreateMsgQueue(<MarshalAs(UnmanagedType.LPWStr)> ByVal lpName As String, ByVal lpOptions As MSGQUEUEOPTIONS) As IntPtr
End Function
<StructLayout(LayoutKind.Sequential)> _
Private Structure MSGQUEUEOPTIONS
Public dwSize As Integer
Public dwFlags As Integer
Public dwMaxMessages As Integer
Public cbMaxMessage As Integer
Public bReadAccess As Boolean
End Structure
Private Const MSGQUEUE_ALLOW_BROKEN As Integer = 2
Private Const MSGQUEUE_NOPRECOMMIT As Integer = 1
Private Const MSGQUEUE_MSGALERT As Integer = 1
End Class
The lpOptions parameter is declared incorrectly. You declare it as ByVal but it should be ByRef.
That said, -2147467259 is a bit of an oddity. That's not a Win32 error code. That's a COM HRESULT. Specifically it's 0x80004005. Which is the COM wrapper around the Win32 ERROR_ACCESS_DENIED. Not sure where you get a COM HRESULT from in this code mind you, but it would appear that you don't have sufficient rights for what you are attempting.
Related
I want to call function MoveFile from "Kernel32.dll".
1)First approach:
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("KERNEL32.DLL", EntryPoint:="MoveFileW", SetLastError:=True, CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)>
Public Shared Function MoveFile(ByVal src As String, ByVal dst As String) As Boolean
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim src As String = "C:\Users\Baha1990\Documents\Visual Studio 2017\Projects\WindowsApp1\TEST FILE\1\MSACCESS.accdb"
Dim dst As String = "C:\Users\Baha1990\Documents\Visual Studio 2017\Projects\WindowsApp1\TEST FILE\2\MSACCESS.accdb"
Dim RetVal As Boolean = MoveFile(src, dst)
End Sub
End Class
It works pretty well
Second approach:
Imports System.Runtime.InteropServices
Public Class Form1
<Runtime.InteropServices.DllImport("kernel32.dll", SetLastError:=True)> Private Shared Function LoadLibrary(ByVal lpFileName As String) As IntPtr
End Function
<Runtime.InteropServices.DllImport("kernel32.dll", SetLastError:=True, CharSet:=Runtime.InteropServices.CharSet.Ansi, ExactSpelling:=True)> Private Shared Function GetProcAddress(ByVal hModule As IntPtr, ByVal procName As String) As IntPtr
End Function
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Public Delegate Function _MoveFile(ByVal src As String, ByVal dst As String) As Boolean
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim src As String = "C:\Users\Baha1990\Documents\Visual Studio 2017\Projects\WindowsApp1\TEST FILE\1\MSACCESS.accdb"
Dim dst As String = "C:\Users\Baha1990\Documents\Visual Studio 2017\Projects\WindowsApp1\TEST FILE\2\MSACCESS.accdb"
Dim pDll As IntPtr = IntPtr.Zero
pDll = LoadLibrary("kernel32.dll")
Dim pProc2D = GetProcAddress(pDll, "MoveFileW")
Dim MoveFile = Marshal.GetDelegateForFunctionPointer(pProc2D, GetType(_MoveFile))
Dim RetVal = MoveFile.DynamicInvoke(src, dst) 'Here I get boolean as false it should be true
or
Dim RetVal = MoveFile.Method.Invoke(What to pass here in my case?)
End Sub
End Class
So Question: What is difference between DLLImport and DynamicInvoke or Method.Invoke, and why I have fail with DynamicInvoke and what params to pass to Method.Invoke?
Ok, in second approach I figure out that in this line:
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Needs additional params, after I edited as:
<UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError:=True, CharSet:=CharSet.Unicode)>
Dim RetVal = MoveFile.DynamicInvoke(src, dst) - DynamicInvoke works perfect.
So question what to pass as params to Method.Invoke still open.
Ok, I also figured out about Method.Invoke:
Dim param = {src, dst}
Dim RetVal = MoveFile.Method.Invoke(MoveFile, param) - works perfect.
So seems all three aproach works and gives same result, but what advantage gives these methods between each other. Who can explain?
My code using proxy works but when the proxy is invalid or restricted my program directly uses my IP address, i used a web browser that directly checks my ip, is there any way that i could set an exception whenever the proxy i used is invalid or restricted?
here is my working code:
Imports System.Runtime.InteropServices
#Region "Using Proxy"
<Runtime.InteropServices.DllImport("wininet.dll", SetLastError:=True)> _
Private Shared Function InternetSetOption(ByVal hInternet As IntPtr, ByVal dwOption As Integer, ByVal lpBuffer As IntPtr, ByVal lpdwBufferLength As Integer) As Boolean
End Function
Public Structure Struct_INTERNET_PROXY_INFO
Public dwAccessType As Integer
Public proxy As IntPtr
Public proxyBypass As IntPtr
End Structure
Private Sub UseProxy(ByVal strProxy As String)
Const INTERNET_OPTION_PROXY As Integer = 38
Const INTERNET_OPEN_TYPE_PROXY As Integer = 3
Dim struct_IPI As Struct_INTERNET_PROXY_INFO
struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY
struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy)
struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local")
Dim intptrStruct As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI))
Marshal.StructureToPtr(struct_IPI, intptrStruct, True)
Dim iReturn As Boolean = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI))
End Sub
#End Region
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UseProxy(ProxyText.Text)
WebBrowser1.Navigate("ipchicken.com")
End Sub
Try the solution below:
Another Stackoverflow Answer
I believe if you bind the address to that specific ip it wont work , if the ip is invalid or not working, and wont use your systems default.
I have an application which displays images and we're moving them to a different server. On the existing server, they can view as many images as they want and it won't ask them to log in again. On the new server, it asks them to log in before they can view an image even though the browser control has their credentials. If I take the value of the web browser's absoluteUri property and paste it into IE, it loads the image without asking to log in.
I'm trying to pass the userID and password credentials to the webBrowser control on my form by implementing IAuthenticate, and all the examples I found online are in C#. In trying to narrow down where the problem is, I've commented out the IAuthenticate implementation because it gets errors before the implementation is called. Right now I have:
Imports System.Runtime.InteropServices
<ComImport(),
Guid("00000112-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IOleObject
Sub SetClientSite(pClientSite As IOleClientSite)
Sub GetClientSite(ppClientSite As IOleClientSite)
Sub SetHostNames(szContainerApp As Object, szContainerObj As Object)
Sub Close(dwSaveOption As UInteger)
Sub SetMoniker(dwWhichMoniker As UInteger, pmk As Object)
Sub GetMoniker(dwAssign As UInteger, dwWhichMoniker As UInteger, ppmk As Object)
Sub InitFromData(pDataObject As IDataObject, fCreation As Boolean, dwReserved As UInteger)
Sub GetClipboardData(dwReserved As UInteger, ppDataObject As IDataObject)
Sub DoVerb(iVerb As UInteger, lpmsg As UInteger, pActiveSite As Object, lindex As UInteger, hwndParent As UInteger, lprcPosRect As UInteger)
Sub EnumVerbs(ppEnumOleVerb As Object)
Sub Update()
Sub IsUpToDate()
Sub GetUserClassID(pClsid As UInteger)
Sub GetUserType(dwFormOfType As UInteger, pszUserType As UInteger)
Sub SetExtent(dwDrawAspect As UInteger, psizel As UInteger)
Sub GetExtent(dwDrawAspect As UInteger, psizel As UInteger)
Sub Advise(pAdvSink As Object, pdwConnection As UInteger)
Sub Unadvise(dwConnection As UInteger)
Sub EnumAdvise(ppenumAdvise As Object)
Sub GetMiscStatus(dwAspect As UInteger, pdwStatus As UInteger)
Sub SetColorScheme(pLogpal As Object)
End Interface
<ComImport(),
Guid("00000118-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IOleClientSite
Sub SaveObject()
Sub GetMoniker(ByVal dwAssign As Integer, ByVal dwWhichMoniker As Integer, ByRef ppmk As Object)
Sub GetContainer(ByRef ppContainer As Object)
Sub ShowObject()
Sub OnShowWindow(ByVal fShow As Boolean)
Sub RequestNewObjectLayout()
End Interface
<ComImport(),
Guid("6d5140c1-7436-11ce-8034-00aa006009fa"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IServiceProvider
<PreserveSig()>
Sub QueryService(ByRef guidService As Guid, ByRef riid As Guid,
<Out(), MarshalAs(UnmanagedType.Interface)> ByRef ppvObject As Object)
End Interface
<ComImport> _
<Guid("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B")> _
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IAuthenticate
'<MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)
Sub Authenticate(phwnd As IntPtr,
<MarshalAs(UnmanagedType.LPWStr)> ByRef pszUsername As String,
<MarshalAs(UnmanagedType.LPWStr)> ByRef pszPassword As String)
End Interface
Public Class frmIE
Implements IOleClientSite
Implements IServiceProvider
Public Shared IID_IAuthenticate As New Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b")
Private _user As String
Private _pwd As String
Friend WriteOnly Property url(user As String, pwd As String) As System.Uri
Set(ByVal value As System.Uri)
Dim oc As IOleObject
webIE.Navigate("about:blank") ' iAuthenticate not always called on first run
oc = DirectCast(webIE.ActiveXInstance, IOleObject)
' if I comment the following line out, it loads the image ok and asks for credentials
oc.SetClientSite(DirectCast(Me, IOleClientSite)) ' instead of trycast, so can see error: An unhandled exception of type 'System.ExecutionEngineException' occurred in System.Windows.Forms.dll
_user = user
_pwd = pwd
webIE.Navigate(value)
End Set
End Property
Public Sub GetContainer(ByRef ppContainer As Object) Implements IOleClientSite.GetContainer
ppContainer = Me ' doesn't reach stop placed here
End Sub
Public Sub GetMoniker(dwAssign As Integer, dwWhichMoniker As Integer, ByRef ppmk As Object) Implements IOleClientSite.GetMoniker
Dim i As Integer
i = 0 ' doesn't reach stop placed here
End Sub
Public Sub OnShowWindow(fShow As Boolean) Implements IOleClientSite.OnShowWindow
Dim i As Integer
i = 0 ' doesn't reach stop placed here
End Sub
Public Sub RequestNewObjectLayout() Implements IOleClientSite.RequestNewObjectLayout
Dim i As Integer
i = 0 ' doesn't reach stop placed here
End Sub
Public Sub SaveObject() Implements IOleClientSite.SaveObject
Dim i As Integer
i = 0 ' doesn't reach stop placed here
End Sub
Public Sub ShowObject() Implements IOleClientSite.ShowObject
Dim i As Integer
i = 0 ' doesn't reach stop placed here
End Sub
Public Sub QueryService(ByRef guidService As System.Guid, ByRef riid As System.Guid,
<Out(), MarshalAs(UnmanagedType.Interface)> ByRef ppvObject As Object) Implements IServiceProvider.QueryService
If guidService.CompareTo(IID_IAuthenticate) = 0 AndAlso riid.CompareTo(IID_IAuthenticate) = 0 Then
'ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IAuthenticate)) ' doesn't reach stop placed here
Else
ppvObject = IntPtr.Zero ' does reach stop placed here, 2x
' 1st guid is 4c96be40-915c-11cf-99d3-00aa004ae837 = SID_SToplevelBrowser
' 1st riid is 02ba3b52-0547-11d1-b833-00c04fc9b31f
' 2nd guid is SID_SToplevelBrowser
' 2nd riid is 6d5140c1-7436-11ce-8034-00aa006009fa
End If
End Sub
End Class
but it's giving me an error on the line
oc.SetClientSite(DirectCast(Me, IOleClientSite))
saying "An unhandled exception of type 'System.ExecutionEngineException' occurred in System.Windows.Forms.dll" Which looks like a generic error that could have many causes.
I'm assuming I've missed some declaration or usage detail, but I can't tell where or if that's even really the problem.
All help appreciated,
-Beth
We ended up passing the navigate method of the webBrowser object a string instead of a new system.uri object, and that fixed it for us.
When i am Running this Block of code it runs, however when i try to change the running process memory address's string value to somethinhg else it give me an error:
"System.IndexoutofRangeException Index was outside the Bounds of the Array"
These are the Functions:
<DllImport("kernel32.dll", SetLastError:=True)> _
Public Shared Function WriteProcessMemory(ByVal hProcess As IntPtr, ByVal lpBaseAddress As IntPtr, ByVal lpBuffer As Byte(), ByVal nSize As System.UInt32, <Out()> ByRef lpNumberOfBytesWritten As Int32) As Boolean
End Function
Public Shared Function StrToByteArray(ByVal str As String) As Byte()
Dim encoding As New System.Text.ASCIIEncoding()
Return encoding.GetBytes(str)
End Function
Public Shared Function Poke(ByVal proc As Process, ByVal target As Integer, ByVal data As Byte()) As Boolean
Return WriteProcessMemory(proc.Handle, New IntPtr(target), data, data.Length, 0)
End Function
This is the button which executes the changed memory address value string.
Private Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
Try
Dim p As Process() = Process.GetProcessesByName(AppName.Text)
Dim Written As Boolean = False
Written = Poke(p(0), &HB8FDCC, StrToByteArray(TxtVal.Text))
If Written = True Then
MsgBox("WriteProcessMemory Sucess!", MsgBoxStyle.OkOnly, "Poke Memory Status")
ElseIf Written = False Then
MsgBox("WriteProcessMemory Failed!", MsgBoxStyle.OkOnly, "Poke Memory Status")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Do not add the extension of program/application in the name of Process,
in your case, for Chrome
AppName.Text must be "Chrome" instead of "Chrome.exe",
Good Luck.
I have the following code as part of my control. SetReaderMode function creates the structure and calls the function explained here, http://msdn.microsoft.com/en-us/library/bb775599(VS.85).aspx
When I run this code, i get the error
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I'm not sure what the issue may be. What am I doing wrong?
<DllImport("Comctl32.dll", EntryPoint:="#383", _
CallingConvention:=CallingConvention.StdCall)> _
Private Shared Sub DoReaderMode(prmi As READERMODEINFO)
End Sub
<StructLayout(LayoutKind.Sequential)>
Private Structure READERMODEINFO
Dim cbSize As UInt32
Dim hwnd As IntPtr
Dim fFlags As UInt32
Dim prc As IntPtr
Dim pfnScroll As ReaderScrollCallbackDelegate
Dim fFlags2 As TranslateDispatchCallbackDelegate
Dim lParam As IntPtr
End Structure
Private Sub SetReaderMode()
Dim Info As New READERMODEINFO
Info.hwnd = Me.Handle
Info.fFlags = 0
Info.prc = IntPtr.Zero
Info.pfnScroll = New ReaderScrollCallbackDelegate(AddressOf ReaderScrollCallback)
Info.fFlags2 = New TranslateDispatchCallbackDelegate(AddressOf TranslateDispatchCallback)
Info.lParam = IntPtr.Zero
Info.cbSize = Marshal.SizeOf(Info)
DoReaderMode(Info)
End Sub
Private Delegate Function ReaderScrollCallbackDelegate(ByVal prmi As READERMODEINFO, dx As Integer, dy As Integer) As Boolean
Private Delegate Function TranslateDispatchCallbackDelegate(lpmsg As IntPtr) As Boolean
<AllowReversePInvokeCalls()>
Private Function TranslateDispatchCallback(lpmsg As IntPtr) As Boolean
Return True
End Function
<AllowReversePInvokeCalls()>
Private Function ReaderScrollCallback(ByVal prmi As READERMODEINFO, dx As Int32, dy As Int32) As Boolean
Return True
End Function
Is not an easy nut to crack. Assuming the callback are correct in term of signature/calling convention, a problem can be that since the carbage collector collect Info at the end of the function SetReaderMode, the callback address becames invalid. So try to declare Info as a member variable. If the error remain callback signature has something wrong, but as I said, not so easy to see the error at a glance.
I've figured it out. After reviewing the documentation more closely, I've added a ByRef to the DoReaderMode definition and to the ReaderScrollCallback definition, since the arguments where defined as pointers to structures, not just structures. I also added some other code to pass the rectangle in the ReaderModeInfo structure.
Below is the working code. Interestingly, the documentation states that you click to exit ReaderMode, however when testing it looks like you have to hold the button down and release to exit.
<DllImport("Comctl32.dll", EntryPoint:="#383", _
CallingConvention:=CallingConvention.StdCall)> _
Private Shared Sub DoReaderMode(ByRef prmi As READERMODEINFO)
End Sub
<StructLayout(LayoutKind.Sequential)>
Private Structure READERMODEINFO
Dim cbSize As UInt32
Dim hwnd As IntPtr
Dim fFlags As UInt32
Dim prc As IntPtr
Dim pfnScroll As ReaderScrollCallbackDelegate
Dim fFlags2 As TranslateDispatchCallbackDelegate
Dim lParam As IntPtr
End Structure
Private Sub SetReaderMode()
Dim SetReaderModeInfo As READERMODEINFO
Dim rect As New Interop.RECT(Me.Width / 2 - 20, Me.Height / 2 - 20, Me.Width / 2 + 20, Me.Height / 2 + 20)
Dim pnt As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(rect))
Marshal.StructureToPtr(rect, pnt, True)
SetReaderModeInfo = New READERMODEINFO
SetReaderModeInfo.hwnd = Me.Handle
SetReaderModeInfo.fFlags = 1
SetReaderModeInfo.prc = pnt
SetReaderModeInfo.pfnScroll = New ReaderScrollCallbackDelegate(AddressOf ReaderScrollCallback)
SetReaderModeInfo.fFlags2 = New TranslateDispatchCallbackDelegate(AddressOf TranslateDispatchCallback)
SetReaderModeInfo.lParam = IntPtr.Zero
SetReaderModeInfo.cbSize = Marshal.SizeOf(SetReaderModeInfo)
DoReaderMode(SetReaderModeInfo)
Marshal.FreeHGlobal(pnt)
End Sub
Private Delegate Function ReaderScrollCallbackDelegate(ByRef prmi As READERMODEINFO, dx As Integer, dy As Integer) As Boolean
Private Delegate Function TranslateDispatchCallbackDelegate(ByRef lpmsg As Interop.MSG) As Boolean
Private Function TranslateDispatchCallback(ByRef lpmsg As Interop.MSG) As Boolean
Return False
End Function
Private Function ReaderScrollCallback(ByRef prmi As READERMODEINFO, dx As Int32, dy As Int32) As Boolean
Return True
End Function