hooking another program's calls to winapi functions in vb.net - vb.net

I have been trying to build a game bot in vb.net. One of the main problems is getting access to the text the game prints on the screen so I have been trying to hook the games calls to the windows api drawtext and textout functions. I have been hunting for examples of how to set up a hook in vb.net for a long time without any luck. I have found it impossible to translate examples in old school vb, C++, and C#. For convenience's sake I would like to use the freely available deviare and/or easyhook libraries. Can anyone help?

I found working vb.net code based on the deviare hooking dlls buried in the deviare forums.
please remember to add all 6 deviare references found under the com tab of the add references page of visual studio after installing deviare.
Public Class Form1
'To print to a textbox in the gui you will have to call textbox.invoke
Private _mgr As Deviare.SpyMgr
Private WithEvents _hook As Deviare.Hook
Private _proc As DeviareTools.IProcess
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
_mgr = New Deviare.SpyMgr()
_hook = _mgr.CreateHook("user32.dll!ShowWindow")
_hook.Attach(_mgr.Processes)
_hook.AddProcessFilter(0, "notepad", 1)
_hook.Hook()
Private Sub OnFunctionCalled(ByVal proc As DeviareTools.IProcess, ByVal callInfo As DeviareParams.ICallInfo, ByVal rCall As Deviare.IRemoteCall) Handles _hook.OnFunctionCalled
Debug.Print("Caught function call in " & proc.Name) 'view in imediate window
End Sub
end class

I am in the process of converting the Easyhook c# code into vb.net. At the moment I am getting the error code 5 message and the hooked application is being closed by windows eg to help protect your computer etc. If anyone could help with this then I would be grateful. What I have so far is...
Imports EasyHook
Imports System
Imports System.Diagnostics
Imports System.Runtime.Remoting
Imports System.Windows.Forms
Imports System.Security
Imports System.Security.Principal
Namespace FileMon
Friend Class Program
' Methods
Public Shared Sub Main(ByVal args As String())
Dim result As Integer = 0
If ((args.Length <> 1) OrElse Not Integer.TryParse(args(0), result)) Then
Console.WriteLine()
Console.WriteLine("Usage: FileMon %PID%")
Console.WriteLine()
Else
Try
Try
Console.WriteLine("Registering Application")
Console.WriteLine()
Config.Register("A FileMon like demo application.", "FileMon.exe", "FileMonInject.dll")
Catch exception1 As ApplicationException
Console.WriteLine("This is an administrative task! " & exception1.ToString)
Console.WriteLine()
Process.GetCurrentProcess.Kill()
End Try
Console.WriteLine("Creating IPC Server")
Console.WriteLine()
RemoteHooking.IpcCreateServer(Of FileMonInterface)(Program.ChannelName, WellKnownObjectMode.SingleCall)
RemoteHooking.Inject(result, "FileMonInject.dll", "FileMonInject.dll", New Object() {Program.ChannelName})
Console.WriteLine("Injected")
Console.WriteLine()
Console.ReadLine()
Catch exception As Exception
Console.WriteLine("There was an error while connecting to target:" & exception.ToString)
End Try
End If
End Sub
' Fields
Private Shared ChannelName As String
End Class
End Namespace
and
Imports System
Namespace FileMon
Public Class FileMonInterface
Inherits MarshalByRefObject
' Methods
Public Sub IsInstalled(ByVal InClientPID As Integer)
Console.WriteLine("FileMon has been installed in target " & InClientPID)
End Sub
Public Sub OnCreateFile(ByVal InClientPID As Integer, ByVal InFileNames As String())
Dim i As Integer
For i = 0 To InFileNames.Length - 1
Console.WriteLine(InFileNames(i))
Next i
End Sub
Public Sub Ping()
End Sub
Public Sub ReportException(ByVal InInfo As Exception)
Console.WriteLine(("The target process has reported an error:" & InInfo.ToString))
End Sub
End Class
End Namespace

