如何使用 c# 自动化 SAP GUI

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13130176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:41:09  来源:igfitidea点击:

How do I automate SAP GUI with c#

c#sap

提问by Luke101

I would like to automate an SAP GUI window using the C# language. I am able to do it in VBScript but code reuse is horrible. Besides Id like to use threading instead of having 80 or more processes running. Where can I find any documentation and samples of how to do this? Here is the code I am working with. Basically, the problem I am facing is - how do I make a connection to SAP GUI then create an SAP GUI on the fly then start making transactions and entering text in some fields.

我想使用 C# 语言自动化 SAP GUI 窗口。我可以在 VBScript 中做到这一点,但代码重用很糟糕。除了我喜欢使用线程而不是运行 80 个或更多进程。我在哪里可以找到有关如何执行此操作的任何文档和示例?这是我正在使用的代码。基本上,我面临的问题是 - 如何连接到 SAP GUI,然后动态创建 SAP GUI,然后开始进行交易并在某些字段中输入文本。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using White.Core.Factory;
using White.Core.UIItems.Finders;
using White.Core.InputDevices;
using System.Threading;
using System.Diagnostics;
using SAP.Connector;
using SAP;


namespace SAP_Automation
{
    class Program
    {
        public static void Main(string[] args)
        {
            string ExeSourceFile = @"C:\Program Files\SAP\SapSetup\setup\SAL\SapLogon.s8l";
            White.Core.Application _application;
            White.Core.UIItems.WindowItems.Window _mainWindow;

            var c = SAP.Connector.Connection.GetConnection("**");
            var c = new SAPConnection("ASHOST=*; GWHOST=*; GWSERV=*; ASHOST=*; SYSNR=00;USER=user; PASSWD=**;");
            c.Open();


            }
        }
    }
}

As you can see I can create a connection but I dont know how to create a session to the GUI and start entering text in fields. Any examples and samples would be appreciated.

如您所见,我可以创建连接,但我不知道如何创建到 GUI 的会话并开始在字段中输入文本。任何示例和示例将不胜感激。

采纳答案by tyh

This might be necro-threading but I was in a similar situation where I work. We needed SAP GUI Automation for testing purposes that could integrate with the rest of our homegrown automation platform written in C#. I helped create a proposal for one solution that took advantage of a SAP provided library for GUI automation that could be used as the basis for an automation layer for SAP.

这可能是 necro-threading 但我在我工作的情况下处于类似的情况。我们需要 SAP GUI 自动化用于测试目的,它可以与我们用 C# 编写的其他本土自动化平台集成。我帮助创建了一个解决方案的提案,该解决方案利用 SAP 提供的 GUI 自动化库,可用作 SAP 自动化层的基础。

Does the following file exist on your SAP file installation? x:\Program Files\SAP\FrontEnd\SAPGui\sapfewse.ocx?

您的 SAP 文件安装中是否存在以下文件?x:\Program Files\SAP\FrontEnd\SAPGui\sapfewse.ocx?

