Send keyboard or mouse input to a window

Title InputToWin(BETA)

License info
You must credit the author.

Author name
Shane Findley

System Requirements
ME/2000/XP/Vista with VB2003 or 2005 1.1 or 2.0 .NET Framework

Description
This class can be used to send keyboard and mouse events directly to a window.
It sends input events, to the specified window matching the given title, class name, process name, or integer handle.
For more information about SendKeys.Send (http://msdn2.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx).

Screen-shot
http://a715.ac-images.myspacecdn.com/images01/114/l_cfe73c73254e2616bf39be9a344f213a.jpg

Feature list
s.KeysToSend(sText, wName, wInputIdle, kBlock, sFlush, rForeground)
Description:
This function simulates keyboard events more reliably than SendKeys.Send (http://msdn2.microsoft.com/en-us/library/system.windows.forms.sendkeys.send.aspx)
It sends Text, keys, or key combinations, to the specified window matching the title, class name, process name, or integer handle.
Parameters:
sText The text or key commands to send. See the KeyCommandsToFile sub, for more details.
wName The name of the window. Specify the window title, class name, process name, or integer handle.
wInputIdle Waits for the window to be ready before sending.
kBlock Blocks other keyboard and mouse events while sending.
sFlush Flushes keyboard messages after injecting them. Specify -1 to not flush keys. Specify an integer to flush for that number of milliseconds.
rForeground Returns the foreground window. Specify True or False.
Return value:
Returns false if a window handle cannot be found, or the foregroundwindow cannot be forced, or the keys cannot be simulated.
Examples:

Specify only the first parameter, to behave just as microsoft's Sendkeys.Send().

s.KeysToSend("{tab 4}Hello World!") 'Press tab 4 times to place focus on textbox, then write "Hello World!".

Send keys to specified window by title, without disturbing keys, then return the foreground window.

s.KeysToSend("Hello World!", "New Text Document - Notepad", True, True, -1, True)

If the application is already running, and you know the class name.

s.KeysToSend("Hello World!", "Notepad", True, True) 'Wait for input idle, and blocks normal keyboard input for a moment

If the process is already running and you know its name.

s.KeysToSend("Hello World!", "notepad.exe", True, True)

If you already have the window handle.

Dim hwnd As Int32 = s.GetHandle("Notepad") 'Get handle of a notepad
s.KeysToSend("Hello World!", hwnd.ToString, True, True) 'Sends the keys for Hello World!, to notepad's handle.

If the application is not already started, use this syntax to specify a system file path, or any other path to an executable.

Dim sSystem As String = System.Environment.SystemDirectory.Substring(0, System.Environment.SystemDirectory.Length - 9)
s.KeysToSend("Hello World!", sSystem & "\notepad.exe", True, True)

Print and view all available key commands for the KeysToSend method

s.KeyCommandsToFile()

Keys can be sent by command within brackets, to a window like this:

s.KeysToSend("{return}", "Notepad") 'This simply presses the return/enter key once

Press a command key several times in a row like this:

s.KeysToSend("{return 10}{tab 7}Hi there!", "Notepad")'This presses the return key 10 times, and then the tab key seven times, then writes "Hi There!"

Try each one of these key combos one at a time.

s.KeysToSend("%(f)", "Notepad") '(Alt + f) to open the file menu.
's.KeysToSend("+(a)", "Notepad") '(Shift + a) makes a capital A.
's.KeysToSend("^(p)", "Notepad") '(Ctrl + p) prints the current notepad
's.KeysToSend("%(fx)", "Notepad") '(Alt + fx) to access main menu shortcuts, and exit notepad
's.KeysToSend("^({escape})") '(Ctrl + Escape) to open start menu
's.KeysToSend("^(+({escape}))") '(Ctrl+Alt+Escape) to open Task manager
's.KeysToSend("^(%(f))") '(Ctrl+Alt+f) to access a desktop shortcut ending in f. (You must make the desktop combo first)
's.KeysToSend("+(%({space}x))", "Notepad") '(Shift + Alt + Space) to open the system menu of a notepad and Maximize screen. Use c for close etc.
's.KeysToSend("#(l)") '(Win + L) to log off immediately. (2000/XP only)

This four part process copies the current screen to the clipboard, and sends it to MS-Paint for printing

s.KeysToSend("%({PrintScreen})") 'Part 1 For active window only 's.KeysToSend("{PrintScreen 2}") 'For desktop window only
s.KeysToSend("^(vp)", System.Environment.SystemDirectory & "\mspaint.exe", True) 'Part 2 Start MS paint, paste, and invoke print
s.KeysToSend("%(n)", "Print") 'Part 3 Answer no if there is no printer installed
s.KeysToSend("%(p)", "Print") 'Part 4 Print if print button is enabled

s.KeyToMessage(vkCode, hWnd, kDown, kUp, bPost)
Description:
This function sends or posts key messages to a window.
Parameters:
vkCode The keycode to send.
hWnd The handle of the window.
kDown Presses key down.
kUp Lifts key up.
bPost Posts the message into the queue instead of sending it.
Return value:
Returns true if successful.
Examples:
Use a string array to press a button that's on a main form

Dim sArray() As String = s.CArr("AppTitleHere", 1, "Button", 1)
Dim hwnd As Int32 = s.GetHandle(sArray)
s.KeyToMessage(Keys.Space, hwnd)

s.KeysToText(sText, hWnd, bPost)
Description:
This function sends or posts text to a window.
Parameters:
sText The text to send.
hWnd The handle of the window.
bPost Posts the message into the queue instead of sending it.
Return value:
Returns true if successful.
Examples:
Use a string array to set the text of a child window.

Dim sArray() As String = s.CArr("Notepad", 1, "Edit", 1)
Dim hwnd As Int32 = s.GetHandle(sArray)
s.KeysToText("hello", hwnd)

s.MouseToSend(mButtons, wName, isMenu, x, y, cWheel, rCursor)
Description:
This class sends mouse events, to a specified window matching the title, class name, process name, or handle.
Parameters:
mButtons The button to click, or event to simulate.
"LClick" Indicates a left click.
"LDblClick" Indicates a double left click.
"RClick" Indicates a right click.
"RDblClick" Indicates a double right click.
"MClick" Indicates a middle click.
"MDblClick" Indicates a double middle click.
"XClick" Indicates an x click.
"XDblClick" Indicates a double x click.
"Move" Indicates a relative mouse movement from current position.
"Absolute Move" Indicates an abosoute movement where x and y contain normalized absolute coordinates.
"Wheel" Windows NT only: Specifies that the wheel has been moved, if the mouse has a wheel. The amount of movement is given in cWheel.
wName The name of the window. Specify the window title, class name, process name, integer handle or array of window names.
isMenu Indicates that a menu is to be clicked. The menu path is to be specified in the wName parameter.
x Indicates the mouses absolute position along the x-axis or its amount of motion since the last mouse event was generated, depending on the setting of ABSOLUTE.
Absolute data is given as the mouses actual x-coordinate; relative data is given as the number of mickeys moved.
A mickey is the amount that a mouse has to move for it to report that it has moved. If percentages are used, ie "%50", then proportions of the window are used instead.
y Indicates the mouses position along the y-axis, in the same way as x.
cWheel If mButtons is "Wheel", then cWheel Indicates the amount of wheel movement.
A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
One wheel click is defined as WHEEL_DELTA, which is 120. If mButtons is not "Wheel", then cWheel should be zero.
rCursor Returns the cursor to it's previous position before sending.
Return value:
Returns false if a handle can't be found, or the window can't be set as the TopMost, or the window rectangle can't be found, or the mouse event fails in any way.
Examples:

Move mouse 100 to the right, and 100 down, from it's current position.

s.MouseToSend("Move", "", 0, "100", "100")

Move mouse to absolute coordinates somewhere on the screen

s.MouseToSend("Absolute Move", "", 0, "10000", "10000")

Click a child button on a form.

s.MouseToSend("LClick", s.CArr("Form2", 1, "Button3", 1))

Close notepad, by double clicking its system menu icon at the top left hand corner

s.MouseToSend("LdblClick", "Notepad", 0, "15", "15")

Maximize or minimize notepad, by double clicking its titlebar

s.MouseToSend("LDblClick", "Notepad", 0, "%50", "15")

Right click on the middle of notepad's titlebar, while keeping the cursor position.

s.MouseToSend("RClick", "Notepad", 0, "%50", "15", 0, False)

Click on a child window, by specifying the window's text or class names, and their indexes as arrays

s.MouseToSend("LClick", s.CArr("Form2", 1, "GroupBox1", 1, "GroupBox2", 1, "GroupBox3", 1, "Start", 1), 0, "%50", "%50", 0, False)

Click on a tab control(processes) of the task manager, by using absolute coordinates of the specified window

s.MouseToSend("LClick", s.CArr("Windows Task Manager", 1, "SysTabControl32", 1), 0, "100", "7")

Now click on a child, by using "", and the child window(if any) will be obtained by it's index only

s.MouseToSend("LClick", s.CArr("Windows Task Manager", 1, "", 1, "End Process", 1))

Click menu items by index

s.MouseToSend("LClick", s.CArr("Windows Task Manager", 1, "", 3, "", 2, "", 3), 1)

Click menu item by caption

s.MouseToSend("LClick", s.CArr("Notepad", 1, "File", 1, "Exit", 1), 1)

Click system menu by index, to close notepad

s.MouseToSend("LClick", s.CArr("Notepad", 1, "", 7), -1)

Build this app and name as Form2, run outside the project folder as if it was an external application, then run this as Form1

s.MouseToSend("LClick", s.CArr("Form2", 1, "", 2, "", 4, "", 3, "", 7, "", 4), 1) ' Click through many sub menus.

s.GetSetCursorPosition(x, y)
Description: This function gets or set the cursor's position.
Parameters:
x The x coordinate. Specify -1 for both x and y, to get the current position.
y The y coordinate. Specify -1 for both x and y, to get the current position.
Return value:
Returns the current cursor position in a POINT structure.
Example:
This gets the cursor position, and then sets it elsewhere.

Dim p As POINT = s.GetSetCursorPosition()
MessageBox.Show(p.X & " " & p.Y)
s.GetSetCursorPosition(0, 0)'Set to the top left

- Continued below in the next post...

Download
[11646 byte] By [TT-n] at [2007-11-20 11:51:42]
# 1 Re: Send keyboard or mouse input to a window
Additional features

s.CArr(wName1, wIndex1, wName2, wIndex2, wName3, wIndex3...)
Description:
This function coverts strings and integers into an array for input.
Parameters:
wNamex The parameter for window titles(text), class names, and nothing, ie "".
wIndexx The parameter for the index of the window matching the wNamex parameter, in case there is more than one.
Return value:
The return value, is a string array.

s.GetHandle(wName, wIndex)
Description:
This function gets or verifies the handle of a window or child windows.
Parameters:
wName The title(Text), class name, process name, or a string array of windows.
wIndex The index of the window if there are more than one that match the wName parameter. This does not apply if wName is an array.
Return value:
Returns an integer handle if found or verified, otherwise its 0.
Examples:

Dim hwnd As Int32 = s.GetHandle("Form1")
MessageBox.Show(hwnd.ToString & " is the handle.")

You can also get a specific handle by using the following commands enclosed in brackets.

's.GetHandle("{active}") 'Gets the handle of the currently active window.
's.GetHandle("{desktop}") 'Gets the handle of the desktopwindow.
's.GetHandle("{focus}") 'Gets the handle of the window with focus.
's.GetHandle("{foreground}") 'Gets the handle of the current foregroundwindow.
's.GetHandle("{frompoint}") 'Gets the handle of the window under the cursor.
's.GetHandle("{ancestor}", hwnd) 'Gets the ancestor handle of the specified window.
's.GetHandle("{childfrompoint}", hwnd) 'Gets the child handle of a parent window under the cursor.
's.GetHandle("{menu}", hwnd) 'Gets the menu handle of the specified window.
's.GetHandle("{parent}", hwnd) 'Gets the parent handle of the specified window.
's.GetHandle("{top}") 'Gets the handle of the top window.
s.GetHandle("") 'Gets any available window.

s.GetWindowFocus()
Description:
This function gets the handle of the window that currently has keyboard focus.
Return value:
The window handle.
Example:

Dim hwnd As Int32 = s.GetWindowFocus()
s.KeysToText("hello", hwnd)

s.GetWindowName(hWnd, gText, gClass, gProcess)
Description:
This function gets the title or class name, or process name of a window.
Parameters:
hWnd The handle of the window.
gText Indicates that the title is to be retrieved.
gClass Indicates that the class name is to be retrieved.
gProcess Indicates that the process name is to be retrieved.
Return value:
Returns a structure of the window name.
Examples:
Get window title(text) from handle.

MessageBox.Show(s.GetWindowName(Me.Handle.ToInt32, True, False, False).lpText)

Get window class name from handle.

MessageBox.Show(s.GetWindowName(Me.Handle.ToInt32, False, True, False).lpClassName)

Get window process name from handle.

MessageBox.Show(s.GetWindowName(Me.Handle.ToInt32, False, False, True).lpProcessName)

Get all window names from handle.

Dim wn As New InputToWin.WINDOWNAME()
wn = s.GetWindowName(Me.Handle.ToInt32)
MessageBox.Show(wn.lpText & " " & wn.lpClassName & " " & wn.lpProcessName)


s.SleepFlush(dwMilliseconds, fInterval)
Description:
This combines System.Threading.Thread.Sleep(0), with SendKeys.Flush.
Parameters:
It sleeps for dwMilliseconds seconds, while flushing every fInterval milliseconds
dwMilliseconds The number of milliseconds to sleep in milliseconds, ie 5000 = 5 seconds.
fInterval The number of milliseconds between flushes. Flushing helps process window messages that are still in the queue.
Return value:
Returns true if there are no more messages in the queue.
Examples:
Sleeps until there are no more messages in the queue, or 5 seconds is up, while flushing every 1 millisecond.

SleepFlush()

Sleeps for 5 seconds, and flushes every 200 milliseconds.

SleepFlush(5000, 200)

s.WindowWaitToExist(wName, dwMilliseconds, wInputIdle, sFlush)
Description:
This function waits for a window to exist, or the timeout has elapsed.
Parameters:
wName The title or class name of the window. Specify "" to wait for any window to exist or cease to exist.
dwMilliseconds The number of milliseconds to wait. Specify 0 as the dwMilliseconds, to wait forever for the specified wName window.
wInputIdle Waits for the window to be ready for input.
sFlush Flushes pending keyboard messages.
Specify -1 to not flush keys.
Specify an integer to flush for that number of milliseconds.
Return value:
Returns true if a window exists.
Example:
You may want to use the WindowWaitToExist function after clicking a button, that does some lengthy operation.
Wait forever, until any window changes. {Use with caution}

s.WindowWaitToExist("", 0)

Wait for window to exist and be ready for input. Then flush any messages in the queue.

s.WindowWaitToExist("Registry Editor", 5000, True, 400)

Wait for a window to exist and be ready for input.

s.KeysToSend("#(R)") 'Win+R combo to bring up run command window
s.WindowWaitToExist("Run") 'Wait for it to exist
s.KeysToSend("regedit{return}", "Run") 'Type in regedit and then press return
s.WindowWaitToExist("Registry Editor", 5000, True, 400) 'Wait 5 seconds for registry editor to exist and be ready for input, then flush for 400 milliseconds
s.KeysToSend("%(ef)", "Registry Editor") 'Alt+ef menu shortcut
s.WindowWaitToExist("Find") 'wait for the find window
s.KeysToSend("cowabunga%(f)", "Find") 'look for nonsense word so that the entire registry is searched
s.WindowWaitToExist("", 0)
MessageBox.Show("Finished waiting for window")

s.WindowWaitForIdle(wName, dwMilliseconds)
Description:
This function waits for a window to be ready for user input.
Parameters:
wName The title or class name of the window.
dwMilliseconds The number of milliseconds to wait.
Return value:
Returns false if the window is not ready for input, or the time runs out, or an error occurs while waiting.
Example:

s.WindowWaitForIdle("ApplicationTitleHere")

s.WindowForceSetForeground(hWnd)
Description:
This function forces the foreground window to be set by using the Ctrl+Alt key combo, and locks out other applications from calling setforegroundwindow.
Parameter:
hWnd The handle of the window to be forced.
Return value:
If the foreground window has been set to the specified handle the return is true, otherwise its false.
Example:
Force the foreground window on a handle

Dim hwnd As Int32 = s.GetHandle("Notepad")
s.WindowForceSetForeground(hwnd)

s.WindowReturnForeground(fReturn)
Description:
This function returns the foreground window by using the Ctrl+Alt+Escape combo, and keeps the original tab order.
Parameter:
fReturn Specify true, to return to the previous foreground.
Return value:
Returns true upon success.
Example:
Return the foreground window to the previous window

s.WindowReturnForeground(True)

Advanced features You can also make the following private functions public.
Shared
ChildWindowFromPoint
GetChildWindow
InputBlock
InputState
KeyState
KeyStateAsync
WindowFromPoint

Keyboard
KeysToLift
KeyToDown
KeyToUp
KeyToPress

Mouse
CEvent
GetSetTopWindow
GetSetZOrder
FindMenuItemPos
MenuItemDim
MouseToPress
MouseMenuClick
MoveItemToItem

Advantages of InputToWin over SendKeys.

Keyboard focus is forced to an application by using the Ctrl+Alt key combination, and SetForegroundWindow API.
Other applications are locked out from using SetForegroundWindow function while keys are being sent.
The foregroundwindow can be returned to it's original position, without changing the z-order.
When a key being pressed represents an action that starts a new window, it can wait until that window exists before sending more keys.
Win+key combos are now possible(2000/Xp) and are expressed as a string; "#(l)" (Win+L)
All keys between 0 and 255 can be called! See the KeyCommandsToFile sub for all available commands.
GetHandle will validate, find, or start an executable to ensure that there is a window, to get the handle of. This makes finding a windows handle easy.
See the WindowCommandsToFile for all available commands.
SleepFlush provides a unique method that overcomes timing issues.
Keys can be sent to a disabled, minimized or hidden window. The window is first shown, and then returned to it's original state after sending keys.
Strings can be repeated, ie "{hello 10}" repeats the hello string ten times.
InputToWin includes mouse methods, and advanced features.


Disadvantages of InputToWin compared to SendKeys.

None yet known. Let me know if you find any!
TT-n at 2007-11-10 3:08:12 >