4

我有一个 WPF 应用程序,我想从另一个应用程序控制它。我想要一些基本功能,例如将焦点设置在特定控件上,获取控件的文本并将文本/键发送到控件。

这可能吗?

4

2 回答 2

5

是的,这是可能的,并且有多种方法可以做到这一点。如果它们都在同一个网络上,您可以在它们之间建立 TCP 连接,都需要 TCPlistener 和 TCP 客户端。

但是,我建议您查看的是WCF。使用 WCF,您将能够做您需要的事情(并且可能更多!),但是要充分熟悉 WCF 库,您需要大量阅读。

您可以从以下内容开始:

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

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

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

对于 WCF 方面,您需要做的事情的大纲是:

A.ServiceHost在每个应用程序(在它们的构造函数中)使用相同的 URI 作为引用打开 a。这将打开一个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。这允许两个应用程序都知道正在传递什么(如果有的话 - 在您的情况下,这将是一个空白,只是一个“提示”,让应用程序知道通过接口执行预先指定的操作)。请注意,我没有展示如何对每个应用程序进行调用,您可以自己解决这个问题......

上面有一些空白你必须填写,但使用我提供的所有内容应该有助于你做你需要的事情。

我希望这有帮助。

于 2013-04-09T11:10:04.593 回答
0

UIAutomation 就是答案。这是一篇关于 CodeProject 的有趣文章。

http://www.codeproject.com/Articles/289028/White-An-UI-Automation-tool-for-windows-applicio

于 2013-04-09T10:55:46.747 回答