简体   繁体   中英

Visual C# Drawing graphics based on data via. USB

I am trying to draw graphics on a form application based on data from an externally connected USB device to my PC. my goal is to continuously uploading the data from USB device and updating the graphics like every 20ms.

First, I made the below two codes and put them in button_click function. Each time the button is clicked, they work fine.

uploadData(); // this uploads 2KB data from USB device connected to my PC

drawGraphics(); // this draws graphics on a picture box

So as next step, I put them in while infinite loop like below. But drawing does not work while data uploading from the USB device keeps running. I was probing the USB device hardware and I confirmed it keeps sending new data to my PC.

while(true)
{
   uploadData(); 

   drawGraphics(); 
}

I put Thread.Sleep() between the above codes and put various delay values to see if the problem is solved, but no success.

Interesting thing is that each time when I move mouse's cursor over the form, the drawing starts a bit but stops at early point.

This could be related to very simple mistake. I am kind of new to Visual C# so just hit this wall and not able to overcome it.

Usually the way to handle an occasional-update requirement in a GUI app is to use a timer. The timer runs on a background thread and notifies the main thread occasionally that a "tick" has occurred. This way, other operations like processing mouse and keyboard input, drawing to the screen, etc. can continue. I'm not entirely sure why your solution isn't working, but I'm 99% sure you can fix it by replacing the while loop with a System.Windows.Forms.Timer that ticks on the desired interval.

So, I recommend: adding a Windows Forms Timer to your form via the Visual Studio designer, setting its Interval property to the desired number of milliseconds, registering an event handler for the timer tick, moving the uploadData() call to that event handler, and moving the content of the drawGraphics() method to the PictureBox 's Paint event.

Instead of having an infinite loop, create a timer control. Set the Interval to 20 (thats 20 ms). In the OnTick create an Method that:

1) Send the Enabled property of your timer to 'False' 2) Calls your upLoadData and drawGraphics methods 3) Sets the Enabled property of your timer to 'True'

This way you won't simultaneously try to access the data on the USB more than once at a time if for some reason the 1st occurence takes a little longer than expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM