Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a server-client application, but my task now is to fill a square of a rectangle when I click it. How can I do this?
C#
using System;
using System.Windows.Forms;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.ComponentModel;
using System.Linq;

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
//using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {

        int xStart = 20, yStart = 20;
        
        int lungCasuta = 20;
        int nrCasute = 10;
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream = default(NetworkStream);
        string readData = null;

        public Form1()
        {
            InitializeComponent();
        
        }

        /*DRAW method---------------------*/

       private delegate void LetsDraw();
        private Graphics m_FormGraphs;
        private const int m_iSquare = 8;
        private int iCol = 0, iRow = 0, iX = 30, iY = 80;
        private const int m_iWidth = 50, m_iHeight = 50;
      //  private Holder[,] holders = new Holder[10, 10];

        private void Draw()
        {
            string[] abc = new string[20] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };

            // string abc1 = "abcdefghij";
            string[,] sCoordinates = new string[20, 20];
            //    string[] s = new string[10];
            for (int i = 0; i <= 19; i++)
            {
                //populate the array
                if (i == 20)
                {
                    iCol = 0;
                    iRow += 1;
                }
                sCoordinates[iRow, iCol] = abc[i];
                // s[iCol] = abc1.Substring(1);
                //abc = abc.Remove(0, 1);
                iCol += 1;
            }
            float fLocal = (float)60;
            float fX = (float)iX;
            float fY = (float)iY;
            Font font = new Font("Arial", 10);
            SolidBrush sBlack = new SolidBrush(Color.Black);
            Point pLocation = new Point(iX, iY);
            PointF pfLocation = new PointF(fX, fY);
            Pen pen = new Pen(new SolidBrush(Color.Black), 3);
            //Setting the row and column to origin
            iRow = 0;
            iCol = 0;
            pfLocation.X += 25;
            pfLocation.Y = fLocal;

            for (int iCount = 0; iCount < 10; iCount++)
            {
                //put numbers
                m_FormGraphs.DrawString("" + (iCount + 1), font, sBlack, pfLocation);
                pfLocation.X += 50;
            }
            pfLocation = new PointF(10, fY + 10);
            for (int iCount = 0; iCount < 10; iCount++)
            {
                //put letters
                m_FormGraphs.DrawString("" + (char)(iCount + 'A'), font, sBlack, pfLocation);
                pfLocation.Y += 50;
            }
        }

        /*DRAW method------------------------END*/

        private void button1_Click(object sender, EventArgs e)//send the message
        {
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + Environment.NewLine);
          //  byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }

        private void button2_Click(object sender, EventArgs e)//connect to server
        {
            readData = "Conected to Chat Server ...";
            msg();
            clientSocket.Connect("127.0.0.1", 8888);
            serverStream = clientSocket.GetStream();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + Environment.NewLine);
           // byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            Thread ctThread = new Thread(getMessage);
            ctThread.Start();
        }

        private void getMessage()
        {
            while (true)
            {
                     string bytesFrom = "";
                     string dataClient = null;



                NetworkStream networkStream = clientSocket.GetStream();
                StreamReader reader = new StreamReader(networkStream);
                serverStream = clientSocket.GetStream();
                int buffSize = 1024;
                // string inStream = "";
               byte[] inStream = new byte[10025];

                if (serverStream.CanRead)
                {
                  //  inStream = reader.ReadLine();
                  //  buffSize = clientSocket.ReceiveBufferSize;
                    serverStream.Read(inStream, 0, buffSize);
                   
                 //   dataClient = inStream;
                  string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                    readData = "" + returndata;
                    msg();
                }
            }
        }

        private void msg()
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(msg));
            else
                textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + readData;
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {
            Pen blackpen = new Pen(Color.Black, 1);
            SolidBrush sBlack = new SolidBrush(Color.Black);
            Font font = new Font("Arial", 10);
            Graphics g = e.Graphics;
            
            
            
            for (int i = 0; i <= 10; i++)
            {
                g.DrawLine(blackpen, xStart, yStart + i * lungCasuta, xStart + nrCasute * lungCasuta, yStart + i * lungCasuta);
                g.DrawLine(blackpen, xStart + i * lungCasuta, yStart, xStart + i * lungCasuta, yStart + nrCasute * lungCasuta);
                
            }
            for (int i = 0; i < 10; i++)
            {
                PointF pfLocation = new PointF(xStart - 18, yStart + lungCasuta / 4 + i * lungCasuta);
                g.DrawString("" + (i + 1), font, sBlack, pfLocation);
                pfLocation = new PointF(xStart + lungCasuta / 4 + i * lungCasuta, yStart - 18);
                g.DrawString("" + (char)(i + 'A'), font, sBlack, pfLocation);
            }

            g.Dispose();

        }

        private void panel2_MouseClick(object sender, MouseEventArgs e)
        {

            textBox2.Text = (char)('A'+Math.Abs((e.X - xStart) / this.lungCasuta) )+ "," + Math.Abs(1+(e.Y - yStart) / this.lungCasuta);

            DrawRectangle(xStart, yStart, (Math.Abs((e.X - xStart) / this.lungCasuta)), (Math.Abs(1 + (e.Y - yStart) / this.lungCasuta)));
            txtXStart.Text =Convert.ToString(xStart);
            txtYStart.Text = Convert.ToString(yStart);

            txtX.Text = Convert.ToString(Math.Abs((e.X - xStart) / this.lungCasuta));
            txtY.Text = Convert.ToString(Math.Abs(1 + (e.Y - yStart) / this.lungCasuta));



            button1.PerformClick();
        }

     
        private void DrawRectangle(int XStart, int YStart, int XFinal, int YFinal)
        {
            System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
            System.Drawing.Graphics formGraphics = this.CreateGraphics();
            formGraphics.FillRectangle(myBrush, new Rectangle(XStart, YStart, XFinal, YFinal));
            myBrush.Dispose();
            formGraphics.Dispose();
        }
       private void btnDraw_Click(object sender, EventArgs e)
        {
            //DrawRectangle(300,200,30,30);
            DrawRectangle(xStart, yStart, Convert.ToInt16(txtX.Text), Convert.ToInt16(txtY.Text));

        }
      }
}


