Basic API Usage Examples
This section provides fundamental examples of how to use the Ranorex API for common automation tasks. These examples are perfect for developers new to Ranorex and serve as building blocks for more complex automation scenarios.
Hello World Example
The simplest possible Ranorex automation - opening Notepad and typing text.
using Ranorex;
using Ranorex.Core;
using System;
using System.Diagnostics;
public class HelloWorldAutomation
{
public void Run()
{
// Initialize Ranorex runtime
Host.Initialize();
try
{
Report.Info("Hello World", "Starting basic automation example");
// Launch Notepad
Process.Start("notepad.exe");
// Wait for Notepad window to appear
var notepadWindow = "/form[@processname='notepad']";
Host.Local.FindSingle<Form>(notepadWindow, 10000);
// Find the text area and type Hello World
var textArea = notepadWindow + "/text[@class='Edit']";
var textElement = Host.Local.FindSingle<Text>(textArea);
textElement.Click();
textElement.PressKeys("Hello, Ranorex World!");
Report.Success("Hello World", "Successfully automated Notepad!");
// Close without saving
textElement.PressKeys("{Alt}{F4}");
// Handle save dialog if it appears
try
{
var dontSaveButton = "/form[@title='Notepad']/button[@text=\"Don't save\"]";
var button = Host.Local.FindSingle<Button>(dontSaveButton, 3000);
button.Click();
}
catch (RanorexException)
{
// Save dialog didn't appear, that's fine
}
}
catch (Exception ex)
{
Report.Failure("Hello World", $"Automation failed: {ex.Message}");
throw;
}
finally
{
Host.Shutdown();
}
}
}
Element Interactions
This comprehensive example demonstrates various ways to interact with UI elements.
using Ranorex;
using Ranorex.Core;
using System;
public class ElementInteractions
{
public void Run()
{
Host.Initialize();
try
{
// Different ways to find and interact with elements
// 1. Direct element clicking
var submitButton = "/form[@title='MyApp']/button[@text='Submit']";
var button = Host.Local.FindSingle<Button>(submitButton);
button.Click();
Report.Info("Interaction", "Clicked submit button");
// 2. Text input with different methods
var usernameField = "/form[@title='Login']/text[@name='username']";
var textElement = Host.Local.FindSingle<Text>(usernameField);
// Clear field first, then type
textElement.Click();
textElement.PressKeys("{Ctrl}a"); // Select all
textElement.PressKeys("john.doe@example.com");
Report.Info("Interaction", "Entered username");
// 3. Dropdown/ComboBox selection
var countryDropdown = "/form[@title='Profile']/combobox[@name='country']";
var dropdown = Host.Local.FindSingle<ComboBox>(countryDropdown);
dropdown.Click();
dropdown.PressKeys("United States"); // Type to select
dropdown.PressKeys("{Return}");
Report.Info("Interaction", "Selected country from dropdown");
// 4. Checkbox interaction
var agreeCheckbox = "/form/checkbox[@text='I agree to terms']";
var checkbox = Host.Local.FindSingle<CheckBox>(agreeCheckbox);
if (!checkbox.Checked)
{
checkbox.Click();
Report.Info("Interaction", "Checked agreement checkbox");
}
// 5. Radio button selection
var maleRadio = "/form/radiobutton[@text='Male']";
var radioButton = Host.Local.FindSingle<RadioButton>(maleRadio);
radioButton.Click();
Report.Info("Interaction", "Selected gender radio button");
// 6. Double-click interaction
var fileItem = "/form/list/listitem[@text='document.txt']";
var listItem = Host.Local.FindSingle<ListItem>(fileItem);
listItem.DoubleClick();
Report.Info("Interaction", "Double-clicked file item");
// 7. Right-click and context menu
var targetElement = "/form/panel[@name='workspace']";
var panel = Host.Local.FindSingle<Container>(targetElement);
panel.Click(Location.CenterRight); // Right-click
// Select from context menu
var contextMenuItem = "/contextmenu/menuitem[@text='Properties']";
var menuItem = Host.Local.FindSingle<MenuItem>(contextMenuItem, 2000);
menuItem.Click();
Report.Info("Interaction", "Used context menu");
// 8. Keyboard shortcuts
var mainWindow = "/form[@title='MyApp']";
var window = Host.Local.FindSingle<Form>(mainWindow);
window.Focus();
window.PressKeys("{Ctrl}s"); // Save shortcut
Report.Info("Interaction", "Used keyboard shortcut");
}
catch (Exception ex)
{
Report.Failure("Element Interactions", $"Failed: {ex.Message}");
throw;
}
finally
{
Host.Shutdown();
}
}
}
Basic Validations
Examples of how to validate application state and element properties.
using Ranorex;
using Ranorex.Core;
using System;
using System.Drawing;
public class BasicValidations
{
public void Run()
{
Host.Initialize();
try
{
// 1. Element existence validation
var loginDialog = "/form[@title='Login']";
if (Host.Local.TryFindSingle(loginDialog, out Element dialog))
{
Report.Success("Validation", "Login dialog exists");
}
else
{
Report.Failure("Validation", "Login dialog not found");
}
// 2. Text content validation
var welcomeMessage = "/form/text[@name='welcome']";
var messageElement = Host.Local.FindSingle<Text>(welcomeMessage);
string actualText = messageElement.Text;
string expectedText = "Welcome to MyApp";
if (actualText == expectedText)
{
Report.Success("Text Validation", "Welcome message is correct");
}
else
{
Report.Failure("Text Validation",
$"Expected: '{expectedText}', but found: '{actualText}'");
}
// 3. Element state validation
var saveButton = "/form/button[@text='Save']";
var button = Host.Local.FindSingle<Button>(saveButton);
// Check if button is enabled
if (button.Enabled)
{
Report.Success("State Validation", "Save button is enabled");
}
else
{
Report.Info("State Validation", "Save button is disabled");
}
// Check if element is visible
if (button.Visible)
{
Report.Success("Visibility", "Save button is visible");
}
// 4. Numeric validation
var counterDisplay = "/form/text[@name='counter']";
var counterElement = Host.Local.FindSingle<Text>(counterDisplay);
if (int.TryParse(counterElement.Text, out int counterValue))
{
if (counterValue > 0)
{
Report.Success("Numeric Validation", $"Counter value is positive: {counterValue}");
}
else
{
Report.Failure("Numeric Validation", $"Counter should be positive, but is: {counterValue}");
}
}
else
{
Report.Failure("Numeric Validation", $"Counter text is not numeric: '{counterElement.Text}'");
}
// 5. Color validation (for visual verification)
var statusIndicator = "/form/panel[@name='status']";
var statusPanel = Host.Local.FindSingle<Container>(statusIndicator);
// Capture element screenshot for color analysis
var elementImage = statusPanel.CaptureCompressedImage();
// In real scenarios, you would analyze the image for expected colors
Report.Info("Visual Validation", "Status indicator color captured for analysis");
// 6. List/Table content validation
var dataTable = "/form/table[@name='results']";
var table = Host.Local.FindSingle<Table>(dataTable);
var rows = table.Find<Row>("./row");
if (rows.Count >= 1)
{
Report.Success("Data Validation", $"Table contains {rows.Count} rows as expected");
// Validate specific cell content
var firstRowFirstCell = rows[0].Find<Cell>("./cell")[0];
if (firstRowFirstCell.Text.Contains("Expected Data"))
{
Report.Success("Cell Validation", "First cell contains expected data");
}
}
else
{
Report.Failure("Data Validation", "Table should contain at least one row");
}
// 7. URL validation (for web applications)
try
{
var webDoc = Host.Local.FindSingle<WebDocument>("/dom[@domain='example.com']");
string currentUrl = webDoc.PageUrl;
string expectedUrl = "https://example.com/dashboard";
if (currentUrl.Contains("dashboard"))
{
Report.Success("URL Validation", "Navigated to correct page");
}
else
{
Report.Failure("URL Validation", $"Expected URL containing 'dashboard', but found: {currentUrl}");
}
}
catch (RanorexException)
{
Report.Info("URL Validation", "No web document found - skipping web validation");
}
}
catch (Exception ex)
{
Report.Failure("Basic Validations", $"Validation failed: {ex.Message}");
throw;
}
finally
{
Host.Shutdown();
}
}
}
Repository Basics
Learn how to use Ranorex repositories for organized element management.
using Ranorex;
using Ranorex.Core;
using System;
// Example showing repository usage patterns
public class RepositoryBasics
{
public void Run()
{
Host.Initialize();
try
{
// 1. Basic repository access
var repo = MyAppRepository.Instance;
// Access elements through repository structure
repo.LoginDialog.UsernameField.Click();
repo.LoginDialog.UsernameField.PressKeys("testuser");
repo.LoginDialog.PasswordField.Click();
repo.LoginDialog.PasswordField.PressKeys("password123");
repo.LoginDialog.LoginButton.Click();
Report.Info("Repository", "Performed login using repository elements");
// 2. Wait for elements using repository
repo.MainWindow.Self.WaitForExists(10000);
Report.Success("Repository", "Main window appeared after login");
// 3. Check element properties through repository
if (repo.MainWindow.WelcomeLabel.Exists)
{
string welcomeText = repo.MainWindow.WelcomeLabel.Text;
Report.Info("Repository", $"Welcome message: {welcomeText}");
}
// 4. Repository element validation
if (repo.MainWindow.MenuBar.FileMenu.Enabled)
{
repo.MainWindow.MenuBar.FileMenu.Click();
Report.Info("Repository", "Opened File menu");
// Access submenu through repository
repo.MainWindow.MenuBar.FileMenu.NewMenuItem.Click();
Report.Info("Repository", "Selected New from File menu");
}
// 5. Working with repository collections
var menuItems = repo.MainWindow.MenuBar.Self.Find<MenuItem>("./menuitem");
Report.Info("Repository", $"Found {menuItems.Count} menu items");
foreach (var item in menuItems)
{
Report.Info("Menu Item", $"Available: {item.Text}");
}
}
catch (Exception ex)
{
Report.Failure("Repository Basics", $"Repository operation failed: {ex.Message}");
throw;
}
finally
{
Host.Shutdown();
}
}
}
// Example repository structure (this would be auto-generated by Ranorex Studio)
public partial class MyAppRepository
{
private static MyAppRepository _instance;
public static MyAppRepository Instance
{
get
{
if (_instance == null)
_instance = new MyAppRepository();
return _instance;
}
}
public MyAppRepositoryFolders.LoginDialogFolder LoginDialog { get; private set; }
public MyAppRepositoryFolders.MainWindowFolder MainWindow { get; private set; }
private MyAppRepository()
{
LoginDialog = new MyAppRepositoryFolders.LoginDialogFolder(this);
MainWindow = new MyAppRepositoryFolders.MainWindowFolder(this);
}
}
// Repository folder structure
public class MyAppRepositoryFolders
{
public class LoginDialogFolder
{
private readonly MyAppRepository _repo;
public LoginDialogFolder(MyAppRepository repo)
{
_repo = repo;
}
public Form Self => Host.Local.FindSingle<Form>("/form[@title='Login']");
public Text UsernameField => Self.FindSingle<Text>("./text[@name='username']");
public Text PasswordField => Self.FindSingle<Text>("./text[@name='password']");
public Button LoginButton => Self.FindSingle<Button>("./button[@text='Login']");
}
public class MainWindowFolder
{
private readonly MyAppRepository _repo;
public MainWindowFolder(MyAppRepository repo)
{
_repo = repo;
MenuBar = new MenuBarFolder(_repo);
}
public Form Self => Host.Local.FindSingle<Form>("/form[@title='MyApp']");
public Text WelcomeLabel => Self.FindSingle<Text>("./text[@name='welcome']");
public MenuBarFolder MenuBar { get; private set; }
}
public class MenuBarFolder
{
private readonly MyAppRepository _repo;
public MenuBarFolder(MyAppRepository repo)
{
_repo = repo;
}
public MenuBar Self => Host.Local.FindSingle<MenuBar>("/form[@title='MyApp']/menubar");
public MenuItem FileMenu => Self.FindSingle<MenuItem>("./menuitem[@text='File']");
}
}
Application Lifecycle Management
Complete example of managing application startup, operation, and shutdown.
using Ranorex;
using Ranorex.Core;
using System;
using System.Diagnostics;
public class ApplicationLifecycleExample
{
public void Run()
{
Host.Initialize();
Process applicationProcess = null;
try
{
// 1. Application startup with process tracking
Report.Info("Lifecycle", "Starting application");
applicationProcess = StartApplication("C:\\MyApp\\MyApp.exe");
// 2. Wait for application to be ready
WaitForApplicationReady();
// 3. Perform application operations
PerformApplicationTasks();
// 4. Graceful shutdown
Report.Info("Lifecycle", "Shutting down application gracefully");
GracefulShutdown();
}
catch (Exception ex)
{
Report.Failure("Lifecycle", $"Application lifecycle failed: {ex.Message}");
// Force kill if graceful shutdown failed
if (applicationProcess != null && !applicationProcess.HasExited)
{
Report.Info("Lifecycle", "Force killing application process");
applicationProcess.Kill();
}
throw;
}
finally
{
Host.Shutdown();
}
}
private Process StartApplication(string applicationPath)
{
var processInfo = new ProcessStartInfo
{
FileName = applicationPath,
WorkingDirectory = System.IO.Path.GetDirectoryName(applicationPath),
UseShellExecute = false
};
var process = Process.Start(processInfo);
Report.Success("Startup", $"Application started with PID: {process.Id}");
return process;
}
private void WaitForApplicationReady()
{
// Wait for main window
var mainWindow = "/form[@title='MyApp']";
Host.Local.FindSingle<Form>(mainWindow, 30000);
// Wait for loading to complete
var loadingIndicator = "/form[@title='MyApp']/text[@text='Loading...']";
Host.Local.WaitForNotExists(loadingIndicator, 60000);
Report.Success("Startup", "Application is ready for automation");
}
private void PerformApplicationTasks()
{
// Example application operations
var repo = MyAppRepository.Instance;
// Navigate to a feature
repo.MainWindow.MenuBar.ToolsMenu.Click();
repo.MainWindow.MenuBar.ToolsMenu.OptionsMenuItem.Click();
// Configure something
repo.OptionsDialog.GeneralTab.Click();
repo.OptionsDialog.AutoSaveCheckbox.Click();
repo.OptionsDialog.OkButton.Click();
Report.Info("Operation", "Completed application configuration");
}
private void GracefulShutdown()
{
var repo = MyAppRepository.Instance;
// Try normal exit first
repo.MainWindow.MenuBar.FileMenu.Click();
repo.MainWindow.MenuBar.FileMenu.ExitMenuItem.Click();
// Handle save dialog if present
try
{
repo.SaveDialog.Self.WaitForExists(5000);
repo.SaveDialog.DontSaveButton.Click();
}
catch (RanorexException)
{
// No save dialog appeared
}
// Wait for application to close
Host.Local.WaitForNotExists("/form[@title='MyApp']", 10000);
Report.Success("Shutdown", "Application closed gracefully");
}
}
Next Steps
After mastering these basic patterns:
- Code Cookbook - Learn reusable utilities and helper methods
- Desktop Patterns - Technology-specific automation techniques
- Web Patterns - Browser automation patterns
- Advanced Integration - Complex scenarios and external integrations
Common Troubleshooting
Element Not Found
- Verify your RanoreXPath expressions using Ranorex Spy
- Add appropriate wait times for dynamic content
- Check if the element is in a different window or frame
Timing Issues
- Use
WaitForExists()instead of fixed delays - Implement proper synchronization points
- Consider application load times and network delays
Permission Problems
- Run with appropriate user permissions
- Check if UAC is interfering with automation
- Verify application accessibility settings
For more troubleshooting tips, see our comprehensive guides.