OnKeyDown (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following code aborts a print job if you press Esc. Note that you should set KeyPreview to True to ensure that the OnKeyDown event handler of Form1 is called. Printer is a global Printers functions that returns a global instance of TPrinter to manage interaction with the printer.


Code

#include <Printers.hpp>

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
   KeyPreview = True;
}

void __fastcall TForm1::FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)

{
  if (Key == VK_ESCAPE && Printer()->Printing)
  {
	Printer()->Abort();
	MessageDlg("Printing aborted", mtInformation,
               TMsgDlgButtons() << mbOK,0);
  }
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  TMemo *Memo1 = new TMemo(Form1); // The parent (Form1) will clean up this object.
  Memo1->Parent = Form1;
  Memo1->Visible = True;
  Memo1->Width = 700;
  if (OpenDialog1->Execute())
  {
	Memo1->Lines->LoadFromFile(OpenDialog1->FileName);

	Printer()->BeginDoc();
	int X = 200;
	int Y = 200;
	for (int I = 0; I <= 10; I++)
	  if (!Printer()->Aborted)
	  {
		Printer()->Canvas->TextOut(X, Y, Memo1->Lines->Strings[I]);
		Y = Y + 80;
		if (Y > (Printer()->PageHeight - 300))
		{
		  Y = 200;
		  Printer()->NewPage();
          Sleep(1000);  // to give you time to abort!
		}
	  }
	if (!Printer()->Aborted) Printer()->EndDoc();
  }
}

Uses