Monday, July 11, 2022

Scientific Calculator

To get familiar with VCL form application development, let's create a simple scientific calculator. This example is based on How to Create a Calculator with Pascal in Dephi by DJ Oamen.

Calculator User Interface


The TButton control in Delphi Pascal does not allow the color to be changed. The buttons in the UI shown above are TPanel controls with MouseEnter and MouseLeave event handlers to change the panel color to a lighter gray to simulate a button.

procedure TForm2.PanelMouseEnter(Sender: TObject);
var
  ThePanel: TPanel;
begin
  ThePanel := Sender as TPanel;
  ThePanel.Color := clBtnShadow;
end;
procedure TForm2.PanelMouseLeave(Sender: TObject);
var
  ThePanel: TPanel;
begin
  ThePanel := Sender as TPanel;
  ThePanel.color := cl3DDkShadow;
end;

Calculator Button Handlers

Number Buttons

Typical click handler ('7' button)

procedure TForm2.btn7Click(Sender: TObject);
begin
if txtResult.Text = '0.0' then
  txtResult.Text := '7'
else
  txtResult.Text := txtResult.Text + '7';
end;

Math Operators Buttons

Typical click handler (+ button)

procedure TForm2.btnAddClick(Sender: TObject);
begin
  num1 :=  txtResult.Text;
  oper := '+';
  txtResult.Text := '';
end;

Equals Buton Handler

procedure TForm2.btnEqClick(Sender: TObject);
begin
  num2 := txtResult.Text;
  if oper = '+' then
    result := FloatToStr(StrToFloat(num1) + StrToFloat(num2));
    txtResult.Text := result;
  if oper = '-' then
    result := FloatToStr(StrToFloat(num1) - StrToFloat(num2));
    txtResult.Text := result;
  if oper = '*' then
    result := FloatToStr(StrToFloat(num1) * StrToFloat(num2));
    txtResult.Text := result;
  if oper = '/' then
    result := FloatToStr(StrToFloat(num1) / StrToFloat(num2));
    txtResult.Text := result;
end;

C and CE Button Handlers

procedure TForm2.btnCClick(Sender: TObject);
begin
    txtResult.Text := '0.0';
end;

procedure TForm2.btnCEClick(Sender: TObject);
var f, s: String;
begin
  txtResult.Text := '0.0';

  f := num1;
  s := num2;

  f := '';
  s := '';
end;

PI Button Handler

procedure TForm2.btnPiClick(Sender: TObject);
begin
   txtResult.Text := '3.14159265';
end;

Function Button Handlers

Typical function click handler (Sin button)

procedure TForm2.btnSinClick(Sender: TObject);
begin
  txtResult.Text := FloatToStr(Sin(StrToFloat(txtResult.Text)));
end;

The full source code for the Scientific Calculator is available on GitHub.




No comments:

Post a Comment

Scientific Calculator

To get familiar with VCL form application development, let's create a simple scientific calculator. This example is based on  How to Cre...