简体   繁体   中英

Why when I'm using Show method on another form the window form stuck and won't open

Where I'm opening the other form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataDemoLogin
{

public partial class Form2 : Form
{
    Form1 game;

    int portNo = 1500;
    private string ipAddress = "127.0.0.1";
    TcpClient client; //client Socket
    byte[] data; //store the data that send to & from the server
    private string key = "rectangle";

    public Form2()
    {
        InitializeComponent();

        client = new TcpClient();
        client.Connect(ipAddress, portNo);

        data = new byte[client.ReceiveBufferSize];
        // continue reading
        client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(client.ReceiveBufferSize), ReceiveMessage, null);
    }

    private void ReceiveMessage(IAsyncResult ar)
    {
        try
        {
            int bytesRead;

            // read the data from the server
            bytesRead = client.GetStream().EndRead(ar);

            if ((bytesRead >= 1))
            {
                // invoke the delegate to display the recived data
                string incomingData = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
                incomingData = decrypt(incomingData);

                if (incomingData == "loginok" || incomingData == "loginnotok" || incomingData == "registok" || incomingData == "regist not ok")
                {
                    MessageBox.Show(incomingData);

                    if (incomingData == "loginok")
                    {
                        game = new Form1();
                        game.Show();
                        SendMessage("look");
                    }
                }

                /*if (incomingData == "waiting" || incomingData == "connecting")
                {
                    game.recievePrivateMessagaes(incomingData);
                }*/
            }

            // continue reading
            client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(client.ReceiveBufferSize), ReceiveMessage, null);
        }

        catch (Exception ex)
        {
            // ignore the error... fired when the user loggs off
        }
    } // end ReceiveMessage

    /// <summary>
    /// convert the message to ASCII code send message to the server
    /// </summary>
    /// <param name="message">the data to send</param>
    private void SendMessage(string message)
    {
        try
        {
            if (message.StartsWith("%%%%login%%%"))
            {
                message = "%%%%login%%%" + encrypt(message.Remove(0, 12) , key);
            }

            else if (message.StartsWith("%%%regist%%%"))
            {
                message = "%%%regist%%%" + encrypt(message.Remove(0, 12), key);
            }

            else
            {
                message = encrypt(message, key);
            }

            // send message to the server
            NetworkStream ns = client.GetStream();
            byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

            // send the text
            ns.Write(data, 0, data.Length);
            //ns.Flush();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    } //end SendMessage

    private void registbtn_Click(object sender, EventArgs e)
    {
        string username = txbusername.Text;
        string password = txbpassword.Text;
        string fname = txbfname.Text;
        string lname = txblname.Text;
        string email = txbemail.Text;
        string city = txbcity.Text; 

        //1 //sql statement
        SendMessage("%%%regist%%%" + username + "9" + password + "9" + fname + "9" + lname + "9" + email + "9" + city);
    }

    private void loginbtn_Click(object sender, EventArgs e)
    {
        string username = txbuserlogin.Text;
        string password = txbpasslogin.Text;

        //1 //sql statement
        SendMessage("%%%%login%%%" + username + "9" + password);
    }

The form I'm trying to open:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataDemoLogin
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private int Speed = 5;
        private string facing = "right";
        private int coinsCollected = 0;

        private void Keyisdown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Left)
            {
                timer2.Enabled = true;
                facing = "left";
                player.Image = Properties.Resources.left;
            }

            if (e.KeyCode == Keys.Right)
            {
                timer2.Enabled = true;
                facing = "right";
                player.Image = Properties.Resources.right;
            }

            if (e.KeyCode == Keys.Down)
            {
                timer2.Enabled = true;
                facing = "down";
                player.Image = Properties.Resources.down;
            }

            if (e.KeyCode == Keys.Up)
            {
                timer2.Enabled = true;
                facing = "up";
                player.Image = Properties.Resources.up;
            }

            if (e.KeyCode == Keys.Left)
            {
                timer2.Enabled = true;
                facing = "left";
            }

            if (e.KeyCode == Keys.Right)
            {
                timer2.Enabled = true;
                facing = "right";
            }

            if (e.KeyCode == Keys.Down)
            {
                timer2.Enabled = true;
                facing = "down";
            }

            if (e.KeyCode == Keys.Up)
            {
                timer2.Enabled = true;
                facing = "up";
            }
        }

    private void gameEngine(object sender, EventArgs e)
    {
        if (facing == "right")
        {
            player.Left += Speed;
        }

        if (facing == "left")
        {
            player.Left -= Speed;
        }

        if (facing == "up")
        {
            player.Top -= Speed;
        }

        if (facing == "down")
        {
            player.Top += Speed;
        }

        if (player.Left < -10)
        {
            player.Left = 590;
        }

        if (player.Left > 600)
        {
            player.Left = 10;
        }

        if (player.Top < -10)
        {
            player.Top = 400;
        }

        if (player.Top > 410)
        {
            player.Top = 10;
        }

        foreach (Control x in this.Controls)
        {
            if ((string)x.Tag == "wall")
            {
                if (player.Bounds.IntersectsWith(x.Bounds))
                {
                    gameOverPlayer("wall");
                }
            }
            else if ((string)x.Tag == "coin")
            {
                if (player.Bounds.IntersectsWith(x.Bounds) && x.Visible)
                {
                    coinsCollected++;
                    x.Visible = false;
                }
            }
        }

        if (coinsCollected == 102)
        {
            gameOverPlayer("coins");
        }
    }

    private void gameOverPlayer(string message)
    {
        timer2.Stop();
    }

    /*public void recievePrivateMessagaes(string message)
    {
        if (message == "waiting" || message == "connected")
        {
            MessageBox.Show(message);
        }
    }*/
}
}

When the form opens, it gets stuck and it shows this:

what the form shows

The previous form still working but the other form doesn't working when I'm using the method ShowDialog(), the form open but the previous form stop working.

I'm not getting any errors or something, the only thing is when I minimize the form, I can't reopen it.

You cannot open a Form (or anything that derives from Control ) on the non-GUI thread.

This is the thread that has correct COM behavior and message pumping as you'll see by the attribute and way the main form is launched in Main by default.

This is not a bug.

You can marshal over to the UI thread using either Invoke (which is blocking) or BeginInvoke (non blocking).

If you want to check if you're on the GUI thread use InvokeRequired . It will return true at the point you're currently trying to show the form, indicating you need to marshal over.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM