Win32 getmessage loop stops executing when App window looses focus..! i want to run a infinite loop in my application without stopping - win32gui

Win32 getmessage() loop stops executing when App window looses focus..! i want to run a infinite loop in my application without stopping...
The program works flawless when the mouse pointer moves on the window,as it raises a event and the getmessage processes,but when the application window looses its focus or the mouse is not over it,it STOPS!...
i have a function which needs to be called continuously even when the win32 app is minimized or lost focus...
i am calling the function like this...
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
showFrame();
}
i know,only when any event is raised the getmessage processes it and in turn the showFrame() function is called,but i want to call the function continuously...
please give me a clue how can i achieve it or do i need to use threading??

GetMessage() blocks until there is a message available to retrieve. If you don't want to wait, then use PeekMessage() instead:
MSG msg;
do
{
...
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
...
}
...
}
while (...);
You can also use either GetQueueStatus() or MsgWaitForMultipleObjects() to detect when there are messages available before then retrieving them, eg:
MSG msg;
do
{
...
if (GetQueueStatus(QS_ALLINPUT))
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
...
}
}
...
}
while (...);
MSG msg;
do
{
...
if (MsgWaitForMultipleObjects(0, NULL, FALSE, 0, QS_ALLINPUT) == WAIT_OBJECT_0)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
...
}
}
...
}
while (...);
Alternatively, you can use SetTimer() to post periodic WM_TIMER messages to the queue, and then your loop can show the frames each time it receives that message.
Alternatively, use a standard GetMessage() loop, and have a separate thread drive your frame logic. Whenever it needs to show a new frame, it can post a user-defined message to the main thread queue so your loop can show the frame.

Related

Start and stop a QThread with a loop