Here is a photo with my server-client application: http://s9.postimg.org/3q3ff8ilb/tscr.jpg[^]

Sorry for the long code, but I posted it all to see everything.
Please help me out!
Many thanks!
Posted
Updated 6-Jun-15 21:04pm
v5
Comments
[no name] 5-Jun-15 16:09pm    
Instead of asking "how do I", you should be telling us what happens with your code when you run it. Not everyone has access to a compiler and a debugger 24/7 to find out what you can easily tell us.
DrgIonuţ 6-Jun-15 2:52am    
Ok. On a panel I drawn rectangle with 10 line and 10 columns. When I click on one square of it I want that the square to be colored.
[no name] 6-Jun-15 8:20am    
Ask yourself. If you read this, does that clearly describe what happens on your screen that no one else can see?
DrgIonuţ 6-Jun-15 8:29am    
Sorry. I don't get your point.
[no name] 6-Jun-15 8:31am    
You cannot understand that we cannot see your computer screen to know what happens when you run your code?

Your problem is not filling something which was previously drawn with the lines. As I can see, you know how to use FillRectangle. Your problem is different. I can see the fragments of code where you do drawing on click or some other events. The problem is: what you draw this way is not backed with the rendering in the handler of the event Paint, or, with nearly the same effect, in the overridden method OnPaint. Next invalidation will wide all the drawing outside Paint, and this invalidation can happen if you simply move part of the window outside of the screen and then move again.

