How can a self-hosted (WinForm ) WCF service interact with the main form?

前端 未结 3 467
借酒劲吻你
借酒劲吻你 2020-12-10 09:33

Simplified version of what I\'m trying to achieve:

  • I have a WinForms app that runs hidden (Visible = false) in the background.
  • It\'s got only one Form
3条回答
  •  借酒劲吻你
    2020-12-10 10:01

    Using this method you have completely a thread-safe application, and you don't have any limitation.

    Service Contract Definition

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        void DisplayAlert();
    }
    

    Service Implementation

    public class Service:IService
    {
        public void DisplayAlert()
        {
            var form = Form1.CurrentInstance;
            form.MySynchronizationContext.Send(_ => form.Show(), null);
        }
    }
    

    Program.cs

    [STAThread]
    static void Main()
    {        
        var host = new ServiceHost(typeof (Service));
        host.Open();
    
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Application.Run(new Form1());
     }
    

    Form Implementation

    public partial class Form1 : Form
    {
        public static Form1 CurrentInstance;
        public SynchronizationContext MySynchronizationContext;
        private bool showForm = false;
    
        public Form1()
        {
            InitializeComponent();
            MySynchronizationContext = SynchronizationContext.Current;
            CurrentInstance = this;
        }
    
        // use this method for hiding and showing if you want this form invisible on start-up
        protected override void SetVisibleCore(bool value)
        {
            base.SetVisibleCore(showForm ? value : showForm);
        }
    
        public void Show()
        {
            showForm = true;
            Visible = true;   
        }
    
        public void Hide()
        {
            showForm = true;
            Visible = true;
        }
    }
    

    Client

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press Enter to show form");
            Console.ReadLine();
    
            var client = new ServiceClient();
            client.DisplayAlert();
        }
    }
    

提交回复
热议问题