Table of Contents

Class GuiSession

Namespace
SapGui.Wrapper
Assembly
SapGui.Wrapper.dll

Represents a single SAP GUI session (one window / logon). This is the primary object used for day-to-day automation.

Equivalent to the VBA GuiSession object.

public class GuiSession : GuiComponent, IDisposable
Inheritance
GuiSession
Implements
Inherited Members

Properties

ActiveWindow

Returns the currently active (focused) window in this session. Equivalent to the VBA session.ActiveWindow property. Useful to detect which wnd[x] has focus without guessing the index.

public GuiMainWindow ActiveWindow { get; }

Property Value

GuiMainWindow

Info

Session info, e.g. system ID, client, user.

public GuiSessionInfo Info { get; }

Property Value

GuiSessionInfo

IsBusy

Whether the session is currently busy processing a request.

public bool IsBusy { get; }

Property Value

bool

Methods

Button(string)

Returns a button by ID.

public GuiButton Button(string id)

Parameters

id string

Returns

GuiButton

Calendar(string)

Returns a GuiCalendar by ID.

public GuiCalendar Calendar(string id)

Parameters

id string

Returns

GuiCalendar

CheckBox(string)

Returns a check box by ID.

public GuiCheckBox CheckBox(string id)

Parameters

id string

Returns

GuiCheckBox

ComboBox(string)

Returns a combo box by ID.

public GuiComboBox ComboBox(string id)

Parameters

id string

Returns

GuiComboBox

CreateSession()

Opens a new parallel SAP session on the same connection. The new session appears as the next child in the parent connection's Children collection (Children[n]). Equivalent to the VBA session.CreateSession().

The method returns immediately; poll GetSessions() afterwards to obtain the new GuiSession object.

public void CreateSession()

DismissPostLoginPopups(int, int)

Automatically dismisses common post-SSO / post-login pop-up dialogs.

Call this immediately after obtaining a session from LaunchWithSso(string, bool, int, SapLogAction?, SapLogLevel, ILogger?) (or any other login flow) to clear system notices before starting automation.

Dialogs handled (tried in this order):

  • Multiple Logon / User already logged on – clicks Continue to keep the existing session running and start a new one in parallel.
  • License expiration warnings – clicks OK.
  • System message banners / Message of the Day – clicks OK.
  • Any single-button information dialog – presses that button.

Unrecognised multi-button dialogs are left untouched so that automation does not blindly dismiss dialogs that require a deliberate choice.

Worst-case blocking time: up to maxPopups × timeoutMs + (maxPopups - 1) × 300 ms. With the defaults (5 popups, 3 000 ms each) that is approximately 16.2 seconds when no popups appear at all. Reduce timeoutMs if faster failure detection is needed.

public int DismissPostLoginPopups(int maxPopups = 5, int timeoutMs = 3000)

Parameters

maxPopups int

Maximum number of pop-ups to dismiss in a single call (default 5). Guards against an unexpected dialog loop.

timeoutMs int

Time in milliseconds to wait for each pop-up to appear before concluding there are no more (default 3 000 ms).

Returns

int

The number of pop-ups that were dismissed.

Dispose()

Stops event monitoring and releases the underlying COM RCW for this session immediately, rather than waiting for the GC finalizer.

Does NOT log off or close the SAP window. The session continues to run inside SAP GUI; only the .NET wrapper reference is released. After Dispose, do not call any methods on this GuiSession instance.

Safe to call multiple times.

public void Dispose()

ElementExists(string, int, int)

Polls until the component with id exists and is accessible, or until timeoutMs elapses.

public bool ElementExists(string id, int timeoutMs = 10000, int pollMs = 200)

Parameters

id string

Component ID path, e.g. "wnd[0]/usr/txtFoo".

timeoutMs int

How long to poll in ms. Default: 10 000.

pollMs int

Polling interval in ms. Default: 200.

Returns

bool

true if the component appeared within the timeout.

ExitTransaction()

Exits the current transaction and returns to the SAP Easy Access menu. Equivalent to typing /n in the command field and pressing Enter.

Use /nXX via StartTransaction(string) to jump directly to another transaction without returning to the menu first.

public void ExitTransaction()

FindById(string)

Finds any GUI component by its ID path, e.g. "wnd[0]/usr/txtRSYST-BNAME". Returns the raw COM object; prefer the typed overloads below.

public GuiComponent FindById(string id)

Parameters

id string

Returns

GuiComponent

FindByIdDynamic(string)

Finds a component by ID and returns it as dynamic. This allows 1:1 copy-paste of SAP Script Recorder output without any type casting, because every property and method access is resolved at runtime via late binding – exactly like VBScript does it.

Recorder generates:
session.findById("wnd[0]/usr/txtRSYST-BNAME").Text = "user"
session.findById("wnd[0]/tbar[0]/btn[0]").press()

C# equivalent using this method:
session.FindByIdDynamic("wnd[0]/usr/txtRSYST-BNAME").Text = "user";
session.FindByIdDynamic("wnd[0]/tbar[0]/btn[0]").Press();

