且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用c#在Windows窗体中显示控制台应用程序数据

更新时间:2023-02-13 09:02:15

1)使用1个Button,ListBox和a创建你的WinForm应用程序Backgroundworker

2)添加Button_click-Event,BackgroundWorker1DoWork-Event,BackgroundWorker1RunWorkerCompleted-Event和BackgroundWorker1ProgressChanged-Event



3)添加此代码:

1) create your your WinForm - application with 1 Button, a ListBox and a Backgroundworker
2) Add the Button_click-Event, the BackgroundWorker1DoWork-Event, the BackgroundWorker1RunWorkerCompleted-Event and the BackgroundWorker1ProgressChanged-Event

3) add this code:
void Button1Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}
void BackgroundWorker1DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    int Port = 8088;
    TcpListener server = new TcpListener(IPAddress.Any, Port);
    server.Start();
    byte[] bytes = new byte[1024];
    string data;
    //Console.Write("Waiting for Client connection ");
    backgroundWorker1.ReportProgress(25);

    TcpClient client = server.AcceptTcpClient();
    //Console.WriteLine("\n Client Connected");
    backgroundWorker1.ReportProgress(50);
    NetworkStream stream = client.GetStream();
    int i;
    i = stream.Read(bytes, 0, bytes.Length);
    data = Encoding.UTF8.GetString(bytes, 0, i);
    data = data.Substring(2, data.Length - 2);

    client.Close();server.Close();
    e.Result=data;
}
void BackgroundWorker1RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    listBox1.Items.Add(String.Format("Data Received: {0}", (string)e.Result));
}
void BackgroundWorker1ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    switch (e.ProgressPercentage) {
        case 25:
            listBox1.Items.Add("Waiting for Client connection ");
            break;
        case 50:
            listBox1.Items.Add("Client Connected");
            break;
    }
}