Code Examples

The following code examples explain how to use Ranorex API in order to write code modules or to extend recording modules with user specific code.

Using Repository in Code

C#

[TestModule("D451F1D1-C347-4B58-939F-F6187642EB56", ModuleType.UserCode, 1)]
public class UsingRepository : ITestModule
{
 // Repository object to access UI elements
 MyFirstTestProjectRepository repo = MyFirstTestProjectRepository.Instance;
 	
 /// <summary>
 /// Constructs a new instance.
 /// </summary>
 public UsingRepository()
 {
 // Do not delete - a parameterless constructor is required!
 }

 void ITestModule.Run()
 {
 Mouse.DefaultMoveTime = 300;
 Keyboard.DefaultKeyPressTime = 100;
 Delay.SpeedFactor = 1.0;
 
 // Using Ranorex.Form adapter represented by 'MyApp'
 // 'MyApp' is used as a folder within the repository; 
 // the 'Self' property returns an object of type Ranorex.Form
 
 // Activates application
 repo.MyApp.Self.Activate();
 // Log 'Active' state
 Report.Info(repo.MyApp.Self.Active.ToString());
 // Maximize, Minimize and Restore 
 repo.MyApp.Self.Maximize();
 repo.MyApp.Self.Minimize();
 repo.MyApp.Self.Restore();
 // Closes application
 repo.MyApp.Self.Close();
 
 
 // Using Ranorex.Button adapter represented by 'ButtonAdd' 
 // Read and log value of 'Text' attribute
 Report.Info(repo.MyApp.Buttons.ButtonAdd.Text);
 
 // Press button
 repo.MyApp.Buttons.ButtonAdd.Press();
 // Read and log value of 'Enabled' attribute
 Report.Info(repo.MyApp.Buttons.ButtonAdd.Enabled.ToString());
 
 // Using Ranorex.RadioButton adapter
 // represented by 'GenderOption'
 
 // Select radio button
 repo.MyApp.GenderOption.Select();
 
 // Accessing listitems of Ranorex.List adapter
 // represented by 'CategoryList'
 IList<ranorex.listitem> listItems = repo.MyApp.CategoryList.Items;
 foreach ( Ranorex.ListItem item in listItems )
 {
 	Report.Info(item.Text + " is member of CategoryList");
 }
 
 // Using Ranorex.MenuItem to open 'File' menu
 repo.MyApp.MenuItemFile.Select(); 
 // Selecting sub menu item 'Connect'
 repo.FileMenu.Connect.Select(); 
 // Read and log 'Enabled' state of menu item 'Connect'
 Report.Info(repo.FileMenu.Connect.Enabled.ToString());
 }
}

VB.NET

