I have a windows application written in VS 2005. The application makes queries against to s开发者_运维知识库ql database in a timer cycle every 2 minutes. If there any data changes, the window will be refreshed with new data.
If the user leaves the window, the windows will be automatically locked after a while. There is no sense to keep querying data in ever 2 minutes when the windows is locked; therefore I would like to stop the query when lock is on so that the network data trafic will be reduced and also saves the current windows resources such as memory and CPUs.
I am not sure if there is any way to find out the current windows is locked? Not sure if there is any Windows APIs for this purpose if no .Net classes available?
My project is in .Net 2.0 and all users are in Windows XP.
You don't actually want to query whether windows is locked, instead what you want to query is whether your application is visible - there's no point refreshing your data if the window is minimized or covered by another window either, right?
The standard way to go about this is via a timer and invalidating the window. Use the Timer class to schedule a timer 2 minutes into the future. When the timer fires invalidate your window via Form.Invalidate().
When you invalidate the window, Windows will send it a "paint" message. In the OnPaint
handler, you update the screen with your data. But here's the kicker: if your window is not visible, Windows will not fire the OnPaint
event (that includes if the screen is currently locked)!
Now, your database query is probably a bit too expensive to execute in a OnPaint
event handler, so you might have to do something tricky in your timer handler. For example, you might do the database query in your timer handler and then call Form.Invalidate()
. This means when you come back from locking the screen, your data might be out-of-date so you could have a check to see whether DateTime.Now
is significantly different between the timer handler and the OnPaint
handler and schedule another timer straight away if it is. Otherwise, schedule the timer to run again in 2 minutes from your OnPaint
callback.
I hope all that makes sense :)
精彩评论