Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Modal Forms

Status
Not open for further replies.

ormsk

Programmer
Sep 30, 2002
147
GB
I am new to Delphi and I am looking for a way to pass a string from a modal form, back to it's calling form while keeping things encapsulated.

The help files were suggesting using pointers and constructors, but I could not really understand the code that was listed and my small app would not compile.

Can ayone help?

Thanks
 
What I do when I need this type of functionality is use a "Class Function". This is a special type of method that is part of a particular class that you can call without already having an instance of the class. You declare it like this in either the public or protected section of the interface:
Code:
class function ShowMyForm(aOwner: TComponent): String;
The function itself will look something like this:
Code:
class function TMyForm.ShowMyForm(aOwner: TComponent): String;
var
  frm: TMyForm;
begin
  frm := TMyForm.Create(aOwner);
  result := '';
  try
    if frm.ShowModal = mrOK then
      result := frm.ReturnValue;
  finally
    frm.Free;
  end;
end;
The code that calls this function will look like this:
Code:
  s := TMyForm.ShowMyForm(self);
  if s <> '' then
    //modalresult was mrOK, do whatever you need to 
    //with the return string
  else
    //modalresult was not mrOK, do whatever exception
    //handling you need.

-Dell
 
The way I do it is to declare a global function in the unit that defines the form you want to show modal. In your case it would look something like this:
Code:
function GetMyString(var MyString:string):boolean;
And the implementation would look something like this:
Code:
function GetMyString(var MyString:string):boolean;
var
  nModalResult: integer;
begin
  Application.CreateForm(TForm1, Form1);
  With Form1 do
    begin
      SetupDialog();
      nModalResult := ShowModal;
      if nModalResult = mrOk then
        begin
          Result := True;
          MyString := FMyString;
        end
      else
        Result := False;
      Free;
    end;
end;
Notes:
1. Do not auto-create the form.
2. You may not need a SetupDialog() function if there is nothing special to do before showing the form.
3. FMyString is a private variable in TForm1. Put the string you want to return there.

Then to use it simply invoke the global function:
Code:
:
:
var
  s:string;
begin
  if GetMyString( s ) then
    begin
      // Use the string
    end;
:
:
 

Another way for a simple case is to use one of the Delphi functions InputBox or InputQuery.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top