Note: for typed access with IntelliSense use FindById(string) instead.

public dynamic FindByIdDynamic(string id)

Parameters

id string

Returns

dynamic

FindById<T>(string)

Finds a component and casts it to T.

public T FindById<T>(string id) where T : GuiComponent

Parameters

id string

Returns

T

Type Parameters

T

GetActivePopup(int)

Returns the active modal popup window (GuiMessageWindow), or null if no popup is currently visible. Equivalent to checking wnd[1] / wnd[2] etc.

Handles both SAP GuiMessageWindow (pure message dialogs) and GuiModalWindow (general modal dialogs, e.g. dialog boxes with form fields). Both are returned as a GuiMessageWindow so that callers can use ClickOk(), ClickCancel(), and GetButtons() uniformly.

public GuiMessageWindow? GetActivePopup(int wndIndex = 1)

Parameters

wndIndex int

Returns

GuiMessageWindow

GridView(string)

Returns a GuiGridView by ID.

public GuiGridView GridView(string id)

Parameters

id string

Returns

GuiGridView

HtmlViewer(string)

Returns a GuiHTMLViewer by ID.

public GuiHTMLViewer HtmlViewer(string id)

Parameters

id string

Returns

GuiHTMLViewer

Label(string)

Returns a label by ID.

public GuiLabel Label(string id)

Parameters

id string

Returns

GuiLabel

MainWindow()

Returns the main window.

public GuiMainWindow MainWindow()

Returns

GuiMainWindow

Menu(string)

Returns a menu item by ID, e.g. "wnd[0]/mbar/menu[3]/menu[0]".

public GuiMenu Menu(string id)

Parameters

id string

Returns

GuiMenu

Menubar()

Returns the menu bar.

public GuiMenubar Menubar()

Returns

GuiMenubar

PressBack()

Presses F3 / Back on the main window (VKey 3).

public void PressBack()

PressEnter()

Presses Enter on the main window (VKey 0).

public void PressEnter()

PressExecute()

Presses F8 / Execute on the main window (VKey 8). Equivalent to clicking the Execute button (tbar[1]/btn[8]) on a selection screen or transaction initial screen.

public void PressExecute()

RadioButton(string)

Returns a radio button by ID.

public GuiRadioButton RadioButton(string id)

Parameters

id string

Returns

GuiRadioButton

ScrollContainer(string)

Returns a GuiScrollContainer by ID.

public GuiScrollContainer ScrollContainer(string id)

Parameters

id string

Returns

GuiScrollContainer

SendVKey(int)

Sends a virtual key to the main window.

Common VKey codes:

VKeyAction
0Enter
3F3 — Back (one screen back within the transaction)
4F4 — Input Help / Possible Values
8F8 — Execute (runs the current report or selection screen)
11Ctrl+S — Save
12F12 — Cancel (discards changes and closes the current screen)
15Shift+F3 — Exit (steps back to the previous menu level)
public void SendVKey(int vKey)

Parameters

vKey int

Shell(string)

Returns a GuiShell by ID.

public GuiShell Shell(string id)

Parameters

id string

Returns

GuiShell

StartMonitoring(int)

Starts event monitoring for this session.

COM event sink (preferred): On the first call, the wrapper tries to connect a COM event sink to the underlying SAP COM object via IConnectionPointContainer. If successful, Change, Destroy, AbapRuntimeError, StartRequest, and EndRequest are all driven by the true SAP COM events — including a populated FunctionCode.

Polling fallback: If the COM sink cannot connect (e.g. the SAP version does not expose IConnectionPointContainer), a background thread polls IsBusy every pollMs milliseconds. StartRequest and EndRequest are approximated from IsBusy transitions; FunctionCode is always empty.

Safe to call multiple times — subsequent calls are no-ops.

public void StartMonitoring(int pollMs = 500)

Parameters

pollMs int

Polling interval used only in the fallback path. Default 500 ms.

StartTransaction(string)

Enters a transaction code, same as typing it in the command field and pressing Enter.

When called while already inside a transaction, prefix the code with /n to force SAP to navigate unconditionally, e.g. "/nSE16". A bare code (e.g. "SE16") is only reliable from the SAP Easy Access menu. Use "/o" prefix to open the transaction in a new parallel session.

public void StartTransaction(string tCode)

Parameters

tCode string

Statusbar()

Returns the status bar.

public GuiStatusbar Statusbar()

Returns

GuiStatusbar

StopMonitoring()

Stops the event monitor started by StartMonitoring(int).

public void StopMonitoring()

Tab(string)

Returns a GuiTab by ID.

public GuiTab Tab(string id)

Parameters

id string

Returns

GuiTab

TabStrip(string)

Returns a GuiTabStrip by ID.

public GuiTabStrip TabStrip(string id)

Parameters

id string

Returns

GuiTabStrip

Table(string)

Returns a GuiTable by ID.

public GuiTable Table(string id)

Parameters

id string

Returns

GuiTable

TextField(string)

Returns a text field by ID.

public GuiTextField TextField(string id)

Parameters

id string

Returns