easyhook libraries
Try to use the EasyHook library

Related

Convert the program interface to another language interface VB.NET

What is wrong with the code to convert the program interface to another language interface? In Visual Basic .NET (Visual Studio 2019)
Imports System.Globalization
Imports System.ComponentModel
Public Class Form1
Private Sub ArButton_Click(sender As Object, e As EventArgs) Handles ArButton.Click
Languages.changelanguge("ar")
End Sub
Private Sub EnButton_Click(sender As Object, e As EventArgs) Handles EnButton.Click
Languages.changelanguge("en")
End Sub
End Class
Public Module Languages
Public Sub changelanguge(ByVal languge As String)
For Each obj As Control In Form1.Controls
Dim lang As ComponentResourceManager = New ComponentResourceManager(GetType(Form1))
lang.ApplyResources(obj, obj.Name, New CultureInfo(languge))
Next
End Sub
End Module
What is happening when you run the code? I was implementing this recently and the below link assisted a lot.
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=netframework-4.8

Event 'Load' cannot be found

Getting the error "Event 'Load' cannot be found" referring to "Handles MyBase.Load" Please see attached code. Any help much appreciated!
I have many other applications set up the same way and they all work. However, these were in an older version of Visual Studio.
Option Explicit On
Option Strict On
Imports System, System.IO
Imports System.Text
Public Class Form1
Private Sub cleanXMLDialog_Load(ByVal eventSender As System.Object, ByVal
eventArgs As System.EventArgs) Handles MyBase.Load
Main()
End
End Sub
Public Sub Main()
Dim directories() As String = Directory.GetDirectories("C:\")
Dim files() As String = Directory.GetFiles("C:\", "*.dll")
DirSearch("c:\")
End Sub
Sub DirSearch(ByVal sDir As String)
Dim d As String
Dim f As String
Try
For Each d In Directory.GetDirectories(sDir)
For Each f In Directory.GetFiles(d, "*.xml")
'Dim Response As String = MsgBox(f)
Debug.Write(f)
Next
DirSearch(d)
Next
Catch excpt As System.Exception
Debug.WriteLine(excpt.Message)
End Try
End Sub
End Class
Load should happen without this error.
This is the class declaration:
Public Class Form1
It looks like you intend this to inherit from a windows Form type, but there's nothing here to make that happen.
You may want this:
Public Class Form1 Inherits System.Windows.Forms.Form
but even this is unlikely to really accomplish anything. It's not enough just to inherit from the Form type if you don't have any controls are properties set and don't ever show the form.
Did you accidentally create a Console or Class Library project when you mean to create a WinForms project?

Object reference not set to an instance of object - vb.net

First a little background information: The purpose of this application is to capture images and save them automatically to a network directory that will be either created or appended using the input of the text box. This code DOES work on my computer (windows 7 home 64 bit). I've created it using microsoft visual basic express 2010.
However..... when attempting to run the application on a windows 10 tablet, I get the follow errors:
On form load:
An error occurred while capturing the image. The video capture will now be terminated.
Object reference not set to an instance of an object.
On button2_Click Event:
Object reference not set to an instance of an object.
Below is the entirety of the code.
Form2.vb
Public Class Form2
Public scanIsSet As Boolean
Private webcam As WebCam
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
webcam = New WebCam()
webcam.InitializeWebCam(imgVideo)
webcam.Start()
scanIsSet = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim CFGfile As String
Dim SaveDir As String
Dim imgIndex As Integer
Dim existingImages() As String
SaveDir = "C:\somepath\"
'save image to directory with index number
Try
imgCapture.Image.Save(SaveDir & OrderNumber.Text & "\" & CStr(imgIndex) & ".jpg")
Catch ex As Exception
MsgBox("error while accessing object imgCapture" & ex.Message)
End Try
imgIndex = imgIndex + 1
Else
Beep()
MsgBox("Please scan or type in order number first")
End If
End Sub
End Class
WebCam.vb
Imports System
Imports System.IO
Imports System.Linq
Imports System.Text
Imports WebCam_Capture
Imports System.Collections.Generic
Imports ZXing
Imports ZXing.OneD
'Design by Pongsakorn Poosankam
Class WebCam
Public scanz As Boolean
Public Sub setScan(ByVal x As Boolean)
scanz = x
End Sub
Private webcam As WebCamCapture
Private _FrameImage As System.Windows.Forms.PictureBox
Private FrameNumber As Integer = 30
Public Sub InitializeWebCam(ByRef ImageControl As System.Windows.Forms.PictureBox)
webcam = New WebCamCapture()
webcam.FrameNumber = CULng((0))
webcam.TimeToCapture_milliseconds = FrameNumber
AddHandler webcam.ImageCaptured, AddressOf webcam_ImageCaptured
_FrameImage = ImageControl
End Sub
Private Sub webcam_ImageCaptured(ByVal source As Object, ByVal e As WebcamEventArgs)
_FrameImage.Image = e.WebCamImage
If scanz = True Then
Dim BCreader As New ZXing.BarcodeReader
'BCreader.Options.TryHarder = True
Try
Dim resu As Result = BCreader.Decode(e.WebCamImage)
Form2.OrderNumber.Text = resu.Text
setScan(False)
Form2.Label2.Text = ""
Beep()
Catch ex As Exception
'do nothing
End Try
End If
End Sub
Public Sub Start()
webcam.TimeToCapture_milliseconds = FrameNumber
webcam.Start(0)
End Sub
Public Sub [Stop]()
webcam.[Stop]()
End Sub
Public Sub [Continue]()
' change the capture time frame
webcam.TimeToCapture_milliseconds = FrameNumber
' resume the video capture from the stop
webcam.Start(Me.webcam.FrameNumber)
End Sub
Public Sub ResolutionSetting()
webcam.Config()
End Sub
Public Sub AdvanceSetting()
webcam.Config2()
End Sub
End Class
As you can see toward the end of Form2.vb, I've wrapped imgCapture.Image.Save(SaveDir & OrderNumber.Text & "\" & CStr(imgIndex) & ".jpg") in a Try-Catch block because I suspect it's some sort of problems with the pictureBox objects. The try catch block does indeed catch the exception, but I still have no idea what the problem is, why it happens on the tablet and not the PC, or how to fix it.
I've found similar questions, but none with a solution I can make use of.
Since you are using a library, EasyWebCam, that is outdated and not compatible with Win10, I would suggest switching libraries. Other options out there:
DirectX.Capture
Windows.Media.Capture
I FOUND THE SOLUTION BUT I DON'T KNOW IF YOU NEED IT NOW ANYWAY THE PROBLEM IS IF YOU HAVE CHANGED THE PICTUREBOX NAME THEN IN REFENCES USE THE EXACT NAME YOU HAVE CHANGED TO. EXAMPLE IF I CHANGE ALL MY PICTUREBOX NAMES AS -
PictureBox_A1 , PictureBox_A2 ,... and so on then my refence should be as -
Dim r As DataRow
For Each r In t1.Rows
CType(Controls("PictureBox_" & r(2)), PictureBox).Image = bookedicon
Next
MY REFERENCE IS - "PictureBox_"

NSQ vb.net MessageHandler

I am trying to use this package in vb.net NsqSharp
There is a good code for it in C# but i need it in vb.net.
I got it to send a message to my NSQ server, but the problem is to get it.
But i get a error on consumer.AddHandler(New HandleMessage()) and i do not know if i declare the HandleMessage right.
Imports NsqSharp
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim producer = New Producer("127.0.0.1:4150")
producer.Publish("test-topic-name", Me.txt_tx.Text)
producer.Stop()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim consumer = New Consumer("test-topic-name", "channel-name")
consumer.AddHandler(New HandleMessage())
consumer.ConnectToNsqLookupd("127.0.0.1:4161")
consumer.Stop()
End Sub
Public Interface IHandler : End Interface
Public Sub HandleMessage(message As Message)
Dim msg As String = Encoding.UTF8.GetString(message.Body)
MsgBox(msg)
End Sub
Public Sub LogFailedMessage(message As Message)
Dim msg As String = Encoding.UTF8.GetString(message.Body)
MsgBox(msg)
End Sub
End Class
But i get a error on Implements IHandler
Lovely description of the problem, you can't get useful answers when you don't describe the exact error message you see. You did write the code wrong, VB.NET requires the Implements keyword on interface method implementations. You'd normally fall in the pit of success by letting the IDE generate these methods for you. As soon as you type "Implements IHandler" and press the Enter key, the IDE automagically adds the methods.
So there's probably something wrong with the library reference as well. Steps one-by-one:
Tools > Nuget Package Manager > Package Manager Console.
Type "Install-Package NsqSharp". Watch it trundle while it downloads and installs the package.
Put Imports NsqSharp at the top of the source file.
You should now end up with:
Public Class MessageHandler
Implements IHandler
Private Sub IHandler_HandleMessage(message As Message) Implements IHandler.HandleMessage
Dim msg As String = Encoding.UTF8.GetString(message.Body)
MessageBox.Show(msg)
End Sub
Private Sub IHandler_LogFailedMessage(message As Message) Implements IHandler.LogFailedMessage
Dim msg As String = Encoding.UTF8.GetString(message.Body)
MessageBox.Show(msg)
End Sub
End Class

Creating a Serial Port in code in VB.net

I am trying to create a serial port in VB.net using code only. Because I am creating a class library I cannot use the built-in component. I have tried instantiating a new SeialPort() object, but that does not seem to be enough. I'm sure there is something simple I am missing and any help would be greatly appreciated! Thanks!
P.S. I should add that the problem I am having at this time is getting the code to handle the datareceived event. Other than that it might be working, but I can't tell because of that problem.
If you want to use the events make sure you declare your serialPort object using the 'withevents'. The below example will allow you to connect to a serial port, and will raise an event with the received string.
Imports System.Threading
Imports System.IO
Imports System.Text
Imports System.IO.Ports
Public Class clsBarcodeScanner
Public Event ScanDataRecieved(ByVal data As String)
WithEvents comPort As SerialPort
Public Sub Connect()
Try
comPort = My.Computer.Ports.OpenSerialPort("COM5", 9600)
Catch
End Try
End Sub
Public Sub Disconnect()
If comPort IsNot Nothing AndAlso comPort.IsOpen Then
comPort.Close()
End If
End Sub
Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles comPort.DataReceived
Dim str As String = ""
If e.EventType = SerialData.Chars Then
Do
Dim bytecount As Integer = comPort.BytesToRead
If bytecount = 0 Then
Exit Do
End If
Dim byteBuffer(bytecount) As Byte
comPort.Read(byteBuffer, 0, bytecount)
str = str & System.Text.Encoding.ASCII.GetString(byteBuffer, 0, 1)
Loop
End If
RaiseEvent ScanDataRecieved(str)
End Sub
End Class
I found this article to be quite good.
The code i wrote from it is:
port = new System.IO.Ports.SerialPort(name, 4800, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
buffer = port.ReadLine();
// process line
}
Sorry it's C# but...
The only issue I have with it is if the port is dropped while it's open, the app seems to fail on exit.
Thank you all for your help, especially the answer about instantiating a class using the WithEvents keyword.
I found a really great article that explains how to create a manager class for the serial port. It also discusses sending Binary as well as Hex data to the serial port. It was quite helpful.
http://www.dreamincode.net/forums/showtopic37361.htm
I have used the SerialPort .Net class in a past project and I worked fine. You really don't need anything else. Check the hardware setting in the control panel and make sure you instantiate the class with the same parameters.