I successfully managed to connect to an EXISTING instance of SAP GUI with the help of a code example found on Stack Overflow.
However, I am at a loss as to how to disengage from SAP GUI and stop scripting.
After my code has finished, in the SAP GUI window, I can still see the little barbers pole whirling away, indicating that I am still connected to it.
Note: I do not want to kill the session for the user.
My intention here is simply to hook into their current connection, grab some info form their sessions, and then release my involvement with their connection.
And I'd like to do it the 'right' way.. rather than guessing and leaving the user in a mess.
Here's the script I am using to make the connection (SapInfo
and SapInfoItem
are my own structures):
public static Dictionary<string, SapInfoItem> get_sapInfo()
{
Dictionary<string, SapInfoItem> sapInfo = new Dictionary<string, SapInfoItem>();
GuiApplication sapGuiApp;
SapROTWr.CSapROTWrapper sapROTWrapper = new SapROTWr.CSapROTWrapper();
object SapGuilRot = sapROTWrapper.GetROTEntry("SAPGUI");
object engine = SapGuilRot.GetType().InvokeMember("GetSCriptingEngine", System.Reflection.BindingFlags.InvokeMethod,
null, SapGuilRot, null);
sapGuiApp = engine as GuiApplication;
GuiConnection connection = sapGuiApp.Connections.ElementAt(0) as GuiConnection;
foreach (GuiSession child_session in connection.Children)
{
GuiSession session = child_session as GuiSession; //connection.Children.ElementAt(0) as GuiSession;
SapInfoItem sii = new SapInfoItem();
sii.system_name = session.Info.SystemName;
sii.client = session.Info.Client;
sii.client = session.Info.Program;
sii.screen_number = session.Info.ScreenNumber;
sii.handle = session.ActiveWindow.Handle;
sii.transaction = session.Info.Transaction;
sapInfo.Add(sii.handle.ToString("X"), sii);
}
connection.CloseConnection();
return sapInfo;
}
I had the same issue when running a script with Excel vba.
The "little barbers pole" was still running after the end of the script but I noticed that stopping the macro was disconnecting the script from SAP.
In fact it was because I used a public variable to hold the "session" object, so it was still in memory after the end of the script. I solved the issue by destroying the reference to the session object at the end of the script.
So check that you destroy all references to public objects at the end of your code, it could solve your issue.
In vba, the code to do that is
In C#, it should be