如何在C#中的面板上填充绘制的矩形? [英] How do I fill a drawn rectangle on a panel in C#?

查看:117
本文介绍了如何在C#中的面板上填充绘制的矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器 - 客户端应用程序,但我现在的任务是在点击它时填充矩形的正方形。我该怎么做?

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?

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));

        }
      }
}





这是我服务器的照片 - 客户申请: http://s9.postimg.org/3q3ff8ilb/tscr.jpg [ ^ ]



很抱歉长代码,但我发布了所有内容以查看所有内容。

请帮帮我!

非常感谢!



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!

推荐答案

);
serverStream.Write(outStream, 0 ,outStream.Length);
serverStream.Flush();
}

私有 void button2_Click( object sender,EventArgs e) // 连接到服务器
{
readData = Conected to Chat Server ...;
msg();
clientSocket.Connect( 127.0.0.1 8888 );
serverStream = clientSocket.GetStream( );

byte [] outStream = System.Text.Encoding.ASCII.GetBytes(textB ox3.Text + Environment.NewLine);
// byte [] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.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();

线程ctThread = 线程(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;
}

私有 void panel2_Paint( object sender,PaintEventArgs e)
{
Pen blackpen = new Pen(Color.Black, 1 );
SolidBrush sBlack = new SolidBrush(Color.Black);
Font font = new 字体( Arial 10 );
Graphics g = e.Graphics;



for int i = < span class =code-digit> 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 - < span class =code-digit> 18 );
g.DrawString( +( char )(i + ' A'),font,sBlack,pfLocation);
}

g.Dispose();

}

private void panel2_MouseClick(< span class =code-keyword> object sender,MouseEventArgs e)
{

textBox2.Text =( char )(' A' + Math.Abs​​((eX-xStart)/ this .lungCasuta))+ + Math。 Abs(1+(eY - yStart)/ this .lungCasuta);

DrawRectangle(xStart,yStart,(Math.Abs​​((eX - xStart)/ this .lungCasuta)),(Math.Abs​​( 1 +(eY - 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 +(eY-yStart)/ this .lungCasuta));



button1.PerformClick();
}


私有 void DrawRectangle(< span class =code-keyword> int XStart, int YStart, int XFinal, int YFinal)
{
System.Drawing.SolidBrush myBrush = new 系统。 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();
}
私有 void btnDraw_Click( object sender,EventArgs e)
{
// DrawRectangle(300,200, 30,30);
DrawRectangle(xStart,yStart,Convert.ToInt16(txtX.Text),Convert.ToInt16(txtY.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)); } } }





这是我服务器的照片 - 客户申请: http://s9.postimg.org/3q3ff8ilb/tscr.jpg [ ^ ]



很抱歉长代码,但我发布了所有内容以查看所有内容。

请帮帮我!

非常感谢!



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!


你的问题没有填充以前用线条绘制的东西。我可以看到,你知道如何使用 FillRectangle 。你的问题不同了。我可以看到你在点击或其他一些事件上绘制的代码片段。问题是:你以这种方式绘制的内容不支持事件处理程序中的渲染 Paint ,或者,在重写方法<$中具有几乎相同的效果的OnPaint 。下一次失效将扩大 Paint 之外的所有绘图,如果您只是将窗口的一部分移动到屏幕之外然后再移动,则会发生此无效。



要使渲染成为永久渲染,您需要使用 Paint OnPaint 。当您通过处理任何输入事件,动画或任何其他原因更改图形中的内容时,您需要更改渲染中使用的某些数据模型,然后使所有控件或其部分区域无效。您也可以立即通过鼠标进行绘制,但是您需要更新数据的方式与 Paint 上的渲染不相矛盾。



我在过去的答案中解释了它是如何工作的:

什么样的俏皮方法是Paint? (DataGridViewImageCell.Paint(...)) [ ^ ],

在面板上捕获绘图 [ ^ ],

mdi子表单之间的绘制线 [ ^ ],

如何加快我的vb.net应用程序? [ ^ ],

用C#.net鼠标滚轮缩放图像 [ ^ ]。



现在,关于你提出问题的方式。 首先,感谢您提供长代码。即使它比问题真正需要的时间长,至少它会显示您正在做的事情,这与大部分代码示例不同。其他询问者。这是非常好的。与此同时,如果你认为它让我们看到一切,你就错了。你怎么认为我知道 panel2_MouseClick 是鼠标点击的处理程序?只有通过猜测。这只是方法名称。它因为处理程序,只有当你使用+ =运算符将它作为处理程序添加到某个事件实例的调用列表时。我们为什么不看?因为你没有写它,设计师为你做了并自动生成了你没有显示的代码。这是使用设计师的另一个问题:提问时不好。 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
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


这篇关于如何在C#中的面板上填充绘制的矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