我正在尝试编写一个 C# 程序,该程序将使用 SAP 的脚本 API 自动将用户输入到 SAP GUI(当前版本为 7400.3.11.3364)中。我过去使用 VBA 做过类似的事情,但我正在努力让它在 C# 中完全按照我想要的方式工作。我的最终目标是有一个方法可以打开 SAP(如果它尚未运行),返回 SAP 的 GuiApplication 对象,并在我的程序结束后让 SAP 保持打开状态。我目前在 VBA 中使用它,我相信当我们使用 SAP GUI 版本 7.3 时,我在之前的项目中使用 C# 可以正常工作,但我不是 100% 确定
这是我使用的VBA函数:
Public Function GetSapApp() as GuiApplication
Dim Start as Date
If GetObject("SAPGUI") Is Nothing Then
Start = Now()
Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe"
Do Until Not GetObject("SAPGUI") Is Nothing Or Now > (Start + TimeValue("00:01:00"))
DoEvents
Loop
If GetObject("SAPGUI") Is Nothing Then
MsgBox "Unable to detect SAP Scripting API. Please contact the developer."
End If
Set GetSapApp = GetObject("SAPGUI").GetScriptingEngine
End Function
这里是我在谷歌搜索时发现的不同 C# 方法:
下面是我目前正在使用的(这个想法是受此启发:https://www.codeproject.com/Questions/829500/How-do-I-connect-Csharp-to-SAP-GUI) , 但它有几个问题。如果它已经打开,它似乎不会检测到 SAP。此外,在我的程序运行后,我们的任何 VBA 宏都无法检测到此 SAP。
private static GuiApplication GetSapApp()
{
try
{
object SapGuilRot = new CSapROTWrapper().GetROTEntry("SAPGUI");
return SapGuilRot.GetType().InvokeMember("GetScriptingEngine", System.Reflection.BindingFlags.InvokeMethod, null, SapGuilRot, null) as GuiApplication;
}
catch (Exception e)
{
try
{
string SapPath = "C:\\Program Files (x86)\\SAP\\FrontEnd\\SAPgui\\saplogon.exe";
if (File.Exists(SapPath))
{
System.Diagnostics.Process.Start(SapPath);
DateTime StartTime = DateTime.Now;
object SapGuilRot = new CSapROTWrapper().GetROTEntry("SAPGUI");
while (SapGuilRot == null && 30 >= (DateTime.Now - StartTime).TotalSeconds)
{
SapGuilRot = new CSapROTWrapper().GetROTEntry("SAPGUI");
}
return SapGuilRot.GetType().InvokeMember("GetScriptingEngine", System.Reflection.BindingFlags.InvokeMethod, null, SapGuilRot, null) as GuiApplication;
}
else
{
return null;
}
}
catch
{
return null;
}
}
}
这是我尝试过的另一个选项(根据另一个 SO 帖子的这个答案:https://stackoverflow.com/a/14205520/5134861),但它有与上面相同的第一个问题(未检测到如果 SAP 当前正在运行),当您调用
OpenConnection
方法时打开的 SAP 会话看起来不同,然后在我的程序运行完成后关闭。
private static GuiApplication GetSapApp()
{
return (GuiApplication)System.Activator.CreateInstance(Type.GetTypeFromProgID("SapGui.ScriptingCtrl.1"));
}
这是我尝试过的最后一个选项,但我得到一个
Cannot create ActiveX component
错误,尽管已经注册了sapfewse.ocx。
private static GuiApplication GetSapApp()
{
object sap = Microsoft.VisualBasic.Interaction.GetObject("SAPGUI", "");
return sap.GetType().InvokeMember("GetScriptingEngine", System.Reflection.BindingFlags.InvokeMethod, null, sap, null) as GuiApplication;
}
任何帮助和/或建议将不胜感激。
提前致谢!
我用过:
Microsoft.VisualBasic.Interaction.GetObject("SAPGUISERVER", "");
SapROTWr.CSapROTWrapper sapROTWrapper1 = new SapROTWr.CSapROTWrapper();
object SapGuilRot1 = sapROTWrapper1.GetROTEntry("SAPGUI");
object engine1 = SapGuilRot1.GetType().InvokeMember("GetScriptingEngine", System.Reflection.BindingFlags.InvokeMethod, null, SapGuilRot1, null);