Click here to Skip to main content
14,330,121 members
Rate this:
Please Sign up or sign in to vote.
I write this code to send screenshot to multiple connected clients.Works fine on clients end, but freezes the UI of application on server side.I don't understand what cause that problem.

public void LoopClients()

            while (_isRunning)

                TcpClient newClient = Server.AcceptTcpClient();

                Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
        public void HandleClient(object obj)
            TcpClient client = (TcpClient)obj;

            BinaryFormatter binaryformatter = new BinaryFormatter();
            while (client.Connected)

                MainStream = client.GetStream();
                binaryformatter.Serialize(MainStream, GrabDesktop());

        private static Image GrabDesktop()
            System.Drawing.Rectangle bound = Screen.PrimaryScreen.Bounds;
            Bitmap screenshot = new Bitmap(bound.Width, bound.Height, PixelFormat.Format32bppArgb);
            Graphics graphics = Graphics.FromImage(screenshot);
            graphics.CopyFromScreen(bound.X, bound.Y, 0, 0, bound.Size, CopyPixelOperation.SourceCopy);
            return screenshot;

I call the loopClient() function in timer and than timer in button to run the program.
Any suggestion to improve the code or fix t resolve the problem would be great help.

What I have tried:

I have searched many solution but noting is quit helping in any ways.
Updated 15-Aug-18 0:39am
F-ES Sitecore 15-Aug-18 6:13am
If it's freezing the UI then run the code in its own thread using BackgroundWorker or the Thread class or some other way to do this. Google "winforms run code on new thread" and I'm sure you'll find lots of examples.
Member 13714031 15-Aug-18 6:32am
I create a new thread to run in the loopclient() function. Now application works fine.Thanks for help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100