Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to prematurely escape a While Loop

Status
Not open for further replies.

nhungr

Programmer
Jan 31, 2005
26
0
0
CA
I am writing a C++ DLL that runs a very long While loop. How can I allow the user to break out of this loop by pressing Esc on the keyboard?

Thanks alot!
Nikolai.
 
One way:

Spawn a separate thread to actually run the loop code, and have the original (parent) thread listen for keyboard input while waiting for the loop thread to exit. If the parent notices that the user has pressed [tt]Esc[/tt], have it kill or signal the looping thread.
 
chipperMDW's solution is ideal.
More simple (and dirty) polling for console apps:
Code:
#include <conio.h>
// Warning: non-standard header.

void KbFlush()
{
  while (_kbhit())
    _getch();
}

namespace { const int esc = 27; }

bool KbTest()
{
  bool res = false;
  if (_kbhit())
  {
     if (_getch() == esc)
        res = true;
     else
	printf("Press esc to quit...\n");
     KbFlush();
  }
  return res;
}
/// Using pattern:
void testloop()
{
  for (;;)
  {
  /////
    if (KbTest())
       break;
  /////
  }
}
 
Thanks alot for the tips...

ArkM: I tried implanting a version of your code into mine, but for some reason there is no response to any key presses. _kbhit() always returns 0 regardless of what key I press!?!

The loop I am trying to interrupt is in a DLL that I call from a separate executable file (created in Visual Basic).

Any ideas??

Thanks again,
Nikolai.
 
Try GetStdHandle/PeekConsoleInput etc console API stuff (console app, polling mode of ops; see MSDN for more info).
Sorry, now I have no time to check up on this approach...
 
Thanks so much for the help. I figured it out. I just modified your KbTest function with the following code:

Code:
bool KeyboardTest()
{
	if (GetAsyncKeyState(VK_ESCAPE)!=0)
	{
		return true;
	}
	return false;
}

and it works... Thanks again,

Nikolai.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top