簡體   English   中英

從另一個應用程序控制WPF應用程序

[英]Control WPF application from another application

我有一個WPF應用程序,我想從另一個應用程序控制它。 我希望具有一些基本功能,例如,將焦點放在特定控件上,獲取控件的文本並將文本/鍵發送給該控件。

這可能嗎?

是的,這是可能的,並且有多種方法可以實現。 如果它們都在同一網絡上,則可以在它們之間建立TCP連接,兩者都需要一個TCPlistener和一個TCP客戶端。

但是,我建議您看的是WCF 使用WCF,您將能夠完成所需的工作(可能還有更多!),但是要充分熟悉WCF庫,還需要大量閱讀。

您可以從以下內容開始:

  1. 兩個.Net應用程序之間的有效通信

  2. 使用WCF在兩個Winform應用程序之間進行通信?

  3. 兩個WPF應用程序之間的通信

對於WCF而言,要做的事情是:

ServiceHost使用相同的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 這使兩個應用程序都知道正在傳遞的內容(如果有的話-在您的情況下將是無效的,只是一個“提示”,讓應用程序知道通過接口執行預先指定的操作)。 請注意,我沒有顯示如何對每個應用程序進行調用,您可以自己解決這個問題。

上面有一些空白,您需要填寫,但是使用我提供的所有內容應該可以幫助您完成所需的工作。

我希望這有幫助。

UIAutomation是答案。 這是有關CodeProject的有趣文章。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM