从另一个应用程序控制WPF应用程序

4
我有一个WPF应用程序,希望从另一个应用程序中控制它。我想要一些基本功能,例如将焦点设置在特定的控件上,获取控件的文本以及向控件发送文本/按键。
这是否可行?

1
这是可能的吗?你尝试过什么吗? - Soner Gönül
请先尝试自己解决问题,然后再在 Stack Overflow 上提问。 - Prahalad Gaggar
2个回答

5
是的,这是可能的,有各种方法可用于实现。如果它们都在同一个网络上,您可以在它们之间建立TCP连接,两者都需要一个TCPlistener和一个TCP client。

然而,我建议您看一下WCF。使用WCF,您将能够做到您所需的(可能还有更多!),但需要大量阅读以充分熟悉WCF库。

您可以从以下内容开始查看:

  1. 两个 .Net 应用程序之间的高效通信

  2. 使用 WCF 在两个 winform 应用程序之间进行通信?

  3. 两个 WPF 应用程序之间的通信

对于WCF方面,您需要完成以下步骤:

A. 在每个应用程序的构造函数中使用相同的URI打开一个ServiceHost作为参考。这将打开一个NetNamedPipeBinding,您可以在其中两个应用程序之间进行通信。

例如:

public static ServiceHost OpenServiceHost<T, U>(T instance, string address) 
{
    ServiceHost host = new ServiceHost(instance, new Uri[] { new Uri(address) });
    ServiceBehaviorAttribute behaviour = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
    behaviour.InstanceContextMode = InstanceContextMode.Single;
    host.AddServiceEndpoint(typeof(U), new NetNamedPipeBinding(), serviceEnd);
    host.Open();
    return host;
}

B. 在相关频道上创建监听器。这可以在两个应用程序中都完成,以实现双向通信。

例如:

/// <summary>
/// Method to create a listner on the subscribed channel.
/// </summary>
/// <typeparam name="T">The type of data to be passed.</typeparam>
/// <param name="address">The base address to use for the WCF connection. 
/// An example being 'net.pipe://localhost' which will be appended by a service 
/// end keyword 'net.pipe://localhost/ServiceEnd'.</param>
public static T AddListnerToServiceHost<T>(string address)
{
    ChannelFactory<T> pipeFactory = 
        new ChannelFactory<T>(new NetNamedPipeBinding(), 
                                     new EndpointAddress(String.Format("{0}/{1}",
                                                                                  address, 
                                                                                  serviceEnd)));
    T pipeProxy = pipeFactory.CreateChannel();
    return pipeProxy;
}

C. 创建一个接口,并用于两个应用程序中并在相应的类中进行继承。例如:IMyInterface

您可以设置一个库,该库可用于两个应用程序,以允许一个一致的代码库。这样的库将包含上述两种方法(及更多内容),并且将在两个应用程序中使用,如下所示:

// Setup the WCF pipeline.
public static IMyInterface pipeProxy { get; protected set;}
ServiceHost host = UserCostServiceLibrary.Wcf
    .OpenServiceHost<UserCostTsqlPipe, IMyInterface>(
        myClassInheritingFromIMyInterface, "net.pipe://localhost/YourAppName");
pipeProxy = UserCostServiceLibrary.Wcf.AddListnerToServiceHost<IMyInterface>("net.pipe://localhost/YourOtherAppName");

在这里,pipeProxy 是从 IMyInterface 继承的某个类。这允许两个应用程序知道正在传递什么(如果有的话——在您的情况下,它将是一个 void,只是一个“提示”,让应用程序通过接口预先指定做某些事情)。请注意,我没有展示如何对每个应用程序进行调用,您可以自己解决这个问题...

上面有一些空白需要填写,但使用我提供的所有内容应该可以帮助您完成所需的工作。

希望这可以帮到您。


0

感谢大家的回答。我已经尝试了Microsoft UI Automation和White Framework,两者都完美地运行了。谢谢。 - Yagneshwara Lanka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接