In a QT app, I want to start a loop inside a qthread that reads 2 different sounds (it's a metronome).
I have a function with my process. I want to start it when I click on a button and stop it with another one.
The problem is, when I start it, my app doesn't respond, I can't click on the stop button. I have to stop the app.
#include <QSound>
#include <QEventLoop>
ClickThread::ClickThread(): highClickFile("://high_click.wav"), lowClickFile("://low_click.wav"), isRunning(false)
{
this->highClick = new QSound(highClickFile);
this->lowClick = new QSound(lowClickFile);
this->setPeriod(120);
}
void ClickThread::run()
{ QTimer *timer = new QTimer();
timer ->moveToThread(this);
timer->connect(timer, SIGNAL(timeout()),this, SLOT(process()));
timer ->start();
exec();
}
void ClickThread::process(){
highClick->play();
QThread::msleep(period);
highClick->stop();
lowClick->play();
QThread::msleep(period);
lowClick->stop();
lowClick->play();
QThread::msleep(period);
lowClick->stop();
lowClick->play();
QThread::msleep(period);
lowClick->stop();
}
void ClickThread::setIsRunning(bool set)
{
this->isRunning=set;
}
void ClickThread::setPeriod(unsigned long bpm)
{
this->period = 60000/bpm;
}
Thx for your answers
Stop using QTimer.
The QTimer you have currently is default to a timeout interval of 0. That is going to stuff up the event queue with infinite calls to process(), which will cause serious problems.
You should use this while loop instead:
stopPlaying = false;
while(stopPlaying == false)
{
process();
}
The boolean stopPlaying variable should be declared in your "ClickThread" class definition and used by your stop button to cause the thread to drop out of the loop, terminating the thread.

Android: ASyncTask's behavior contrary to documentation

First time writing an AsyncTask and I seem to have a subtle design flaw that prevents both ProgressDialog, ProgressBar, and even Log.d() from working properly. I suspect that somehow I am not actually creating a new thread/task.
Short: the symptoms
A ProgressDialog is created in the constructor, and the code orders Android to show it in onPreExecute(), but the dialog never shows.
onProgressUpdate() is supposed to execute whenever I call publishProgress() from within doInBackground(), correct? Well, it doesn't. Instead, it executes when doInBackground() completes.
Long: investigations
Things I have verified through the emulator and, when possible, on a phone:
onPreExecute() is definitely called
the progress bar is not reset until after doInBackground() completes
update_dialog.show() is definitely executed, but the dialog does not appear unless I remove the .dismiss() in onPostExecute(); I imagine dialog is, like the progress bar, not shown until after doInBackground() completes, but is naturally immediately dismissed
the code will happily show dialogs when no computation is involved
doInBackground() definitely invokes publishProgress()
when it does, onProgressUpdate() does not execute immediately! that is, I have a breakpoint in the function, and the debugger does not stop there until after doInBackground() completes! (perhaps this is a phenomenon of the debugger, rather than doInBackground(), but I observe the same symptoms on a mobile device)
the progress bar gets updated... only after doInBackground() completes everything
similarly, the Log.d() data shows up in Android Monitor only after doInBackground() completes everything
and of course the dialog does not show up either in the emulator or on a device (unless I remove .dismiss() from onPostExecute())
Can anyone help find the problem? Ideally I'd like a working dialog, but as Android has deprecated that anyway I'd be fine with a working progress bar.
Code
Here are the essentials, less the details of computation &c.:
Where I call the AsyncTask from the main thread:
if (searching) { // this block does get executed!
Compute_Task my_task = new Compute_Task(overall_context, count);
my_task.execute(field, count, max_x, max_y);
try { result = my_task.get(); } catch (Exception e) { }
}
The AsyncTask itself:
private class Compute_Task extends AsyncTask<Object, Integer, Integer> {
public Compute_Task(Context context, int count) {
super();
current_positions = 0;
update_dialog = new ProgressDialog(context);
update_dialog.setIndeterminate(true);
update_dialog.setCancelable(false);
update_dialog.setTitle("Thinking");
update_dialog.setMessage("Please wait");
}
protected void onPreExecute() {
super.onPreExecute();
update_dialog.show();
ProgressBar pb = ((ProgressBar) ((Activity) overall_context).findViewById(R.id.progress_bar));
pb.setMax(base_count);
pb.setProgress(0);
}
protected void onPostExecute() {
super.onPostExecute();
update_dialog.dismiss();
}
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
ProgressBar pb = ((ProgressBar) ((Activity) overall_context).findViewById(R.id.progress_bar));
pb.setMax(base_count);
pb.incrementProgressBy(1);
Log.d(tag, values[0].toString());
}
protected Integer doInBackground(Object... params) {
Integer result = compute_scores(
(boolean[][]) params[0], (Integer) params[1], (Integer) params[2], (Integer) params[3], 0)
);
return result;
}
public int compute_scores(boolean[][] field, int count, int max_x, int max_y, int level) {
int result, completed = 0;
switch(count) {
// LOTS of computation goes on here,
// including a recursive call where all params are modified
if (level == 0)
publishProgress(++completed);
}
}
ProgressDialog update_dialog;
}
Turns out this is basically the same issue as the one given here. The "fatal" line is this one:
try { result = my_task.get(); } catch (Exception e) { }
Apparently this puts the UI thread into deep sleep. One should not use get() with an AsyncTask unless one is willing to suspend the UI thread. We have to perform a little magic in onPostExecute() instead.
Although it turns out that this was a duplicate, I didn't find it until after I wrote it, because I didn't realize the thread was blocking.

Checking data passed from Arduino into Processing

