[英]picture box image does not change in C#
當我的板卡(一個USB模塊)連接到計算機或與計算機斷開連接時,我想更改圖片的盒子圖像。 但是我認為我的線程只會執行一次。 並且圖片框的圖像不會改變。
我的代碼:
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);
}));
}
您可以在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);
}
}
您可能應該添加一個安全開關以脫離循環。 =)
您可以使用下面提到的代碼
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.