c# - WCF,从服务访问 Windows 窗体控件

标签 c# asp.net wcf

我有一个托管在 Windows 窗体中的 WCF 服务。

如何从我的服务中的方法访问表单的控件?

比如我有

public interface IService    {
    [ServiceContract]
    string PrintMessage(string message);
}

public class Service: IService    
{
    public string PrintMessage(string message)
    {
        //How do I access the forms controls from here?
        FormTextBox.Text = message;
    }
}

最佳答案

首先,ServiceContract属性应该在接口(interface)上,而不是PrintMessage()方法上。

使用您的示例的更正版本,您可以这样做。

[ServiceContract]
public interface IService
{
    [OperationContract]
    string PrintMessage(string message);
}
public class Service : IService
{
    public string PrintMessage(string message)
    {
        // Invoke the delegate here.
        try {
            UpdateTextDelegate handler = TextUpdater;
            if (handler != null)
            {
                handler(this, new UpdateTextEventArgs(message));
            }
        } catch {
        }
    }
    public static UpdateTextDelegate TextUpdater { get; set; }
}

public delegate void UpdateTextDelegate(object sender, UpdateTextEventArgs e);

public class UpdateTextEventArgs
{
    public string Text { get; set; }
    public UpdateTextEventArgs(string text)
    {
        Text = text;
    }
}

public class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();

        // Update the delegate of your service here.
        Service.TextUpdater = ShowMessageBox;

        // Create your WCF service here
        ServiceHost myService = new ServiceHost(typeof(IService), uri);
    }
    // The ShowMessageBox() method has to match the signature of
    // the UpdateTextDelegate delegate.
    public void ShowMessageBox(object sender, UpdateTextEventArgs e)
    {
        // Use Invoke() to make sure the UI interaction happens
        // on the UI thread...just in case this delegate is
        // invoked on another thread.
        Invoke((MethodInvoker) delegate {
            MessageBox.Show(e.Text);
        } );
    }
}

这基本上是@Simon Fox 建议的解决方案,即使用委托(delegate)。可以这么说,这有希望只是在骨头上放一些肉。

关于c# - WCF,从服务访问 Windows 窗体控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1366317/

相关文章:

c# - 使 Visual Studio 2012 在一个解决方案中查找并运行 x64 和 x86 单元测试

wcf - 银光 : WCF getting error on server but localhost works fine

c# - 将数据集从 WCF 服务传递到 Silverlight 应用程序

c# - 扩展方法语法与查询语法

c# - 如何在文本框中获取选定的行?

asp.net - 使用asp.net从windows服务器连接到Red hat linux上的oracle 11g

ASP.NET 路由目录请求

c# - Linux 中单声道的 Asp.net : ScriptManager. 找不到 ScriptResourceMapping

c# - 如何从客户端请求中获取 X509Certificate

c# - 在代码优先 Entity Framework 中将外键包含在复合主键中