As part of a project my group has to program an Arduino to get a signal from an RFID, and pass data into Processing depending on said signal. For example, when a tag is sensed by the Arduino, String data would be passed into Processing and handled there.
We have the Arduino part working but Processing is throwing up errors. In our project we must wait for user input at certain points.
public int readRFID()
{
int tagNumber = 0;
//Has to be contained in try/catch because of errors with null
try
{
if ( myPort.available() > 0) { // If data is available,
val = myPort.readStringUntil('\n');
} // read it and store it in val
//Convert val into integer and set to tagNumber
tagNumber = Integer.parseInt(val);
}
//An error occurs if val is null, which is the case every time unless it actually gets data
catch(Exception e)
{
tagNumber = 0;
}
return tagNumber;
}
At the end, tagNumber should be returned as either 0 or a positive value (when a tag is present and there is a number to be read in). In the method that calls this method we have this:
//RFID SCANNING GOES HERE
int tag = 0;
while (tag == 0)
{
//When RFID reads as null, this method should return 0 until a tag
//is read in
tag = readRFID();
}
//userChoice is set to the number read in -1 because tags are numbered 1, 2, 3, 4
//but userChoice will refer to an index in an array that starts at 0
userChoice = tag - 1;
We are not sure why this code isn't working - all we're sure of is that the method has to be continuously called until a tag is present. Any suggestions would be greatly appreciated.

How to Break an Infinite Loop using QPushButton?

I have an infinite loop, inside the loop I want to insert a state whenever I click a button, it will break the current loop.
I've tried several ways like:
if(ui->btnStop->isDown())
{
break;
}
if(ui->btnStop->isChecked())
{
break;
}
and
if(cv::waitKey(10)>=0)
{
break;
}
But, it doesn't work.
I wonder why cv::waitKey doesn't work in Qt, but in a non-Qt project it will work flawlessly.
Are there any other way to break an infinite loop with a QPushButton?
Any help would be appreciated.
It doesn't work because the event processor cannot run whilst execution is locked in your loop. The easiest solution is to simply call QApplication::processEvents() in each loop, this will force the event processor to run.
// Add a boolean to your class, and a slot to set it.
MyClass
{
...
private slots:
void killLoop() { killLoopFlag_ = true; }
private:
bool killLoopFlag_;
}
// In the constructor, connect the button to the slot.
connect( ui->btnStop, SIGNAL( clicked() ),
this, SLOT( killLoop ) );
// Then when performing the loop, force events to be processed and then
// check the flag state.
killLoopFlag_ = false;
while ( true ) {
// ...Do some stuff.
QApplication::processEvents();
if ( killLoopFlag_ ) {
break;
}
}
However you need to ask yourself: Should I be doing long running calculations inside the GUI thread? The answer is usually no.

Flex text change event

I'm tracking how fast does the text of a textArea change. If it changes faster than 500 ms then i don't want to do anything, but if it doesn't change in 500 ms, i want to call a method.
I tried like this:
public function textchangeListener(e : Event):void
{
if(((new Date).getTime() - changeTime)>500)
{
prepareText();
}
changeTime = (new Date).getTime();
}
This method is the event handler for text change.
But the problem is, if it changes only under 500 ms and after that it doesn't change, then my method won't be called. I make this for a better performance, so the prepareText() is called only when the user stops typing for 500 ms.
How about this...
Once you get the first text change event you can call a procedure like textTimeOut(). It will essentially work like this.
function textTimeOut():void
{
start a timer for 500 ms
set an event listener for it (your prepareText() function)
if textTimeOut is called again before the timer gets to 0,
reset the timer to 500 ms
}
I would use a setTimeout in the event handler and reset it everytime it changes:
var changeTimeout:Number = -1
function handler(e:Event):void {
if(changeTimeout != -1)
clearTimeout(changeTimeout)
changeTimeout = setTimeout(function():void{
changeTimeout = -1
prepareText();
}, 500)
}
So I used a timer. Thanks for the advice. This is what the end result is:
protected var timer:Timer = new Timer(300);
public function AdvancedTextArea()
{
super();
this.addEventListener(Event.CHANGE,textchangeListener);
timer.addEventListener(TimerEvent.TIMER,prepareText);
timer.repeatCount = 1;
}
public function textchangeListener(e : Event):void
{
if(timer.running)
{
timer.stop();
}
timer.start();
}

Resources