HandleMessage (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following code demonstrates background processing using the OnIdle event and using the HandleMessage method to allow messages or background processing to get through. Note: You must add MyIdleHandler to the Form1 methods.

Code

// Global variables to show the order of events
int XPos, YPos, Delta;

/*
 This is a utility procedure to display messages.
 Add it at the beginning of the unit.
*/
void StatusMsg(TForm *Form, TCanvas *Canvas, char *Message, bool Bkg)
{
  if (!Bkg)
	Canvas->Font->Style = TFontStyles() << fsBold; // Foreground messages are bold.
  Canvas->TextOut(XPos, YPos, Message);
  if (!Bkg)
	Canvas->Font->Style = TFontStyles();
  // Change Xpos and YPos to prepare for the next message.
  YPos += Delta;
  if (YPos >= Form->ClientHeight - 10)
  {
	YPos = 10;
	XPos += 180;
  }
  if (XPos >= Form->ClientWidth - 100)
  {
    if (Canvas->Font->Color == clRed)
      Canvas->Font->Color = clBlack;
    else
      Canvas->Font->Color = clRed;
    XPos = 10;
  }
}

/*
  This is the OnCreate event handler for Form1. It initializes global values and sets 
  the application's OnIdle event handler.
*/
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
  Button1->Caption = "Do not yield";
  Button2->Caption  = "Handle Message";
  Application->OnIdle = MyIdleHandler;
  XPos = 10;
  YPos = 10;
  if (Canvas->Font->Height > 0)
    Delta = Canvas->Font->Height + 1;
  else
    Delta = 1 - Canvas->Font->Height;
}

/*
  This is the OnIdle event handler. It is set in the Form's
  OnCreate event handler, so you only need to add it as a private
  method of the form. Usually, it would perform background
  processing for the application. This one simply writes a
  message to inform you when it is there.
*/
void __fastcall TForm1::MyIdleHandler(TObject *Sender, bool &Done)
{
  StatusMsg(Form1, Canvas, "This represents a background process.", true);
}

/*
  This is the OnClick event handler for Button1. 
  It simulates a lengthy process.
*/
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  int X, Y;
  StatusMsg(Form1, Canvas, "The Button1Click handler is starting", false);
  for (int I = 0; I < 100; I++)
  {
    randomize();
    for (int J = 0; J < 100; J++)
      Y = random(J);
	X = random(I);
  }
  StatusMsg(Form1, Canvas, "The Button1Click handler is done", false);
}

/*
  This is the OnClick event handler for button2. 
  It simulates a lengthy process that allows 
  other messages to be processed.
*/
void __fastcall TForm1::Button2Click(TObject *Sender)
{
  int X, Y;
  StatusMsg(Form1, Canvas, "The Button2Click handler is starting", false);
  for (int I = 0; I < 100; I++)
  {
    randomize();
	for (int J = 0; J < 100; J++)
    {
	  Y = random(J);
	}
	// Yield to OnIdle or other messages
	Application->HandleMessage();
	X = random(I);
  }
  StatusMsg(Form1, Canvas, "The Button2Click handler is done", false);
}

Uses