简体   繁体   中英

How to visualize the data from c# console app in windows form?

I'm getting data from UDP port and there is no problem to show it in console. I've got a problem trying to send this data to Windows Form and use it there. Here is my code:

using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApp2 {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine();
            Thread t = new Thread(FormDrawing);
            t.Start(UDPListener());
        }

        // Listening Port
        static byte[] UDPListener() {
            Console.WriteLine("Waiting for client");
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 162);
            EndPoint ep = (EndPoint)ipep;
            socket.Bind(ep);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            byte[] indata = new byte[1024];
            IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
            EndPoint inep = (EndPoint)peer;
            int inlen = socket.ReceiveFrom(indata, ref inep);
            socket.Close();
            Console.WriteLine(indata.ToString());
            return indata;
        }

        // Drawing Form
        static void FormDrawing(object ob) {
            byte[] obj = (byte[])ob;
            Form mainForm = new Form();
            if (obj != null) {
                Button MS2 = new Button {
                    Location = new Point(0, 0),
                    Size = new Size(80, 80),
                    Text = obj.ToString(),
                    BackColor = Color.Green
                };
                mainForm.Controls.Add(MS2);
            }
            mainForm.Show();
            Thread.Sleep(5000);
        }
    }
}

Window opens with some kind of button. So, obj is not null. But this button is white. Form closes after 5 seconds. What can be the problem?

Remember till when your application is alive? Unless there is at least 1 foreground thread in your application.

When you start application, main thread enters Main() method. It get bytes from the socket and starts a new thread passing these bytes as an argument. And then your main thread exits, but as you created your foreground thread application still works. New thread creates form and shows it, but it does not initialize message dispatching loop, that's why your form is not rendered completely and behaves as a handing application - it just does not process any messages from the user (mouse over, clicks, dragging etc). Meantime, you freeze a thread for 5 seconds and then it exits, your application is closed.

So no problem here, there is no magic, everything is deterministic and works exactly as you programmed it:)

Try use Application.Run(mainForm); or mainForm.ShowDialog() instead of mainForm.Show() . These methods will start application messaging loop and you'll see form opened till you close it. Read more about application messaging loop here .

Another note is that you don't set an apartment in your UI thread. Read here more what the hack is that. Please call t.SetApartmentState(ApartmentState.STA); before you call Start() . Another option is to mark your Main() with STAThreadAttribute and run your form as I described above in your Main() method.

The easiest way would probably be to make sure you have the latest dotnet core version installed, then do dotnet new winforms from the command line and use that project as your starting point.

That'll give you a main method like this:

[STAThread]
static void Main()
{
    Application.SetHighDpiMode(HighDpiMode.SystemAware);
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

As sander has said above, your code appears to be doing as you'd expect ie opening, sleeping for 5 seconds and ending. I imagine you've seen the same behaviour in a basic console app and got around it by using Console.ReadLine() ... the same applies here in a sense.

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