Open WinForm from SignalR Client

Viewed 78

i have used this sample [GitHub SignalR Samples] https://github.com/nthdeveloper/SignalRSamples
it use a winforms as a signalR server
it use two clients winforms and a javascript
it append the client message in the textbox

   private void SimpleHub_MessageReceived(string senderClientId, string message)
    {
        //One of the clients sent a message, log it
        this.BeginInvoke(new Action(() =>
        {
            string clientName = _clients.FirstOrDefault(x => x.Id == senderClientId)?.Name;

            writeToLog($"{clientName}:{message}");
        }));
    }

i need to open a form based on message

  private void SimpleHub_MessageReceived(string senderClientId, string message)
    {
        //One of the clients sent a message, log it
        this.BeginInvoke(new Action(() =>
        {
            string clientName = _clients.FirstOrDefault(x => x.Id == senderClientId)?.Name;
            switch (message)
            {
                case "form1":
                    Form1 frm = new Form1();
                    frm.Show();
                    break;
                case "form2":
                   Form2 frm = new Form();
                    frm.Show();
                    break;

                default:
                    // code block
                    break;
            }
          
          
        }));
    }

i have tried that code the form opens and stays loading i can not interact with it what is missing

1 Answers

Because Form.Show does not block causing it to go out of scope immediately.

You need to use Form.ShowDialog. This will block allowing the life cycle of the form to complete before going out of scope.

With that being said, try this:

switch (message)
{
    case "form1":
        using(var frm = new Form1())
        {
            frm.ShowDialog(this);
        }
        break;
    case "form2":
        using(var frm = new Form2())
        {
            frm.ShowDialog(this);
        }
        break;
    default:
        // code block
        break;
}
Related