//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "CppTestForm.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TCppTest *CppTest;

//---------------------------------------------------------------------------

__fastcall TCppTest::TCppTest(TComponent* Owner)
        : TForm(Owner)
{
}

void __fastcall TCppTest::FormCreate(TObject *Sender)
{
  Thread    =
    std::auto_ptr<TStopStartThread>(new TStopStartThread);
  UntilFlag =
    std::auto_ptr<TEvent>(new TEvent(NULL, true, false, NULL));
  WaitThread = NULL;
} // TCppTest::FormCreate

void __fastcall TCppTest::BeepBtnClick(TObject *Sender)
{
  RunInThread(Beep);
} // TCppTest::BeepBtnClick

void __fastcall TCppTest::WaitBtnClick(TObject *Sender)
{
  WaitBtn->Enabled = false;
  WaitForThread(Pause);
  WaitBtn->Enabled = true;
} // TCppTest::WaitBtnClick

void __fastcall TCppTest::MsgWaitBtnClick(TObject *Sender)
{
  MsgWaitBtn->Enabled = false;
  MsgWaitForThread(WaitThread, Pause);
  MsgWaitBtn->Enabled = true;
} // TCppTest::MsgWaitBtnClick

void __fastcall TCppTest::StopStartWaitBtnClick(TObject *Sender)
{
  StopStartWaitBtn->Enabled = false;
  Thread->Run(Pause, NULL, false);
  StopStartWaitBtn->Enabled = true;
} // TCppTest::StopStartWaitBtnClick

void __fastcall
     TCppTest::StopStartMsgWaitBtnClick(TObject *Sender)
{
//  try {
    StopStartMsgWaitBtn->Enabled = false;
    Thread->Run(Pause);
    StopStartMsgWaitBtn->Enabled = true;
//  } catch (EAbort&) { Close(); }
} // TCppTest::StopStartMsgWaitBtnClick

void __fastcall TCppTest::InfiniteWaitBtnClick(TObject *Sender)
{
//  try {
    InfiniteWaitBtn->Enabled = false;
    Thread->Run(InfinitePause);
    InfiniteWaitBtn->Enabled = true;
//  } catch (EAbort&) { Close(); }
} // TCppTest::InfiniteWaitBtnClick

void __fastcall TCppTest::EventWaitBtnClick(TObject *Sender)
{
  EventWaitBtn->Enabled = false;
  UntilBtn->Enabled     = true;

  UntilFlag->ResetEvent();
  MsgWaitForSingleObject((HANDLE) UntilFlag->Handle);

  EventWaitBtn->Enabled = true;
  UntilBtn->Enabled     = false;
} // TCppTest::EventWaitBtnClick

void __fastcall TCppTest::UntilBtnClick(TObject *Sender)
{
  UntilFlag->SetEvent();
} // TCppTest::UntilBtnClick

void __fastcall TCppTest::SpawnBtnClick(TObject *Sender)
{
  SpawnBtn->Enabled = false;
  MsgWaitForSingleObject(SpawnProcess("test.bat").hProcess);
  SpawnBtn->Enabled = true;
} // TCppTest::SpawnBtnClick

void __fastcall TCppTest::wmClose(TMessage Message)
{
  if (WaitThread != NULL) WaitThread->AbortThread();
  if (UntilBtn->Enabled)  UntilFlag->SetEvent();
  if (Thread->Waiting)    Thread->AbortThread();
  Close();
} // TCppTest::wmClose

//---------------------------------------------------------------------------