You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于.NET与Microsoft库提取并执行XAML中的UI自动化工作流?

.NET平台提取并执行XAML工作流实现UI自动化方案

核心依赖库

使用微软官方的Windows Workflow Foundation (WF) 加载执行XAML工作流,结合Windows UI Automation库实现UI操作逻辑,无需第三方工具。


1. 加载XAML工作流定义

通过ActivityXamlServices.Load()方法直接读取XAML文件并解析为可执行的工作流对象:

using System.Activities;
using System.Activities.XamlIntegration;

// 从本地XAML文件加载工作流
Activity workflow = ActivityXamlServices.Load(@"C:\YourWorkflow.xaml");

2. 执行工作流实例

根据需求选择同步或异步执行方式:

  • 同步执行(适合简单场景):
// 传入工作流所需参数(可选)
var inputParams = new Dictionary<string, object>
{
    {"TargetAppPath", @"C:\Path\To\TargetApp.exe"}
};

// 执行并获取输出结果
var outputParams = WorkflowInvoker.Invoke(workflow, inputParams);
string result = outputParams["OperationResult"]?.ToString();
  • 异步执行(适合需要生命周期管理的复杂场景):
var workflowApp = new WorkflowApplication(workflow, inputParams);

// 绑定工作流生命周期事件
workflowApp.Completed = args =>
{
    var finalResult = args.Outputs["OperationResult"];
    // 处理完成逻辑
};

workflowApp.Aborted = args =>
{
    // 处理异常终止逻辑
};

// 启动工作流
workflowApp.Run();

3. 封装UI自动化自定义活动

将UI操作逻辑封装为WF自定义活动,嵌入XAML工作流中:

using System.Activities;
using System.Windows.Automation;

public class ClickButtonActivity : CodeActivity
{
    // 输入参数:按钮的AutomationId
    public InArgument<string> ButtonAutomationId { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
        string automationId = ButtonAutomationId.Get(context);
        
        // 查找目标按钮元素
        var condition = new PropertyCondition(
            AutomationElement.AutomationIdProperty, 
            automationId
        );
        AutomationElement buttonElement = AutomationElement.RootElement.FindFirst(
            TreeScope.Descendants, 
            condition
        );

        // 执行点击操作
        if (buttonElement != null)
        {
            var invokePattern = buttonElement.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
            invokePattern?.Invoke();
        }
    }
}

4. 关键注意事项

  • 安装必要NuGet包:System.Activities(WF核心)、UIAutomationClient和UIAutomationTypes(UI自动化)。
  • XAML工作流中需正确引用自定义活动的命名空间,例如:
    xmlns:custom="clr-namespace:YourNamespace;assembly=YourAssembly"
    
  • 运行程序需具备足够权限,对目标应用的UI操作可能需要管理员权限。

内容的提问来源于stack exchange,提问作者Shady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:15:54