StringSender's sauce.
Hey guys, as you may or may not know I released a library called "StringSender.dll" a long time ago. The other day TimoTerremoto had a problem with the dll so I decided to re-open the old project and see what the problem might have been. When I saw the code I'll admit I was a bit disgusted at how n00b I was back then; there was a LOT of poor coding going on there. Anyway, now I've freshened the code up a bit, I thought I'd share it with everyone.
Unfortunately the syntax highlighting plugin isn't working so well.
Enjoy.
Unfortunately the syntax highlighting plugin isn't working so well.
Code:
Imports System.Runtime.InteropServices
Public Class KeySender
<DllImport("user32.dll", SetLastError:=True)> _
Private Shared Function keybd_event(ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As UInt32, ByVal dwExtraInfo As UIntPtr) As Boolean
End Function
Public Shared Sub SendString(ByVal message As String, Optional ByVal pauseLength As Int32 = 0)
Dim ASCII As String = message.ToUpper() '//Asc only works on upper case letters properly.
For i As Integer = 0 To message.Length - 1 '//loop through the characters.
Dim vk As Byte = CType(Asc(ASCII(i)), Byte)
If Char.IsUpper(message(i)) Then 'check if the original character is uppercase
SendTwoKeys(16, vk) 'if so, send the shift key + the key.
Else
SendKey(vk) 'otherwise just send the key.
End If
If pauseLength > 0 Then Threading.Thread.Sleep(pauseLength) 'if the user specified a pause length, pause for that time.
Next i
End Sub
Public Shared Sub SendKey(ByVal vKeyCode As Byte)
Try
keybd_event(vKeyCode, 0, 0, UIntPtr.Zero) 'key down
Threading.Thread.Sleep(5) 'very light tap on the keyboard.
keybd_event(vKeyCode, 0, 2, UIntPtr.Zero) 'key up
Catch ex As Exception
End Try
End Sub
Public Shared Sub SendTwoKeys(ByVal firstKey As Byte, ByVal secondKey As Byte)
Try
keybd_event(firstKey, 0, 0, UIntPtr.Zero) 'hold down key 1
keybd_event(secondKey, 0, 0, UIntPtr.Zero) 'hold down key 2
System.Threading.Thread.Sleep(20) 'let the key register
keybd_event(secondKey, 0, 2, UIntPtr.Zero) 'release key 2
keybd_event(firstKey, 0, 2, UIntPtr.Zero) 'release key 1
Catch ex As Exception
End Try
End Sub
End Class