Public Class UsingRepository
	Implements ITestModule
	' Repository object to access UI elements
	Private repo As MyFirstTestProjectRepository = MyFirstTestProjectRepository.Instance

	''' <summary>
	''' Constructs a new instance.
	''' </summary>
			' Do not delete - a parameterless constructor is required!
	Public Sub New()
	End Sub

	''' <summary>
	''' Performs the playback of actions in this module.
	''' </summary>
	''' <remarks>You should not call this method directly, instead pass the module
	''' instance to the <see cref="TestModuleRunner.Run(ITestModule)"> method
	''' that will in turn invoke this method.</see></remarks>
	Private Sub ITestModule_Run() Implements ITestModule.Run
		Mouse.DefaultMoveTime = 300
		Keyboard.DefaultKeyPressTime = 100
		Delay.SpeedFactor = 1.0
		' Using Ranorex.Form adapter represented by 'MyApp'
		' 'MyApp' is used as a folder within the repository; 
		' the 'Self' property returns a Ranorex.Form object

		' Activates application
		repo.MyApp.Self.Activate()
		' Log 'Active' state
		Report.Info(repo.MyApp.Self.Active.ToString())
		' Maximize, Minimize and Restore 
		repo.MyApp.Self.Maximize()
		repo.MyApp.Self.Minimize()
		repo.MyApp.Self.Restore()
		' Closes application
		repo.MyApp.Self.Close()


		' Using Ranorex.Button adapter represented by ButtonAdd' 
		' Read and log value of 'Text' attribute
		Report.Info(repo.MyApp.Buttons.ButtonAdd.Text)

		' Press button
		repo.MyApp.Buttons.ButtonAdd.Press()
		' Read and log value of 'Enabled' attribute
		Report.Info(repo.MyApp.Buttons.ButtonAdd.Enabled.ToString())

		' Using Ranorex.RadioButton adapter
		' represented by 'GenderOption'

		' Select radio button
		repo.MyApp.GenderOption.[Select]()
		' Accessing listitems of Ranorex.List adapter
		' represented by 'CategoryList'
		Dim listItems As IList(Of Ranorex.ListItem) = repo.MyApp.CategoryList.Items
		For Each item As Ranorex.ListItem In listItems
			Report.Info(item.Text & " is member of CategoryList")
		Next

		' Using Ranorex.MenuItem to open 'File' menu
		repo.MyApp.MenuItemFile.[Select]()
		' Selecting sub menu item 'Connect'
		repo.FileMenu.Connect.[Select]()
		' Read and log 'Enabled' state of menu item 'Connect'
		Report.Info(repo.FileMenu.Connect.Enabled.ToString())
	End Sub
End Class

Wait for UI Elements Using Repository

Each item and each folder type provides an additional object item declared with '<objectname>Info'. It is used to access item related attributes without accessing the UI element directly in order to prevent Ranorex from throwing exceptions. The info object is mainly used to check whether an item or a folder path is valid or not. In combination with the timeout set for the item, you can use it to wait for UI elements like dialogs, text values and web content.

C#

// Use the 'Info' object to check existence of the
// 'SaveDialog' item; Method 'Exists' uses the timeout 
// specified for the 'SaveDialog' in the repository
Report.Info("Exists = " + repo.SaveDialog.SelfInfo.Exists().ToString());
 
// Use the 'Info' object to check existence of the
// 'TextOnline' item which uses the following RXPath:
// statusbar/text[@accessiblename='Online']
// This way you can wait with the timeout specified for
// the item within the repository for the text 'Online'
bool statusTextConnected = repo.MyApp.TextOnlineInfo.Exists();
 
// Using 'Info' objects for validation
// Throws a Ranorex.ValidationException if validation
// fails. Automatically reports success or failed message
// to log file 	 	
Validate.Exists(repo.SaveDialog.ButtonOKInfo);
						
// Validates the existence of the repository item,
// but does not throw any exception
Validate.Exists(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false);

VB.NET

' Use the 'Info' object to check existence of the
' 'SaveDialog' item; Method 'Exists' uses the timeout 
' specified for the 'SaveDialog' in the repository
Report.Info("Exists = " & repo.SaveDialog.SelfInfo.Exists().ToString())

' Use the 'Info' object to check existence of the
' 'TextOnline' item which uses the following RXPath:
' statusbar/text[@accessiblename='Online']
' This way you can wait with the timeout specified for
' the item within the repository for the text 'Online'
Dim statusTextConnected As Boolean = repo.MyApp.TextOnlineInfo.Exists()

' Using 'Info' objects for validation
' Throws a Ranorex.ValidationException if validation
' fails. Automatically reports success or failed message
' to log file 	 	
Validate.Exists(repo.SaveDialog.ButtonOKInfo)

' Validates the existence of the repository item,
' but does not throw any exception
Validate.Exists(repo.SaveDialog.ButtonOKInfo, "Check Object '{0}'", False)

Create Adapters to Access More Properties and Methods

If you analyze the VIP Database application form with Ranorex Spy, you see that that the application window provides three adapters (Form, Control and NativeWindow). The Ranorex.Form adapter with all attributes and methods is directly available using the repository's application folder 'MyApp'. If you want to access properties like 'ProcessName' or invoke methods exposed by a .NET WinForms control you need to convert the Form adapter to NativeWindow or Control. As you can see in the code section below the '...Info' object is used to create the desired adapter.

C#

// Creating adapter of type 'NativeWindow' using the "...Info" object 
Ranorex.NativeWindow nativeWnd = repo.MyApp.SelfInfo.CreateAdapter<Ranorex.NativeWindow>(false);
// ... and read value of attribute 'ProcessName'
Report.Info("Process name of VIP Database: " + nativeWnd.ProcessName);
			 
// Using Control Adapter to access properties and methods of 
// .NET WinForms control
Ranorex.Control winFormsControl = repo.MyApp.SelfInfo.CreateAdapter<Ranorex.Control>(false);
// Set background color of VIP application to Color.Black using the
// exposed property 'BackColor'
winFormsControl.SetPropertyValue("BackColor",Color.Black);
			 
// Report screenshot after changing the background color
Report.Screenshot(repo.MyApp.Self);
// Closes VIP Database by invoking the 'Close' method
// exposed by the System.Windows.Forms.Form class
winFormsControl.InvokeMethod("Close");

VB.NET

' Creating adapter of type 'NativeWindow' using the "...Info" object 
Dim nativeWnd As Ranorex.NativeWindow = repo.MyApp.SelfInfo.CreateAdapter(Of Ranorex.NativeWindow)(False)
' ... and read value of attribute 'ProcessName'
Report.Info("Process name of VIP Database: " & nativeWnd.ProcessName)

' Using Control Adapter to access properties and methods of 
' .NET WinForms control
Dim winFormsControl As Ranorex.Control = repo.MyApp.SelfInfo.CreateAdapter(Of Ranorex.Control)(False)
' Set background color of VIP application to Color.Black using the
' exposed property 'BackColor'
winFormsControl.SetPropertyValue("BackColor", Color.Black)

' Report screenshot after changing the background color
Report.Screenshot(repo.MyApp.Self)
' Closes VIP Database by invoking the 'Close' method
' exposed by the System.Windows.Forms.Form class
winFormsControl.InvokeMethod("Close")
Note: In order to access properties or methods exposed by a WinForms control you need to know their names. If you're not familiar with the control's API ask the developer of your application for assistance.

Create a List of Adapters From a Repository Element

If multiple elements match a RanoreXPath of a single repository item use the CreateAdapters method to create a list of adapters.

C#

// Create a list of adapters using the "Info" object
IList<Ranorex.Button> buttonList = 
    repo.MyApp.EnabledButtonsInfo.CreateAdapters<Ranorex.Button>();

// Move the mouse pointer to each button of the list
// and add a screenshot for each to the report        	
foreach (Ranorex.Button button in buttonList )
{
	button.MoveTo();
	Report.Screenshot(button);
}        	

VB.NET

' Create a list of adapters using the "Info" object
Dim buttonList As IList(Of Ranorex.Button) = 
    repo.MyApp.EnabledButtonsInfo.CreateAdapters(Of Ranorex.Button)()

' Move the mouse pointer to each button of the list
' and add a screenshot for each to the report
For Each button As Ranorex.Button In buttonList
	button.MoveTo()
	Report.Screenshot(button)
Next
Learn more about how to create repository items delivering multiple elements here: Adding Repository Items

Using Validate Class

The Ranorex.Validate class is used to check values from UI elements, but it can also be used to simply compare non UI related objects in code. In comparison to a simple IF statement the methods provided automatically log fail or success messages to the report.

C#

// Validate for Existence

// Using 'Info' objects for validation
// Throws a Ranorex.ValidationException if validation
// fails. Automatically reports success or failed message
// to log file            	            	
Validate.Exists(repo.SaveDialog.ButtonOKInfo);
						
// Validates the existence of the repository item,
// but does not throw any exception
bool exists = Validate.Exists(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false);
			
// Check whether an application form exists using a RanoreXPath
Validate.Exists("/form[@controlname='formVipApplication']");

// Check whether an application does not exists
// for the time specified as timeout for the given repository item
Validate.NotExists(repo.MyApp.SelfInfo);

// Validate 'Enabled' attribute of button 'Delete'
Validate.Attribute(repo.MyApp.Buttons.ButtonDeleteInfo,"Enabled",false);

VB.NET

' Validate for Existence

' Using 'Info' objects for validation
' Throws a Ranorex.ValidationException if validation
' fails. Automatically reports success or failed message
' to log file            	            	
Validate.Exists(repo.SaveDialog.ButtonOKInfo)
						
' Validates the existence of the repository item,
' but does not throw any exception
Dim exists As Boolean = Validate.Exists(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false)
			
' Check whether an application form exists using a RanoreXPath
Validate.Exists("/form[@controlname='formVipApplication']")

' Check whether an application does not exists
' for the time specified as timeout for the given repository item
Validate.NotExists(repo.MyApp.SelfInfo)

' Validate 'Enabled' attribute of button 'Delete'
Validate.Attribute(repo.MyApp.Buttons.ButtonDeleteInfo,"Enabled",false)
Note: Each method provided by the Validate class allows to suppress exceptions thrown in case of a failed validation. The code snippet above uses only a few validation methods. For further and more detailed explanation of the Ranorex.Validate class see the API documentation.

Forcing a Test Case to Fail

Ranorex uses exception handling to determine whether a test case run failed or succeeded. As long as no exception is thrown by any of the Ranorex methods (e.g Ranorex.Validate method or use of not valid repository item) the test run will be successful. If you want to prevent Ranorex from throwing exceptions but at the same time decide on your own whether a test case fails or not, you need to throw Ranorex exceptions programmatically.

C#

Ranorex.Cell cellObject = null;
// Try to find  a cell object using two 
// different RanoreXPath expressions
bool found=false;
found = Host.Local.TryFindSingle<Ranorex.Cell>("/form//table/row/cell[3]", 2000, out cellObject);
found = Host.Local.TryFindSingle<Ranorex.Cell>("/form//table/row/cell[4]", 2000, out cellObject);
// If none of the expressions returns an object
// throw new 'ElementNotFoundException' and test case fails
if (!found)
{
	throw new Ranorex.ElementNotFoundException("Both RanoreXPath with no return", null);            	
}
else
{
	// If the value of attribute 'Text' does not equal to the expected value
	// throw new 'ValidationException' to break the test case
	if ( cellObject.Text == "MyExpectedTextValue" )
	{
		Report.Success("User Specific Validation","Text validation of cell object succeeded");
	}
    else
   	{
		throw new Ranorex.ValidationException("Text validation of cell object succeeded failed");
   	}
}

VB.NET

Dim cellObject As Ranorex.Cell = Nothing
' Try to find  a cell object using two 
' different RanoreXPath expressions
Dim found As Boolean = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell[3]", 2000, cellObject)
found = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell[4]", 2000, cellObject)
' If none of the expressions returns an object
' throw new 'ElementNotFoundException' and test case fails
If Not found Then
	Throw New Ranorex.ElementNotFoundException("Both RanoreXPath with no return", Nothing)
Else
	' If the value of attribute 'Text' does not equal to the expected value
	' throw new 'ValidationException' to break the test case
	If cellObject.Text = "MyExpectedTextValue" Then
		Report.Success("User Specific Validation", "Text validation of cell object succeeded")
	Else
		Throw New Ranorex.ValidationException("Text validation of cell object succeeded failed")
	End If
End If

Set Up Automation Speed

You can optionally specify and change the automation speed at any time in the code. The code generated by a recording uses the same properties to define replay speed as used within a code module. A newly created code module already contains three lines of code specifying the automation speed in the 'Run' method.

C#

void ITestModule.Run()  
{  
     Mouse.DefaultMoveTime = 300;  
     Keyboard.DefaultKeyPressTime = 100;  
     Delay.SpeedFactor = 1.0; 
}

VB.NET

Private Sub ITestModule_Run() Implements ITestModule.Run
     Mouse.DefaultMoveTime = 300  
     Keyboard.DefaultKeyPressTime = 100
     Delay.SpeedFactor = 1.0
End Sub

Accessing Test Case & Test Suite Context

Sometimes it's necessary to forward values read from the UI in a code module or recording to the module executed next in the scope of a test case. The example code shown below uses the module variables varDialogTextA (Code Module A) and varDialogTextB (Code Module B) which are both bound to a parameter specified within the test case's data binding dialog to transfer data within a test case.

C#

// ----------------- Code Block used by Code Module A -----------------

// Click 'Save' button to open 'SaveDialog'
repo.MyApp.Buttons.ButtonSave.Click();
// Read text message shown with 'SaveDialog'
// and assign it to the variable 'varDialogTextA' bound to a test case parameter
varDialogTextA = repo.SaveDialog.TextMessage.TextValue;          



// -------- Code Block used by User Code Action of recording B --------            

// Read value of module variable 'varDialogTextB' in other code module
// or recording module using a user code action
Report.Info(varDialogTextB);

// Get the current data context and log
// the current row index of a data driven run
Report.Info(TestCase.Current.DataContext.CurrentRow.ToString());

VB.NET

' ----------------- Code Block used by Code Module A -----------------

' Click 'Save' button to open 'SaveDialog'
repo.MyApp.Buttons.ButtonSave.Click()
' Read text message shown with 'SaveDialog'
' and assign it to the variable 'varDialogTextA' bound to a test case parameter
varDialogTextA = repo.SaveDialog.TextMessage.TextValue

' -------- Code Block used by User Code Action of recording B --------            

' Read value of module variable 'varDialogTextB' in other code module
' or recording module using a user code action
Report.Info(varDialogTextB)

' Get the current data context and log
' the current row index of a data driven run
Report.Info(TestCase.Current.DataContext.CurrentRow.ToString())

Advanced Code Examples

You can also use RanoreXPath expressions directly in code in order to search for items using different 'Find' methods offered by the API. Start searching for elements directly at the root level using 'Host.Local' or reuse existing adapters like repository items to start searching from there.

C#

// Create Ranorex.Button adapter using 'FindSingle' method
// from Host.Local (starting at root node) with absolute RanoreXPath
// Note: ElementNotFound exception is thrown if item is not found within
// the specified timeout of 2000 ms.
Ranorex.Button addButtonVar1 = Host.Local.FindSingle<Ranorex.Button>("/form[@controlname='formVipApplication']/button[@controlname='btAdd']",2000);
addButtonVar1.MoveTo();
            
// Alternatively you can use the 'TryFindSingle' method to prevent
// a test case from failing  because of an exception thrown if
// the element is not found within the specified timeout of 2000 ms
Ranorex.Button addButtonVar2 = null;
bool found = Host.Local.TryFindSingle<Ranorex.Button>("/form[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000, out addButtonVar2);
// Move mouse pointer to button
addButtonVar2.MoveTo();
                        
// Request a list of buttons shown from the VIP Database application
// and create a screenshot for each button in the report file
IList<Ranorex.Button> buttonList = Host.Local.Find<Ranorex.Button>("/form[@controlname='formVipApplication']/button",500);
foreach (Ranorex.Button bt in buttonList)
{
     Report.Screenshot(bt);
}

// Using find methods in combination with existing Ranorex repository items
Ranorex.Button btAdd = repo.MyApp.Self.FindSingle<Ranorex.Button>("button[@controlname='btAdd']",2000);

VB.NET

' Create Ranorex.Button adapter using 'FindSingle' method
' from Host.Local (starting at root node) with absolute RanoreXPath
' Note: ElementNotFound exception is thrown if item is not found within
' the specified timeout of 2000 ms.
Dim addButtonVar1 As Ranorex.Button = Host.Local.FindSingle(Of Ranorex.Button)("/form[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000)
addButtonVar1.MoveTo()

' Alternatively you can use 'TryFindSingle' method to prevent
' a test case from failing  because of an exception thrown if
' the element is not found within the specified timeout of 2000 ms
Dim addButtonVar2 As Ranorex.Button = Nothing
Dim found As Boolean = Host.Local.TryFindSingle(Of Ranorex.Button)("/form[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000, addButtonVar2)
' Move mouse pointer to button
addButtonVar2.MoveTo()

' Request a list of buttons from the VIP Database application
' and create a screenshot for each button in the report file
Dim buttonList As IList(Of Ranorex.Button) = Host.Local.Find(Of Ranorex.Button)("/form[@controlname='formVipApplication']/button", 500)
For Each bt As Ranorex.Button In buttonList
	Report.Screenshot(bt)
Next

' Using find methods in combination with existing Ranorex repository items
Dim btAdd As Ranorex.Button = repo.MyApp.Self.FindSingle(Of Ranorex.Button)("button[@controlname='btAdd']", 2000)

How to do image based automation

If Ranorex is not able to clearly identify some of your GUI elements, it may be helpful to automate them using the implicit image search mechanism of the 'Click' method.

C#

// Create bitmap to search for
// within application form and
// click it
Bitmap bmp = Ranorex.Imaging.Load(
                       @"..\..\Green Sea Turtle Small.bmp");        	
// Performs a right click on the image found
// within the application window based on
// the image location
myRepo.WinFormsApp.Self.Click(MouseButtons.Right,bmp);

// You can also search for images that are slightly different to the
// loaded image by specifying the minimum Similarity for a match (95% = 0.95).
myRepo.WinFormsApp.Self.Click(new Location(bmp, new Imaging.FindOptions(0.95)));
        	
// OR Set the default Similarity value for all following image operations
Imaging.FindOptions.Default.Similarity = 0.95;
myRepo.WinFormsApp.Self.Click(bmp);
        	
Report.Success("Image found and clicked successfully");

VB.NET

' Create bitmap to search for
' within application form and
' click it
Dim bmp As Bitmap = Ranorex.Imaging.Load("..\..\Green Sea Turtle Small.bmp")
' Performs a right click on the image found
' within the application window based 
' on the image location
myRepo.WinFormsApp.Self.Click(MouseButtons.Right, bmp)

' You can also search for images that are slightly different to the
' loaded image by specifying the minimum Similarity for a match (95% = 0.95).
myRepo.WinFormsApp.Self.Click(new Location(bmp, new Imaging.FindOptions(0.95)))
        	
' OR Set the default Similarity value for all following image operations
Imaging.FindOptions.Default.Similarity = 0.95
myRepo.WinFormsApp.Self.Click(bmp)

Report.Success("Image displayed successfully")

How to find and compare images

To compare an image simply search for it within an existing Ranorex element using the 'Contains' method.

C#

// Create bitmap
Bitmap bmp = Ranorex.Imaging.Load(
                       @"..\..\Green Sea Turtle Small.bmp");        	
        	   	
// Search for it within the application window
if (Ranorex.Imaging.Contains(myRepo.WinFormsApp.Self,bmp) == true)
{
  Report.Success("Image found within WinForms application");
}

VB.NET

' Create bitmap
Dim bmp As Bitmap = Ranorex.Imaging.Load("..\..\Green Sea Turtle Small.bmp")
' Search for it within the application window
If Imaging.Contains(myRepo.WinFormsApp.Self,bmp Then
  Report.Success("Image found within WinForms application")
End If
  
Note: Both examples load an uncompressed file (BMP or PNG format) in order to carry out a one-to-one comparison. Use the FindOptions class to configure similarity, preprocessing and other search settings.

Handling unexpected Dialogs

A common problem in UI testing is the appearance of an unexpected dialog - e.g. the Update-Check dialog in KeePass.

To overcome this issue, you can use the PopupWatcher class.

Using this class you can add watches for each dialog which might pop up during test execution.

In this watches you can specify a RanoreXPath or a Repository item the PopupWatcher should keep watching for, as well as a method which should be triggered or a repository item which should be clicked.

C#

void ITestModule.Run()
{

 // Create PopupWatcher
 PopupWatcher myPopupWatcher = new PopupWatcher();
 
 // Add a Watch using a RanoreXPath and triggering the Method CloseUpdateCheckDialog
 myPopupWatcher.Watch("/form[@controlname='UpdateCheckForm']/button[@controlname='m_btnClose']", CloseUpdateCheckDialog);

 // Add a Watch using the info object of a button and triggering the Method CloseUpdateCheckDialog
 // myPopupWatcher.Watch(repo.UpdateCheckDialog.btCloseInfo, CloseUpdateCheckDialog);
 
 // Add a Watch using the info object of the dialog and the info object of the button to click
 // myPopupWatcher.WatchAndClick(repo.UpdateCheckDialog.SelfInfo, repo.UpdateCheckDialog.btCloseInfo);
 
 // Add a Watch using a repository folder object and the info object of the button to click
 // myPopupWatcher.WatchAndClick(repo.UpdateCheckDialog, repo.UpdateCheckDialog.btCloseInfo);

 // Start PopupWatcher
 myPopupWatcher.Start();

}

public static void CloseUpdateCheckDialog(Ranorex.Core.Repository.RepoItemInfo myInfo, Ranorex.Core.Element myElement)
{
 myElement.As<ranorex.button>().Click();
}

public static void CloseUpdateCheckDialog(Ranorex.Core.RxPath myPath, Ranorex.Core.Element myElement)
{
 myElement.As<ranorex.button>().Click();
}

VB.NET

Private Sub ITestModule_Run() Implements ITestModule.Run

	' Create PopupWatcher
	Dim myPopupWatcher As New PopupWatcher()

	' Add a Watch using a RanoreXPath and triggering the Method CloseUpdateCheckDialog
	myPopupWatcher.Watch("/form[@controlname='UpdateCheckForm']/button[@controlname='m_btnClose']", AddressOf CloseUpdateCheckDialog)

	' Add a Watch using the info object of a button and triggering the Method CloseUpdateCheckDialog
	' myPopupWatcher.Watch(repo.UpdateCheckDialog.btCloseInfo, CloseUpdateCheckDialog);

	' Add a Watch using the info object of the dialog and the info object of the button to click
	' myPopupWatcher.WatchAndClick(repo.UpdateCheckDialog.SelfInfo, repo.UpdateCheckDialog.btCloseInfo);

	' Add a Watch using a repository folder object and the info object of the button to click
	' myPopupWatcher.WatchAndClick(repo.UpdateCheckDialog, repo.UpdateCheckDialog.btCloseInfo);

	' Start PopupWatcher
	myPopupWatcher.Start()

End Sub

Public Shared Sub CloseUpdateCheckDialog(myInfo As Ranorex.Core.Repository.RepoItemInfo, myElement As Ranorex.Core.Element)
	myElement.[As](Of Ranorex.Button)().Click()
End Sub

Public Shared Sub CloseUpdateCheckDialog(myPath As Ranorex.Core.RxPath, myElement As Ranorex.Core.Element)
	myElement.[As](Of Ranorex.Button)().Click()
End Sub