Skip to content

Tip: Pass Values Between Windows with an API

A question on the Xojo Forum got me thinking that it may not be obvious how to avoid having to reach inside another window (or dialog etc.) to access its controls to get and set values. I’m sure we all have done this at one time or another but it really is something you should avoid. Here’s a small app to demo how to make an API instead:

  1. Create a new desktop app
  2. Add a new window and set its frame type to “movable modal” name it “myDialog”
  3. Add two Buttons one with the caption “cancel” and one with “close”
  4. Add a property “cancelled as boolean” and make sure its scope is public
  5. Add the action event to the cancel button and add this code:
cancelled = true
  1. Add a textfield name “userText” (so the user can enter something and we can send it back to the caller just to illustrate)
  2. Add another property “userEnteredText as string”
  3. In the “close” button add this code to its action event:
userEnteredText = userText.text

Lastly, turn OFF implicit instance for the myDialog window.

With this technique Cancelled and userEnteredText are the “API” portion of this dialog that the rest of your app uses and cares about. In a more complex example you might return many values or a class instance but the principles are not radically different.

To use this in your code:

  1. On Window1 add a button and a text field – name the text field “fromDialog”
  2. Add the action event to the button
  3. In the action event put this code:
       dim dlg as new myDialog


       if not dlg.Cancelled then
              fromDialog.text = dlg.userEnteredText
       end if

Run the project to try it out.

You’ve now successfully made an API so whatever is using this dialog doesn’t need to know how things work, such as how the dialog presents and stores information. All you need to know is that you create one, tell it to “run” (the ShowModal call) and when it’s done you can ask it for “did the user cancel” and if they didn’t you can ask the dialog for “what did that user enter?” and get a reply.

Beyond that you don’t need to know the names of controls or anything else that dialog doesn’t want you to know about. Next time you need to do something along these lines now you know how to “make an API” you can use and save yourself a lot of headaches down the road.

For another way to make an input window like this, check out the example that is included with Xojo: Examples/Desktop/Windows/InputWindow.