How to use <DllImport> in VB.NET? - vb.net

How should I DLLImport things in VB.NET? An example would be:
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetWindowText(ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer
End Function
If I put it inside a Class or somewhere else, I get "DLLimport is not defined" I am using Visual Studio 2008 Professional

You have to add Imports System.Runtime.InteropServices to the top of your source file.
Alternatively, you can fully qualify attribute name:
<System.Runtime.InteropService.DllImport("user32.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _

Imports System.Runtime.InteropServices

I know this has already been answered, but here is an example for the people who are trying to use SQL Server Types in a vb project:
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Namespace SqlServerTypes
Public Class Utilities
<DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
Public Shared Function LoadLibrary(ByVal libname As String) As IntPtr
End Function
Public Shared Sub LoadNativeAssemblies(ByVal rootApplicationPath As String)
Dim nativeBinaryPath = If(IntPtr.Size > 4, Path.Combine(rootApplicationPath, "SqlServerTypes\x64\"), Path.Combine(rootApplicationPath, "SqlServerTypes\x86\"))
LoadNativeAssembly(nativeBinaryPath, "msvcr120.dll")
LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial140.dll")
End Sub
Private Shared Sub LoadNativeAssembly(ByVal nativeBinaryPath As String, ByVal assemblyName As String)
Dim path = System.IO.Path.Combine(nativeBinaryPath, assemblyName)
Dim ptr = LoadLibrary(path)
If ptr = IntPtr.Zero Then
Throw New Exception(String.Format("Error loading {0} (ErrorCode: {1})", assemblyName, Marshal.GetLastWin32Error()))
End If
End Sub
End Class
End Namespace

I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs statement to state that the StringBuffer is equivalent to LPSTR.
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function

You can also try this
Private Declare Function GetWindowText Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer
I always use Declare Function instead of DllImport...
Its more simply, its shorter and does the same

Related

FindWindowEx in VB.NET

I have a query, how can I kill a process with just the class name using FindWindowEx
If you have been able to reliably get a window handle back from calling FindWindowEx you can then use GetWindowThreadProcessId to find the ID of the process from the window handle.
Once you have the process ID you can find the Process by that ID and call Kill() on it. For example:
Imports System.Runtime.InteropServices
Imports System.Diagnostics
Module Module1
<DllImport("user32.dll", SetLastError:=True)>
Private Function GetWindowThreadProcessId(ByVal hwnd As IntPtr,
ByRef lpdwProcessId As Integer) As Integer
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Private Function FindWindowEx(ByVal parentHandle As IntPtr,
ByVal childAfter As IntPtr,
ByVal lclassName As String,
ByVal windowTitle As String) As IntPtr
End Function
Sub Main()
Dim hWnd As IntPtr = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Chrome_WidgetWin_0", "Spotify Premium")
Dim ProcessId As Integer
GetWindowThreadProcessId(hWnd, ProcessId)
If ProcessId <> 0 Then
Dim Process As Process = Process.GetProcessById(ProcessId)
Process.Kill()
End If
End Sub
End Module
The tricky part will be making sure that you can always get a window handle. Think about cases when there are multiple instances of the handle. You mention class name but it will likely also be necessary to supply the window title to FindWindowEx.
You may also need to consider what happens if calling Process.Kill() should throw an exception, for example, if the user that your program is running under doesn't have the rights to kill that particular process.

'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method

I'm trying to use some winapi methods. how ever, when I try to use the function I get the following error:
'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method.
code:
Public Class Anti
<DllImport("kernel32.dll", SetLastError:=True)> _
Public Function ReadProcessMemory(ByVal hProcess As IntPtr, ByVal lpBaseAdress As Integer, ByRef lpBuffer As Integer, ByVal nSize As Integer, Optional ByRef lpNumberOfBytesRead As Integer = 0) As Boolean
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Public Sub ZeroMemory(ByVal handle As IntPtr, ByVal length As UInt32)
End Sub
<DllImport("kernel32.dll", SetLastError:=True)> _
Public Function VirtualProtect(ByVal lpAddress As IntPtr, ByVal dwSize As Integer, ByVal flNewProtect As Integer, ByRef lpflOldProtect As UInteger) As Boolean
End Function
Public Sub AntiDump()
Try
Dim x(0) As Process
Well, the message is pretty clear. Methods that you apply the DllImport attribute to must be class methods (shared).

How to import and use functions from .dll to VB.NET? I have solution for this in VBA, but not for VB.NET?

I'm newbie in VB.NET. I have some application I have writed in VBA, and now want to transfer to VB.NET.
There is example how I'm declaring these .dll functions:
Public Declare Function loadsession Lib "vpmsdl32" (ByVal vpmname As String) As Long
Public Declare Function setvar Lib "vpmsdl32.dll" (ByVal session As Long, ByVal fieldname As String, ByVal value As String) As Long
Public Declare Function compute Lib "vpmsdl32.dll" (ByVal session As Long, ByVal what As String, ByVal result As String, ByVal result_buffer_size As Long, ByVal message As String, ByVal message_buffer_size As Long, ByVal fieldref As String, ByVal fieldref_buffer_size As Long) As Long
Public Declare Function closesession Lib "vpmsdl32.dll" (ByVal session As Long) As Long
Public Declare Function unloadall Lib "vpmsdl32" () As Long
I'm using this in VBA code in the way, for example, when I open the session with function loadsession:
session = loadsession("absolute-path-to-the-file")
set the input parameters:
ret = setvar(session, "Input name", "Input value")
(Hint: I don't have to declare variable ret) after that I perform computing with:
retcomp = compute(session, "Output name", result, 4000, msg, 1000, fieldref, 250)
(Hint: I also don't have to declare variable retcomp) After that, I get result of calculation in the variable result (It is not clear for me how it is possible to use variable for calling the function as output variable, for some reasons this function assign result of the computation to variable result, but it works!)
Now, I'm trying to implement the similar way in VB.NET application. First, I perform DLLImport of these functions:
Public Class PInvoke
<DllImport("vpmsdl32.dll", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function loadsession(ByVal vpmname As String) As Long
End Function
<DllImport("vpmsdl32.dll", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function setvar(ByVal session As Long, ByVal fieldname As String, ByVal value As String) As Long
End Function
<DllImport("vpmsdl32.dll", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function compute(ByVal session As Long, ByVal what As String, ByVal result As String, ByVal result_buffer_size As Long, ByVal message As String, ByVal message_buffer_size As Long, ByVal fieldref As String, ByVal fieldref_buffer_size As Long) As Long
End Function
<DllImport("vpmsdl32.dll", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function closesession(ByVal session As Long) As Long
End Function
<DllImport("vpmsdl32.dll", SetLastError:=True, CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function unloadall() As Long
End Function
End Class
and later I call these functions and it works for opening session e.g. PInvoke.loadsession. But I don't know how to access to results of PInvoke.compute function by similar principle I've used in VBA?
Thank you very much for the response!

how to hide/unhide window by process name or processid using VB.NET?

im trying to hide/unhide window process by name or PID i have tried
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As ShowWindowCommands) As Boolean
End Function
but ShowWindowCommands what is and how to find it ?
thanks !
there is many ways to do this the easiest one should be this :
'GENERAL IMPORT
Imports System.Runtime.InteropServices
'FORM CLASS DECLARATION
<DllImport("user32.dll")> _
Private Shared Function ShowWindow(ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Boolean
End Function
'then if you want to hide firefox's window :
Dim mywindow As Integer
Dim processRunning As Process() = Process.GetProcesses()
For Each pr As Process In processRunning
If pr.ProcessName = "Firefox" Then
mywindow = pr.MainWindowHandle.ToInt32()
ShowWindow(mywindow , 0)
End If
Next
You can do it like this:
Form.FromHandle(Process.GetProcessById(PID).MainWindowHandle).Show()

VB.Net DLLImport

I got a PL/I Dll and I'm trying to import the DLL into my VB.Net Application.
The first try worked but the program did quit without comment after a few calls.
And it is not possible to call these function twice from two different threads.
I get the result from the DLL in paramone. Any Ideas why this doesn't work right and how to get it to work?
<DllImport(("PLIDLL.dll"), CallingConvention:=CallingConvention.StdCall)> _
Public Shared Sub MYFUNC(ByVal LogonString As String, _
<MarshalAs(UnmanagedType.VBByRefStr)> ByRef paramone As String, _
ByVal paramtwo As String)
End Sub
If anything is unclear please ask.
Greetings Lim
PS: I already tried to rerewrite the PL/I Code so that it returns a String instead of the ByRef value. Same issue.
The Sub in PLI:
MYFUNC: PROC(LOGONSTRING,PARAMONE,PARAMTWO) REORDER
OPTIONS(FROMALIEN NODESCRIPTOR
BYADDR LINKAGE(STDCALL));
DEFAULT RANGE(*) STATIC;
DCL LOGONSTRING CHAR(30);
DCL PARAMONE CHAR(2033);
DCL PARAMTWO CHAR (5500);
Found at least a working solution.
Module NativeMethods
<DllImport("kernel32.dll", SetLastError:=True)> _
Public Function LoadLibrary(ByVal lpFileName As String) As IntPtr
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Public Function GetProcAddress(ByVal hModule As IntPtr, ByVal procedureName As String) As IntPtr
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Public Function FreeLibrary(ByVal hModule As IntPtr) As IntPtr
End Function
End Module
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Sub MYFUNC(ByVal LogonString As String, <MarshalAs(UnmanagedType.VBByRefStr)> ByRef PARAMONE As String, ByVal PARAMTWO As String)
Public Shared Sub CallFunction(ByRef workingObject As PLIOBJECT)
Dim EntryPointer As IntPtr = NativeMethods.LoadLibrary("PLIDLL.dll")
Dim FunctionPointer As IntPtr = NativeMethods.GetProcAddress(EntryPointer, "MYFUNC")
Dim MyFUNC As MYFUNC= CType(Marshal.GetDelegateForFunctionPointer(FunctionPointer, GetType(MYFUNC)), MYFUNC)
MyFUNC(workingObject.Logonstring, workingObject.PARAMONE, workingObject.PARAMTWO)
Dim result As Boolean = NativeMethods.FreeLibrary(EntryPointer)
End Sub