If so, add it to Visual Studio (or whatever IDE you're using) as a reference. It is basically a class library which contains a bunch of SAP specific objects that will allow you to interact with. It is very effective because it exposes most of what you need from the SAP GUI. We discovered in other attempts that a lot of the objects in SAP were not available.

如果是这样,请将其添加到 Visual Studio(或您使用的任何 IDE)作为参考。它基本上是一个类库,其中包含一堆允许您与之交互的 SAP 特定对象。它非常有效,因为它从 SAP GUI 中公开了您需要的大部分内容。我们在其他尝试中发现 SAP 中的许多对象不可用。

This is an early proof of concept I did. Start SAP with a connection string, enter credentials, navigate to a transaction code.

这是我所做的概念的早期证明。使用连接字符串启动 SAP,输入凭据,导航到事务代码。

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using SAPFEWSELib;

namespace SAPGuiAutomated
{
//created a class for the SAP app, connection, and session objects as well as for common methods. 
    public class SAPActive
    {
        public static GuiApplication SapGuiApp { get; set; }
        public static GuiConnection SapConnection { get; set; }
        public static GuiSession SapSession { get; set; }

        public static void openSap(string env)
        {
            SAPActive.SapGuiApp = new GuiApplication();

            string connectString = null;
            if (env.ToUpper().Equals("DEFAULT"))
            {
                connectString = "1.0 Test ERP (DEFAULT)";
            }
            else
            {
                connectString = env;
            }
            SAPActive.SapConnection = SAPActive.SapGuiApp.OpenConnection(connectString, Sync: true); //creates connection
            SAPActive.SapSession = (GuiSession)SAPActive.SapConnection.Sessions.Item(0); //creates the Gui session off the connection you made
        }

        public void login(string myclient, string mylogin, string mypass, string mylang)
        {
            GuiTextField client  = (GuiTextField)SAPActive.SapSession.ActiveWindow.FindByName("RSYST-MANDT", "GuiTextField");
            GuiTextField login  = (GuiTextField)SAPActive.SapSession.ActiveWindow.FindByName("RSYST-BNAME", "GuiTextField");
            GuiTextField pass  = (GuiTextField)SAPActive.SapSession.ActiveWindow.FindByName("RSYST-BCODE", "GuiPasswordField");
            GuiTextField language  = (GuiTextField)SAPActive.SapSession.ActiveWindow.FindByName("RSYST-LANGU", "GuiTextField");

            client.SetFocus();
            client.text = myclient;
            login.SetFocus();
            login.Text = mylogin;
            pass.SetFocus();
            pass.Text = mypass;
            language.SetFocus();
            language.Text = mylang; 

            //Press the green checkmark button which is about the same as the enter key 
            GuiButton btn = (GuiButton)SapSession.FindById("/app/con[0]/ses[0]/wnd[0]/tbar[0]/btn[0]");
            btn.SetFocus(); 
            btn.Press();

        }
    }
    //--------------------------//
    //main method somewhere else 
    public static void Main(string[] args)
    {
        SAPActive.openSAP("my connection string");
        SAPActive.login("10", "jdoe", "password", "EN");
        SAPActive.SapSession.StartTransaction("VA03");
    }

You're right there is not a lot of documentation on this subject. Below are a few sources that helped me get started

你说得对,关于这个主题的文档并不多。以下是一些帮助我入门的资源

-Original source of our plan http://scn.sap.com/thread/1729689

-我们计划的原始来源 http://scn.sap.com/thread/1729689

-Documentation on the API (For VB and javascript but the general rules and objects are identical). Definitely read the portion on the SAP GUI Runtime hierarchy. It'll answer a lot of questions. http://www.synactive.com/download/sap%20gui%20scripting/sap%20gui%20scripting%20api.pdf

- API 文档(对于 VB 和 javascript,但一般规则和对象是相同的)。一定要阅读 SAP GUI 运行时层次结构上的部分。它会回答很多问题。 http://www.synactive.com/download/sap%20gui%20scripting/sap%20gui%20scripting%20api.pdf

回答by Hans Passant

It is very important here to understand what UI Automation can do and what its limitations are. It was designed to automate a user interface's capabilities. You can click buttons, enter text in a textbox, move windows, etcetera, whatever a user can do using the mouse and keyboard.

在这里了解 UI 自动化可以做什么以及它的局限性是非常重要的。它旨在自动化用户界面的功能。您可以单击按钮、在文本框中输入文本、移动窗口等,用户可以使用鼠标和键盘执行任何操作。

What it can notdo is bridge the tall wall that the operating system puts up between processes. A wall that prevents a process from accessing the memory of another process. This is a very important security and safety feature. It for one prevents a process from accessing data that should be private to a process. Like a password. And for another it stops a crashing process from affecting other processes that run on the machine. You can kill a process with Task Manager and everything keeps motoring along happily as though nothing happened.

什么能不能做的是弥合高壁操作系统搭设过程之间。防止一个进程访问另一个进程的内存的墙。这是一项非常重要的安全保障功能。一方面,它可以防止进程访问应该是进程私有的数据。就像密码一样。另一方面,它阻止崩溃的进程影响机器上运行的其他进程。您可以使用任务管理器终止一个进程,一切都在愉快地进行,就好像什么都没发生一样。

A consequence of this is that creating a SAPConnection object in your program is a connection that only your program can use. There is no mechanism to somehow pass this object to another process with UI Automation. At best you could use the data you retrieve from the connection to affect what buttons you click.

这样做的结果是在您的程序中创建 SAPConnection 对象是一个只有您的程序可以使用的连接。没有机制可以通过 UI 自动化以某种方式将此对象传递给另一个进程。您最多可以使用从连接中检索到的数据来影响您单击的按钮。

The kind of process interop that would allow sharing data between processes is well supported in .NET. Low-level approaches are socket and named pipes, high-level are Remoting and WCF. Older programs have COM Automation support, Office is a good example of that. That however requires two to tango, both programs must be written to take advantage of it.

.NET 很好地支持允许在进程之间共享数据的那种进程互操作。低级方法是套接字和命名管道,高级方法是远程处理和 WCF。较旧的程序具有 COM 自动化支持,Office 就是一个很好的例子。然而,这需要两个人来探戈,必须编写两个程序才能利用它。

So if you are trying to automate an existing SAP application and this app does not otherwise explicitly support automation, the kind that an Office program supports, then you are pretty much stuck with just filling text boxes and clicking buttons.

因此,如果您正在尝试自动化现有的 SAP 应用程序,而该应用程序不明确支持自动化(Office 程序支持的那种),那么您几乎只能填充文本框和单击按钮。

回答by mbadit

You can automate any kind of application (browser, desktop, java, etc) with UiPath. Here's a tutorial on how to automate data entry, menu navigation and screen scraping on SAP.

您可以使用UiPath自动化任何类型的应用程序(浏览器、桌面、java 等)。这是有关如何在 SAP 上自动化数据输入、菜单导航和屏幕抓取教程。

You can

你可以

  • use it from code (SDK). It has a tool that auto-generates C# code
  • create and run workflows (visual automation) directly from UiPath Studio.
  • 从代码(SDK)中使用它。它有一个自动生成 C# 代码的工具
  • 直接从UiPath Studio创建和运行工作流(视觉自动化)。

Here's a sample of the C# auto-generated code:

下面是 C# 自动生成的代码示例:

        // Attach window  menu
        UiNode wnd3 = UiFactory.Instance.NewUiNode().FromSelector("<wnd app='sap business one.exe' cls='&#35;32768' idx='1' />");            
        // Click 'Business Pa...' menu
        UiNode uiClickBusinessPamenu_3 = wnd3.FindFirst(UiFindScope.UI_FIND_DESCENDANTS, "<ctrl name='Business Partners' role='popup menu' /><ctrl automationid='2561' />");
        uiClickBusinessPamenu_3.Click(88, 9, UiClickType.UI_CLICK_SINGLE, UiMouseButton.UI_BTN_LEFT, UiInputMethod.UI_HARDWARE_EVENTS);            
        // Attach window 'SAP Business' 
        UiNode wnd4 = UiFactory.Instance.NewUiNode().FromSelector("<wnd app='sap business one.exe' cls='TMFrameClass' title='SAP Business One 9.0 - OEC Computers' />");            
        // Click 'Add' button
        UiNode uiClickAddbutton_4 = wnd4.FindFirst(UiFindScope.UI_FIND_DESCENDANTS, "<wnd cls='ToolbarWindow32' title='View' /><ctrl name='View' role='tool bar' /><ctrl name='Add' role='push button' />");
        uiClickAddbutton_4.Click(13, 24, UiClickType.UI_CLICK_SINGLE, UiMouseButton.UI_BTN_LEFT, UiInputMethod.UI_HARDWARE_EVENTS);

Here's how workflow automation of SAP Business One menus, buttons or typing looks like:

SAP Business One 菜单、按钮或输入的工作流自动化如下所示:

enter image description here

在此处输入图片说明

And finally the SDK documentation is located here... in case you don't want to use workflows.

最后,SDK 文档位于此处...以防您不想使用工作流。

Note:I work at UiPath. You should also try other automation tools like Automation Anywhere, WinAutomation, Jacada, Selenium, Ranorex use them side by side and choose the one that suits better your needs.

注意:我在 UiPath 工作。您还应该尝试其他自动化工具,例如 Automation Anywhere、WinAutomation、Jacada、Selenium、Ranorex,将它们并排使用,然后选择更适合您需求的工具。