Advanced UI Interaction
Beyond basic clicks and text input, modern applications often require more complex UI interactions. This guide covers how to perform advanced actions like drag-and-drop, keyboard shortcuts, and handling custom controls using the Ranorex API.
Drag and Drop
Performing a drag-and-drop operation involves a sequence of mouse actions on the source and target elements.
Example:
public void DragAndDrop(Adapter source, Adapter target)
{
// Move the mouse to the source element
source.Focus();
Mouse.MoveTo(source);
// Press the left mouse button
Mouse.ButtonDown(System.Windows.Forms.MouseButtons.Left);
// Move the mouse to the target element
Mouse.MoveTo(target);
// Release the mouse button
Mouse.ButtonUp(System.Windows.Forms.MouseButtons.Left);
}
// Usage
var sourceElement = repo.MyApp.SourceItem;
var targetElement = repo.MyApp.DropTarget;
DragAndDrop(sourceElement, targetElement);
Keyboard Shortcuts
You can simulate complex keyboard shortcuts using the Keyboard.Press method.
Example:
// Simulate Ctrl+C to copy
Keyboard.Press(System.Windows.Forms.Keys.C, Keyboard.Modifiers.Control);
// Simulate Ctrl+V to paste
Keyboard.Press(System.Windows.Forms.Keys.V, Keyboard.Modifiers.Control);
// You can also chain key presses
Keyboard.Press("{LControlKey down}{Ckey}{LControlKey up}");
Handling Custom Controls
Some applications use custom controls that are not recognized by default by Ranorex. You can interact with these controls by treating them as generic Adapter objects and using low-level actions.
Invoking Control-Specific Actions
If a custom control has specific actions, you can try to invoke them directly.
Example:
// Assuming a custom control has a 'Select' action
var customControl = repo.MyApp.CustomControl;
customControl.Element.InvokeAction("Select");
Interacting via Location
If all else fails, you can interact with a control based on its location on the screen.
Example:
// Click in the center of a custom control
var customControl = repo.MyApp.CustomControl;
customControl.Click(Location.Center);
// Click at a specific offset within the control
customControl.Click(new Location(10, 20));
Simulating Touch Events
For mobile testing, you can simulate touch events like tap, swipe, and pinch.
Example:
// Simulate a tap on a mobile element
var mobileButton = repo.MyMobileApp.SomeButton;
mobileButton.Touch();
// Simulate a swipe
Touch.Swipe(new Location(100, 200), new Location(100, 400));
// Simulate a pinch gesture
var elementToPinch = repo.MyMobileApp.PinchableElement;
elementToPinch.Pinch(40, 200); // Pinch out from 40px to 200px
By mastering these advanced interaction techniques, you can automate even the most complex UI scenarios and ensure comprehensive test coverage for your applications.