我有一个 WPF 应用程序,我想从另一个应用程序控制它。我想要一些基本功能,例如将焦点设置在特定控件上、获取控件的文本以及将文本/键发送到控件。
这可能吗?
最佳答案
是的,这是可能的,并且有多种方法可以做到这一点。如果它们都在同一个网络上,您可以在它们之间建立 TCP 连接,两者都需要一个 TCPlistener 和一个 TCP 客户端。
不过,我建议您看一下 WCF .使用 WCF,您将能够做您需要的事情(并且可能做更多!),但是需要大量阅读才能充分熟悉 WCF 库。
您可以从查看以下内容开始:
对于 WCF 方面的事情,您需要做的大纲是:
一个。使用相同的 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.在相关 channel 上创建一个监听器。这可以在两个应用程序中完成,以允许双向通信。
例子:
/// <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.创建和在两个应用程序中使用并在适当的类中继承的接口(interface)。一些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
继承的某个类。这允许两个应用程序都知道正在传递什么(如果有的话 - 在您的情况下它将是无效的,只是一个“提示”让应用程序知道通过界面做一些预先指定的事情)。请注意,我没有显示如何调用每个应用程序,您可以自己解决...
上面有一些您必须填写的空白,但是使用我提供的所有内容应该可以帮助您完成所需的操作。
希望对您有所帮助。
关于c# - 从另一个应用程序控制 WPF 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899840/