【发布时间】:2018-06-07 02:01:38
【问题描述】:
我正在将 C# 上的 GUI 开发为 Windows 窗体应用程序。我正在使用 TCP/IP 协议从 GUI 服务器(作为 Windows 窗体应用程序)上的客户端(作为控制台应用程序)接收数据流。流模式接收如下:
我在绘图时遇到的麻烦。我在图片框中的图像上绘制两个图形对象。在绘制图形时,第二个显示在绘制时闪烁。 我真的不明白为什么它会在第二个(红色)图形中产生闪烁。 我在这里分享我的服务器代码,请告诉我我错在哪里。
Server Code (GUI):
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Threading;
namespace GUI_Server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread listener;
Int32 port = 3000;
IPAddress ip = IPAddress.Parse("127.0.0.1");
ArrayList nSockets;
String[] PART = null;
String data = null;
private System.Drawing.Graphics g, path;
Double w, x, y, z;
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = new Bitmap("Image");
g = pictureBox1.CreateGraphics();
path = Graphics.FromImage(pictureBox1.Image);
nSockets = new ArrayList();
label1.Text = "IP Address:" + ip;
listener = new Thread(listen);
listener.Start();
}
public void listen()//thread
{
TcpListener tcpListener = new TcpListener(ip, port);
tcpListener.Start();
while (true)
{
Socket handlerSocket = tcpListener.AcceptSocket();
if (handlerSocket.Connected)
{
Control.CheckForIllegalCrossThreadCalls = false;
label2.Text = "Connected";
lock (this)
{
nSockets.Add(handlerSocket);
}
ThreadStart thdstHandler1 = new ThreadStart(handlerThread1);
Thread thdHandler1 = new Thread(thdstHandler1);
thdHandler1.Start();
}
}
}
public void handlerThread1() // thread
{
Socket handlerSocket = (Socket)nSockets[nSockets.Count - 1];
NetworkStream networkStream = new NetworkStream(handlerSocket);
Byte[] bytes = new Byte[1024];
int k;
lock (this)
{
while ((k = networkStream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, k);
PART = data.Split('\t');
if (Convert.ToDouble(part[0]) == 1)
{
w = (Convert.ToDouble(part[1]) / 0.0347) + 60;
x = (Convert.ToDouble(part[2]) / 0.0335) + 656;
textBox1.Text = ("Tag ID_Blue: " + part[0] + "\t" + "X: " + part[2] + "\t" + "Y: " + part[1]);
}
g.DrawRectangle(new Pen(Color.Blue, 3), Convert.ToInt32(x),
Convert.ToInt32(w), 6, 6); // first graphic
if (Convert.ToDouble(part[0]) == 2)
{
y = (Convert.ToDouble(part[1]) / 0.0347) + 60;
z = (Convert.ToDouble(part[2]) / 0.0335) + 656;
textBox2.Text = ("Tag ID_Red: " + part[0] + "\t" + "X: " + part[2] + "\t" + "Y: " + part[1]);
}
g.DrawRectangle(new Pen(Color.Red, 3), Convert.ToInt32(z), Convert.ToInt32(y), 6, 6); // second graphic
Thread.Sleep (50);
pictureBox1.Refresh();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
networkStream.Write(msg, 0, msg.Length);
}
}
handlerSocket = null;
}
有没有办法只刷新图形,而不是整个图片框。是否因为刷新图片框而出现闪烁?
【问题讨论】:
标签: c# multithreading plot picturebox