To make rendering permanent, you need to use Paint or OnPaint. When you change something in graphics by handling any input events, for animation, or any other reason, you need to change some data model used in your rendering, and then invalidate all the control or part of its area. You can also draw by, say, mouse, immediately, but you need to update the data the way not contradicting the rendering on Paint.

I explained how it works in my past answers:
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[^],
capture the drawing on a panel[^],
Drawing Lines between mdi child forms[^],
How to speed up my vb.net application?[^],
Zoom image in C# .net mouse wheel[^].

Now, about the way you ask your question. First of all, thank you for the "long code". Even if it is longer than it is really needed for the question, at least it shows what you are doing, unlike majority of the code samples of other inquirer. This is very good. At the same time, if you think it enables us to "see everything", you are wrong. How do you think I know that panel2_MouseClick is a handler of a mouse click? Only by guessing. This is nothing but the method name. It because a handler only if you add it as a handler to the invocation list of some event instance using += operator. Why don't we see it? Because you did not write it, the designer did it for you and auto-generated the code you did not show. This is yet another problem of the use of the designer: it is bad for asking question. If you really want to produce shortest possible but comprehensive self-contained code sample, use the anonymous methods, like in MyControl.Click += () => {/* ... */}. Or provide full code without the designer with named methods, but show all '+=', as well as all declarations and set-ups.

And, by the way, never use auto-generated names like panel2_MouseClick; they violate (good) Microsoft naming conventions and kill maintenance of the project. Always rename all auto-generated names to something semantically expressive. For such purposes, you are given the refactoring engine.

—SA
 
Share this answer
 
v2
Comments
DrgIonuţ 6-Jun-15 3:01am    
Thanks for advice. I know that I implemented the FillRectangle method, but it has the effect on the form when I press the btnDraw. What I want to do is that when I click on one square of the rectangle which is on the panel the square to be colored. I hope you understood me. Regards, Ionut!
Sergey Alexandrovich Kryukov 6-Jun-15 5:59am    
This could be by the reason I described. I need to do the hit test, change some data and call one of the Invalidate methods, the data will be re-rendered it in OnPaint. Didn't I explain how it all works?
Will you accept the answer formally?
—SA
DrgIonuţ 6-Jun-15 6:05am    
I think if you want to test it, you need and the server's code, because without it you can't test anything. So, should I give it to you?
Ralf Meier 7-Jun-15 14:56pm    
@Sergey:
When I see the posted code I don't believe that the Thread-Starter knows what you tried to explain him. My oppinion is that the TS tries to solve the problem by working around the normal functions of .Net.
Your advice which points to "OnPaint" and/or Invalidate normally must be enough.

@Dragomir:
What Sergey tried to explain you was how .Net works.
For those things you want to do there is the method "OnPaint" which must be overwritten by you. This method also gives you directly a graphics-object for the painting itself.
What you have to do is to do the nescessary drawing-commands by the information which is build up at a seperate place (for example variables inside your class / properties and so on).
I would prefer the following way :
You build an array of boolean which represents your grid.
When you click inside one of grid-places you set this array-element to true and send an 'Invalidate'. Now the 'OnPaint'-Method has to do the work with the Animation ...

I hope my explaining helps a bit ...
DrgIonuţ 7-Jun-15 17:48pm    
Thanks for your reply, Ralf. Well I tried to understand what you said, but I'm new in C# and I don't know how to exactly do this. Do you have an example of what you explained to me? Many thanks in advance! Regards, Ionut!
This sample-code will show you what I have described :
Writing your Custom Control: step by step[^]
 
Share this answer
 
Comments
DrgIonuţ 8-Jun-15 10:59am    
Many thanks for this example. I will try as soon as possible it to see if instead of buttons I could use a rectangle. If any problem occurs I'll let you know. Hope to don't bother you. Regards, Ionut!
Ralf Meier 8-Jun-15 15:34pm    
You are welcome ... and you may contact me as you want ...
Perhaps you also find better samples ... ;)

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900