[英]picture box image does not change in C#
I want to change picture's box image when my board(a USB module) is joined or disjoined to computer. 当我的板卡(一个USB模块)连接到计算机或与计算机断开连接时,我想更改图片的盒子图像。 But I think my thread will execute just one time. 但是我认为我的线程只会执行一次。 And picture box's image won't change. 并且图片框的图像不会改变。
my code: 我的代码:
bool boardjoined = false;
void BoardConnecion()
{
foreach (var item in SerialPort.GetPortNames())
{
if (item == "COM3")
{
boardjoined = true;
DisplayImage(_pic_usb, "on.png");
}
else
{
boardjoined = false;
DisplayImage(_pic_usb, "off.png");
}
}
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_pic_usb.Image = Bitmap.FromFile(Application.StartupPath + @"\off.png");
new Thread(new ThreadStart(BoardConnecion)).Start();
}
private void DisplayImage(PictureBox pic, string picName)
{
pic.Invoke(new EventHandler(delegate
{
pic.Image = Bitmap.FromFile(Application.StartupPath +@"\" + picName);
}));
}
You can do a never ending loop in the BoardConnection. 您可以在BoardConnection中进行永无止境的循环。
void BoardConnecion()
{
while(true)
{
foreach (var item in SerialPort.GetPortNames())
{
if (item == "COM3")
{
boardjoined = true;
DisplayImage(_pic_usb, "on.png");
}
else
{
boardjoined = false;
DisplayImage(_pic_usb, "off.png");
}
}
Thread.Sleep(500);
}
}
You should proabably add a safety switch to get out of the loop to. 您可能应该添加一个安全开关以脱离循环。 =) =)
you can use below mentioned code 您可以使用下面提到的代码
private System.Timers.Timer timerClock = new System.Timers.Timer();
timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
timerClock.Interval = 1000;
timerClock.Enabled = true;
public void OnTimer( Object source, ElapsedEventArgs e )
{
foreach (var item in SerialPort.GetPortNames())
{
if (item == "COM3")
{
boardjoined = true;
DisplayImage(_pic_usb, "on.png");
}
else
{
boardjoined = false;
DisplayImage(_pic_usb, "off.png");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.