Souvik Ghosh
Souvik Ghosh

Reputation: 4616

How do I attach current session to SAP GUI in C#

I am trying to automate the SAP GUI. I have used the library SAPFEWSELib with which I am able to launch my the SAP GUI and connect. Now, I am created a desktop shortcut process (using a built in utility in SAP). So instead of launching and connecting every time I can directly go to the specific screen and automate the next steps from there. To achieve this, I would need to-

  1. Trigger the desktop shortcut to launch SAP
  2. Attach the current SAP session and perform the automation in C# using SAPFEWSELib library

I tried- var session = SapGuiApp.ActiveSession; but I get session as null. Is there any other way to attach the SAP session to SapGuiApp?

Note- SapGuiApp is a type of GuiApplication object which is accessible using SAPFEWSELib.

References-

  1. How do I automate SAP GUI with c#
  2. https://scn.sap.com/thread/159742

Upvotes: 1

Views: 3348

Answers (2)

MiBol
MiBol

Reputation: 2125

You can use the following code to achieve that in C#:

SapROTWr.CSapROTWrapper sapROT = new SapROTWr.CSapROTWrapper();
object objSapGui = sapROT.GetROTEntry("SAPGUI");

object objEngine = objSapGui.GetType().InvokeMember("GetScriptingEngine", System.Reflection.BindingFlags.InvokeMethod, null, objSapGui, null);

for (int x = 0; x < (objEngine as GuiApplication).Children.Count; x++)
{
    GuiConnection sapConnection = ((objEngine as GuiApplication).Children.ElementAt(x) as GuiConnection);
    string strDescr = (sapConnection.Description);
}

Upvotes: 1

PankajKushwaha
PankajKushwaha

Reputation: 928

I have done this in VBA, I guess you can do the same in C# with some edits, this function will give you some idea. You will have to create the session from scratch

Function create_session() As Variant
    Set SapGuiAuto = GetObject("SAPGUI")
    Set sapApplication = SapGuiAuto.GetScriptingEngine
    Set Connection = sapApplication.Children(0)
    Set session = Connection.Children(0)
    Set create_session = session
End Function

How to utilize this code snippet

mysession as object
set myesssion =  create_session()
sessionname = myession.id

do not forget to use the session killer

Function kill_session(session as object)
    Set SapGuiAuto = nothing
    Set sapApplication = nothing
    Set Connection = nothing
    Set session = nothing 
End Function

How to use it.

kill_session(mysession)

Upvotes: 0

Related Questions