简体   繁体   中英

Can I query for user interaction events within a while loop, in a form application?

In my windows form application I have a while loop that is continuously polling a joystick device for values and continuously updating the GUI with those values and then refreshing the GUI. However as long as I am in the while loop the UI is unresponsive to any interaction.

Is there a way to query for any GUI events or interactions like button clicks or key presses while in my while loop?

I would like to be able to exit the loop if certain events or interactions where to occur. I at the least want the close and minimise buttons to work.

Because I only need to poll the joystick and update the GUI 20 times a sec, then the majority of the loop time is just sleep time. But I want to be waiting for events and interactions during this time.

Are you using a game controller? If so, how do you obtain input from it?

With normal Windows input (mouse and keyboard), you would get your overridden OnXxx method invoked (or the corresponding event invoked).

Obviously the usual way to perform blocking or long-running operations without stalling the UI is to run the operation in a separate thread. However, it really depends on how you obtain input from the device.

I have solved this problem much more simply than I expected. Basically it seems a while loop in a GUI application is a bad idea. Trying to update the GUI from a separate thread with a while loop won't work or is just bad programming practice.

Instead of using a while loop to continuously call a function for an indefinite amount of time, I instead use a timer that triggers a function that polls the joystick every 50ms. This means the rest of the time the GUI is free to update its self. I don't need to force it to refresh or query for any user interaction. Because the functions only run very briefly the GUI has plenty of time to breath and no interactions or events will be missed.

To sum it up timer driven function calls can be useful alternative to a while loop and can save you from a multithreading nightmare in a GUI application.

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