The Keyboard property holder exposes methods that are similar to SendKeys. UIAutomation tries to set the focus on a control and thereafter puts keys on it.

The Keyboard property exposes several method of Input Simulator's InputSimulator.Keyboard object:
# just any text
$element.Keyboard.TypeText(string text);
# any character
$element.Keyboard.TypeChar(char character);
# these methods allow you to press specific keys like Control, 
$element.Keyboard.KeyDown(VirtualKeyCode virtualKeyCode);
$element.Keyboard.KeyPress(VirtualKeyCode virtualKeyCode);
$element.Keyboard.KeyPress(VirtualKeyCode[] virtualKeyCodes);
$element.Keyboard.KeyUp(VirtualKeyCode virtualKeyCode);
These method consume the [WindowsInput.Native.VirtualKeyCode] enumeration for both alphanumeric characters and for control keys like RETURN.
You can use the methods on controls that accept input like text boxes as well as controls that accept input for the window they are in, for example:
$wnd = Start-Process calc -PassThru | Get-UiaWindow
$btn1 = Get-UiaButton 1
# sending "222" to the window
$wnd.Keyboard.TypeText("222");
# sending "333" to the button 1
$btn1.Keyboard.TypeText("333");
As can be seen, if controls accept keyboard input, even button 1 accepts number 3. :)

To illustrate the use of KeyDown, KeyPress and KeyUp method, there is the following code that types "AAA" to notepad.exe:
$wnd = Start-Process notepad -PassThru | Get-UiaWindow
$wnd.Keyboard.KeyDown([WindowsInput.Native.VirtualKeyCode]::SHIFT);
$wnd.Keyboard.KeyPress([WindowsInput.Native.VirtualKeyCode]::VK_A);
$wnd.Keyboard.KeyPress([WindowsInput.Native.VirtualKeyCode]::VK_A);
$wnd.Keyboard.KeyPress([WindowsInput.Native.VirtualKeyCode]::VK_A);
$wnd.Keyboard.KeyUp([WindowsInput.Native.VirtualKeyCode]::SHIFT);
Without lines that works with the Shift key, we would see "aaa" instead of "AAA".

These method are priceless when working with controls that don't support pattern.

Please refer to the Key Codes page for the list of key codes.

Last edited May 10, 2014 at 12:39 PM by xinliu, version 8

Comments

No comments yet.