GuiTextField

Toolbar(string)

Returns the application toolbar (tbar[1]) or a toolbar by ID.

public GuiToolbar Toolbar(string id = "wnd[0]/tbar[1]")

Parameters

id string

Returns

GuiToolbar

Tree(string)

Returns a GuiTree by ID.

public GuiTree Tree(string id)

Parameters

id string

Returns

GuiTree

UserArea(string)

Returns the user area (content region) of a window by ID. Defaults to wnd[0]/usr.

public GuiUserArea UserArea(string id = "wnd[0]/usr")

Parameters

id string

Returns

GuiUserArea

WaitForReadyState(int, int, int)

Like WaitReady(int, int) but also verifies that the main window is reachable and that IsBusy stays false for one full settleMs pause before returning. Use this instead of WaitReady(int, int) when screen transitions trigger a brief second busy pulse that WaitReady(int, int) misses.

public void WaitForReadyState(int timeoutMs = 30000, int pollMs = 200, int settleMs = 200)

Parameters

timeoutMs int

Total time budget in ms. Default: 30 000.

pollMs int

Polling interval in ms. Default: 200.

settleMs int

Additional quiet period required before returning. Default: 200.

WaitReady(int, int)

Waits until the session is no longer busy, polling every pollMs milliseconds up to timeoutMs.

public void WaitReady(int timeoutMs = 30000, int pollMs = 200)

Parameters

timeoutMs int
pollMs int

WaitUntilHidden(string, int, int)

Polls until the component with id is no longer accessible (throws on FindById(string)), or until timeoutMs elapses. Useful for waiting out loading spinners or processing dialogs.

public bool WaitUntilHidden(string id, int timeoutMs = 10000, int pollMs = 200)

Parameters

id string

Component ID path to wait for disappearance.

timeoutMs int

How long to poll in ms. Default: 10 000.

pollMs int

Polling interval in ms. Default: 200.

Returns

bool

true if the component disappeared within the timeout.

WithRetry(int, int)

Returns a RetryPolicy that retries SAP operations on SapComponentNotFoundException (slow screen loads) and TimeoutException (session still busy).

Example:

session.WithRetry(maxAttempts: 3, delayMs: 500).Run(() =>
{
    session.WaitReady();
    session.TextField("wnd[0]/usr/txtFoo").Text = value;
});
public RetryPolicy WithRetry(int maxAttempts = 3, int delayMs = 500)

Parameters

maxAttempts int

Maximum number of attempts (≥ 1). Default: 3.

delayMs int

Delay between attempts in ms. Default: 500.

Returns

RetryPolicy

findById(string)

Alias for FindByIdDynamic(string) using the exact camelCase name generated by the SAP Script Recorder. Lets you paste recorder output into C# with only one mechanical change: adding () after argument-less method calls (.press.press()).

Example – recorder VBScript:

session.findById("wnd[0]").maximize
session.findById("wnd[0]/usr/ctxtCATSFIELDS-PERNR").text = "47161"
session.findById("wnd[0]/tbar[1]/btn[5]").press
session.findById("wnd[0]").sendVKey 0

C# equivalent (only parentheses added):

session.findById("wnd[0]").maximize();
session.findById("wnd[0]/usr/ctxtCATSFIELDS-PERNR").text = "47161";
session.findById("wnd[0]/tbar[1]/btn[5]").press();
session.findById("wnd[0]").sendVKey(0);
public dynamic findById(string id)

Parameters

id string

Returns

dynamic

Events

AbapRuntimeError

Fires when an ABAP abend is detected on the status bar (message type A after a round-trip).

Call StartMonitoring(int) to begin receiving events.

public event EventHandler<AbapRuntimeErrorEventArgs>? AbapRuntimeError

Event Type

EventHandler<AbapRuntimeErrorEventArgs>

Change

Fires after every SAP server round-trip completes (IsBusy transitions from true to false). Provides a snapshot of the status bar text and message type.

Call StartMonitoring(int) to begin receiving events.

public event EventHandler<SessionChangeEventArgs>? Change

Event Type

EventHandler<SessionChangeEventArgs>

Destroy

Fires when the session can no longer be accessed (i.e. the user closed the window or the connection was terminated).

Call StartMonitoring(int) to begin receiving events.

public event EventHandler? Destroy

Event Type

EventHandler

EndRequest

Fires at the end of a SAP server round-trip (session transitions from busy to idle), before Change.

When the COM event sink is active FunctionCode is populated. In the polling fallback it is always empty.

Call StartMonitoring(int) to begin receiving events.

public event EventHandler<EndRequestEventArgs>? EndRequest

Event Type

EventHandler<EndRequestEventArgs>

StartRequest

Fires at the beginning of a SAP server round-trip (session transitions from idle to busy).

When the COM event sink is active this event arrives from a true COM source and gives precise timing. In the polling fallback it fires when the background thread first observes IsBusy = true.

Call StartMonitoring(int) to begin receiving events.

public event EventHandler<StartRequestEventArgs>? StartRequest

Event Type

EventHandler<StartRequestEventArgs>