2009. július 1., szerda

Create your first console application to interact with forms


Problem/Question/Abstract:

Interaction between your Console applications and your forms

Answer:

This code demonstrates how to combine console API with usual forms

Create a new -> console application and save it as listing2
Copy the given code in to the console application
Create a form in the same project with name frmDialog1.dfm and dialog1.pas
In the form put three RadioButtons
Now build and run the application
Shift the focus to the console application and type 1 or 2 or 3

Based on the number typed the Radiobutton in the form will be clicked automatically When u press ctrl + c the application exits

program listing2;
{$APPTYPE CONSOLE}
uses
  SysUtils, Windows, Messages, Forms,
  Dialog1 in 'Dialog1.pas' {frmDialog1};

var
  hInput: THandle;
  inRec: TInputRecord;
  dwCount: DWORD;

begin
  {Create a Form in the usual way. The Forms unit ensures that
  the Application object is around to "own" the form.}

  Write('Creating the first Dialog Box...');
  frmDialog1 := TfrmDialog1.Create(Application);
  frmDialog1.Show;
  Writeln('done.');

  Writeln('Press 1, 2 or 3 to change the dialog box. Press Ctrl+ C to exit');

  {Handle the Console input till the user cancels}
  hInput := GetStdHandle(STD_INPUT_HANDLE);
  {GetStdHandle - Returns handle for Standard input/output device}

  while True do
  begin
    {Avoid blocking on user input, so the forms have a chance
    to operate as normal. If we had a message queue present, this
    would be a normal message dispatch loop.}
    Application.ProcessMessages;
    if WaitForSingleObject(hInput, 0) = WAIT_OBJECT_0 then
    begin
      ReadConsoleInput(hInput, inRec, 1, dwCount);
      if (inRec.EventType = KEY_EVENT) and inRec.Event.KeyEvent.bKeyDown then
      begin
        case inRec.Event.KeyEvent.AsciiChar of
          '1':
            begin
              Writeln('->1');
              frmDialog1.RadioButton1.Checked := True;
            end;

          '2':
            begin
              Writeln('->2');
              frmDialog1.RadioButton2.Checked := True;
            end;
          '3':
            begin
              Writeln('->3');
              frmDialog1.RadioButton3.Checked := True;
            end;
        end;
      end;
    end;
  end;
end.

Nincsenek megjegyzések:

Megjegyzés küldése