WCF, access to Windows form elements from a service

I have a WCF service hosted inside a windows form.

How can I access form controls from my service methods?

for example me

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;
    }
}
+5
source share
5 answers

First of all, the ServiceContract attribute must be on the interface, and not on the PrintMessage () method.

Using the revised version of your example, you can do it this way.

[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);
        } );
    }
}

This is essentially a solution proposed by @Simon Fox, i.e. use delegate. Hopefully this just puts some meat on the bones, so to speak.

+5
source

- . - , WCF:

public interface IFormService
{
    string Text { get; set; }
}

IFormService, , .

IFormService:

public class Service : IService
{
    private readonly IFormService form;

    public Service(IFormService form)
    {
        this.form = form
    }

    public string PrintMessage(string message)
    {
        this.form.Text = message;
    }
}

, ServiceHostFactory, Service IFormService.

+3

. , , , , .

, , . WPF Dispatcher.BeginInvoke, , , WinForms.

+1

, .

. , , , .

:

  • , . , .
  • , . .
  • .
0

.

, invoke.

Invoke(new MethodInvoker(delegate{FormTextBox.Text = message;});
0

All Articles