In this tutorial for C#, you'll use Visual Studio to create and run a console app and explore some features of the Visual Studio integrated development environment (IDE) while you do so.
Top: The Save dialog box, or sheet, initially appears in a compact view. Right (inset): If you open the Where pop-up menu, you’ll find that Mac OS X neatly lists all the places it thinks you might want to save your new document: on the hard drive or iDisk, in a folder that you’ve put into your Sidebar (Section 1.2.1), or into a folder you’ve recently opened. Nov 30, 2018 2. Creating Custom Dialog Boxes The Dialog & User Interface VIs are useful when you need a dialog box for a simple application, but you should create a custom dialog box if an application requires a more complex dialog box. To create a custom dialog box, arrange the front panel of a VI to make it look and behave like a dialog box. With the first label being in place, the second quite common Cocoa control used in macOS apps is the text field. It’s a NSTextField object, and its purpose is to enable apps receiving user input when necessary. A text field is a single-line text input control, so if you want multiple lines of text you’d better pick a text view instead.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
Create a project
To start, we'll create a C# application project. The project type comes with all the template files you'll need, before you've even added anything!
Open Visual Studio 2017.
From the top menu bar, choose File > New > Project.(Alternatively, press Ctrl+Shift+N).
In the left pane of the New Project dialog box, expand C#, and then choose .NET Core. In the middle pane, choose Console App (.NET Core). Then name the file Calculator.
Add a workload (optional)
If you don't see the Console App (.NET Core) project template, you can get it by adding the .NET Core cross-platform development workload. Here's how.
Option 1: Use the New Project dialog box
Choose the Open Visual Studio Installer link in the left pane of the New Project dialog box.
The Visual Studio Installer launches. Choose the .NET Core cross-platform development workload, and then choose Modify.
Option 2: Use the Tools menu bar
Cancel out of the New Project dialog box and from the top menu bar, choose Tools > Get Tools and Features.
The Visual Studio Installer launches. Choose the .NET Core cross-platform development workload, and then choose Modify.
Open Visual Studio 2019.
On the start window, choose Create a new project.
On the Create a new project window, enter or type console in the search box. Next, choose C# from the Language list, and then choose Windows from the Platform list.
After you apply the language and platform filters, choose the Console App (.NET Core) template, and then choose Next.
Note
If you do not see the Console App (.NET Core) template, you can install it from the Create a new project window. In the Not finding what you're looking for? message, choose the Install more tools and features link.
Then, in the Visual Studio Installer, choose the .NET Core cross-platform development workload.
After that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work; if so, do so. Next, choose Continue to install the workload. Then, return to step 2 in this 'Create a project' procedure.
In the Configure your new project window, type or enter Calculator in the Project name box. Then, choose Create.
Visual Studio opens your new project, which includes default 'Hello World' code.
Create the app
First, we'll explore some basic integer math in C#. Then, we'll add code to create a basic calculator. After that, we'll debug the app to find and fix errors. And finally, we'll refine the code to make it more efficient.
Explore integer math
Let's start with some basic integer math in C#.
In the code editor, delete the default 'Hello World' code.
Specifically, delete the line that says,
Console.WriteLine('Hello World!');
.In its place, type the following code:
Notice that when you do so, the IntelliSense feature in Visual Studio offers you the option to autocomplete the entry.
Note
The following animation isn't intended to duplicate the preceding code. It's intended only to show how the autocomplete feature works.
Choose the green Start button next to Calculator to build and run your program, or press F5.
A console window opens that reveals the sum of 42 + 119, which is 161.
(Optional) You can change the operator to change the result. For example, you can change the
+
operator in theint c = a + b;
line of code to-
for subtraction,*
for multiplication, or/
for division. Then, when you run the program, the result changes, too.Close the console window.
Add code to create a calculator
Let's continue by adding a more complex set of calculator code to your project.
Delete all the code you see in the code editor.
Enter or paste the following new code into the code editor:
Choose Calculator to run your program, or press F5.
A console window opens.
View your app in the console window, and then follow the prompts to add the numbers 42 and 119.
Your app should look similar to the following screenshot:
Add functionality to the calculator
Let's tweak the code to add further functionality.
Add decimals
The calculator app currently accepts and returns whole numbers. But, it will be more precise if we add code that allows for decimals.
As in the following screenshot, if you run the app and divide number 42 by the number 119, your result is 0 (zero), which isn't exact.
Let's fix the code so that it handles decimals.
Press Ctrl + H to open the Find and Replace control.
Change each instance of the
int
variable tofloat
.Make sure that you toggle Match case (Alt+C) and Match whole word (Alt+W) in the Find and Replace control.
Run your calculator app again and divide the number 42 by the number 119.
Notice that the app now returns a decimal numeral instead of zero.
However, the app produces only a decimal result. Let's make a few more tweaks to the code so that the app can calculate decimals too.
Use the Find and Replace control (Ctrl + H) to change each instance of the
float
variable todouble
, and to change each instance of theConvert.ToInt32
method toConvert.ToDouble
.Run your calculator app and divide the number 42.5 by the number 119.75.
Notice that the app now accepts decimal values and returns a longer decimal numeral as its result.
(We'll fix the number of decimal places in the Revise the code section.)
Debug the app
We've improved on our basic calculator app, but it doesn't yet have fail safes in place to handle exceptions, such as user input errors.
For example, if you try to divide a number by zero, or enter an alpha character when the app expects a numeric character (or vice versa), the app might stop working, return an error, or return an unexpected nonnumeric result.
Let's walk through a few common user input errors, locate them in the debugger if they appear there, and fix them in the code.
Tip
For more information about the debugger and how it works, see the First look at the Visual Studio debugger page.
Fix the 'divide by zero' error
When you try to divide a number by zero, the console app might freeze and then show you what's wrong in the code editor.
Note
Sometimes, the app doesn't freeze and the debugger won't show a divide-by-zero error. Instead, the app might return an unexpected nonnumeric result, such as an infinity symbol. The following code fix still applies.
Let's change the code to handle this error.
Delete the code that appears directly between
case 'd':
and the comment that says// Wait for the user to respond before closing
.Replace it with the following code:
After you add the code, the section with the
switch
statement should look similar to the following screenshot:
Now, when you divide any number by zero, the app will ask for another number. Even better: It won't stop asking until you provide a number other than zero.
Fix the 'format' error
If you enter an alpha character when the app expects a numeric character (or vice versa), the console app freezes. Visual Studio then shows you what's wrong in the code editor.
To fix this error, we must refactor the code that we've previously entered.
Revise the code
Rather than rely on the program
class to handle all the code, we'll divide our app into two classes: Calculator
and Program
.
The Calculator
class will handle the bulk of the calculation work, and the Program
class will handle the user interface and error-capturing work.
Let's get started.
Delete everything in the
Calculator
namespace between its opening and closing braces:Next, add a new
Calculator
class, as follows:Then, add a new
Program
class, as follows:Choose Calculator to run your program, or press F5.
Follow the prompts and divide the number 42 by the number 119. Your app should look similar to the following screenshot:
Notice that you have the option to enter more equations until you choose to close the console app. And, we've also reduced the number of decimal places in the result.
Close the app
If you haven't already done so, close the calculator app.
Close the Output pane in Visual Studio.
In Visual Studio, press Ctrl+S to save your app.
Close Visual Studio.
Code complete
During this tutorial, we've made a lot of changes to the calculator app. The app now handles computing resources more efficiently, and it handles most user input errors.
Here's the complete code, all in one place:
Next steps
Congratulations on completing this tutorial! To learn even more, continue with the following tutorials.
See also
by Stephen Swift
Displaying Dialog Boxes
September 17th, 2001
[Author's Note:If you find any of this tutorial not making sense, check out the some of the earlier installments.]
You run into dialog boxes everywhere when working on your Macintosh. You can create them in AppleScript as well. They may not be the neatest things you can do with AppleScript's functionality, but the end user likes them. Dialog boxes are important because they inform the user of things that happened and they can send input to the script. It also lets us practice using 'if' handlers.
Review
The basic if handler has three parts - comparison, action, and secondary action.Syntax:
ifsomeVariable istruethen
--do something
else
--do something if it is false
endif
The if handler is used to process actions that the user has taken, such as pressing a certain button.
Basic Dialog Box
The basic dialog box is made up of four things: text, icon, buttons, and text input field (See figure 1).
Syntax:
display dialog 'the text' (*See #1*)¬
with icon note | stop | caution(*See #2*) ¬
default answer'type something' (*See #3*)¬
buttons['One', 'Two', 'Three'] (*See #4*)¬
default button1 (*See #5*)
Note: I've separated this command with ¬ characters to make it easier to see the different parts of the script. Normally, this would be on one line. Here's how each of the 5 lines above breaks down:
- This is the only required line. Display dialog is an AppleScript command to display the text (called a string) following it in a dialog box. The command is found in the scripting addition, Display Dialog. It is found in the Scripting Additions folder of the System folder. I'll get into scripting additions later on. Think of them as extensions for AppleScript. If you drag one of them onto the script editor, you will get the dictionary for that command.
- If you include this line in your script, an icon will be displayed with the text. As before, I've split your three options with the | character. You can also include custom icons in your dialog boxes. See ÎCustom Icons' later on in this article.
- The third line adds a text field to your dialog box. The user can type something to give the script information. The string following default answer is the text displayed in the text field when the dialog is displayed. If you don't put anything in the quotation marks, the field is blank.
- You can have up to three custom buttons. A list always follows this object. The items (normally strings) in the list are the buttons. If you don't specify your buttons, OK and Cancel are used. It is recommended to replace the Cancel button with something else so you can control its actions. If Cancel is pressed, the script stops. If you want the user to be able to stop your script, this is good. If you don't, you should create a different button instead.
- The last command controls what button is selected when you hit return. You can refer buttons by their placement in the button list. Item 1 is button One, so the default button is One.
Custom Icons
Parts Of Dialogue Box
You can add your own icons to your dialog boxes using ResEdit. Find an icon you want to use. Select it, choose Get Info, and copy the icon. After you save your script as an application or compiled script, drag it onto ResEdit. Press cmnd-K to create a new resource. Type 'cicn' to create a color icon resource, and hit OK. Paste the icon in the drawing box. Close the drawing box. Press cmnd-I to edit its info, type 129 (or an easy to remember number above 128), and quit out of ResEdit. What you have done is given the script an icon to use, and assigned an ID to it so you can include it in the script. When you use an ID for an icon in your script, AppleScript looks in the script file, the current application, and the System file in that order.Feedback
AppleScript records the users response so you can use it in your script. To see an example of this open Script Editor, open the result window by pressing cmnd-L, paste the following code in the main window, and hit the run button.display dialog 'Hit the OK button then look at the result.' buttons['OK', 'No']
You should see {button returned:'OK'} appear in the window. This is called a record. It is similar to a list, but each item is labeled with an object. AppleScript calls this the button returnedofresult. Using an if handler, we can determine what button was pressed, and what the scripts response should be. If the user hit the OK button, I want AppleScript to display a dialog box with 'Thank you for hitting the OK button.' If the user hit the No button, I want AppleScript to display a dialog box with 'I asked you to hit the OK button. You hit the No button.' This is how we would set it up: display dialog 'Hit the OK button then look at the result.' buttons['OK', 'No'] (*Our original dialog box.*)
ifbutton returnedofresultis'OK' then(*This will return either true or false.*)
display dialog 'Thank you for hitting the OK button.' (*Action completed if the statement is true.*)
else
display dialog 'I asked you to hit the OK button. You hit the No button.' (*Action completed if the statement is false.*)
endif(*Closes the if statement.*)
What if there were three buttons? If handlers can only handle true or false questions. Since there would be more than two choices, we'll have to use process of elimination to narrow it down to only two choices. This is how it would be done:
ifsomeVariable istruethen
--do something
elseifanotherVariable istruethen
--do a second task
else
--do another task
endif
We have three options to test. We can only test two at a time. The first if statement tests option one and two. If option one is true, the if statement completes the first action and ends. Unlike before, we can't assume option two is true. We have to test option two. The second if statement does this. If option two is true, the if statement completes the second action and ends. Now that option three is the only one left, we can assume it is true. However, if there were four options we would have to test option three like we tested option two.
Example:
display dialog 'What is your favorite flavor of ice cream?' buttons['Chocolate', 'Vanilla', 'Neither']
ifbutton returnedofresultis'Chocolate' then
display dialog 'I prefer Vanilla.'
elseifbutton returnedofresultis'Vanilla' then
display dialog 'Same here.'
else
display dialog 'This script is too simple to find out what your preference is.'
endif
When the user types text, it is recorded as the text returnedofresult. We can ask it if it is something, but that is unpractical. If the user was to type in their name, and AppleScript was to look for the word 'Bob' the script might never work. What if Bob typed in Îbob' or ÎBob.'? However, this can be used to see if it is not something with the use of the ¬ si sign (option-=). If I asked for your name, and you didn't type anything, AppleScript could recognize the error. We could then use the text returned in another dialog box.
Example Script:
display dialog 'What is your name?' default answer' buttons['OK'] default button'OK' (*Notice that I chose not to put anything in the text field.*)
iftext returnedofresult–' then(*This makes sure the user didn't just hit OK. You could use 'is not' instead of –*)
display dialog 'Hello ' & text returnedofresult(*See the detailed explanation about this dialog box.*)
else
display dialog 'You didn't enter a name.' (*The dialog box displayed if nothing was entered in the first dialog box.*)
endif
Note: When you type out a dialog message you can include anything in it that can be converted to a string (plain text). In this case, I used the name the user entered. AppleScript takes Îtext returned of result' and converts it to the name I entered in the text field, 'Stephen'. You can combine different types of data with the & sign. It then converts 'Hello ' & 'Stephen' to 'Hello Stephen'. I had to make sure there was a space after Hello or the dialog box would have said 'HelloStephen'.
Make Your Own
Now that I've covered the basic dialog box, we'll use it to make an application. Let's create an application that will ask us for a URL to go to, and it will connect us to that web page with our default browser. See Figure 2 to get an idea on what I want to create.
Fg. 2 - My application design.
We will need to make a dialog box displaying the string 'Type in a URL.' This can be done with display dialog 'Type in a URL.'. We will need to add a custom icon. I've found an icon, followed the instructions on making a custom icon, and my code uses icon129. We will also have to include a text field with 'http://www.macobserver.com' as the default URL. The code default answer makes the text field, and 'http://www.macobserver.com' makes The Mac Observer the default URL. To create the two buttons we will type buttons['Cancel', 'Connect']. To make ÎConnect' the default button we'll add default button2 to the script.
Now we need to process the information given to us. First, we'll make sure that the user typed something by using an if statement. We need to make sure that the text returned of the result is not ' so we will type iftext returnedofresult&'then. Now we want to open the URL given to us. The command 'open url' does just this. If you want more information about this command, open the scripting addition 'Internet Scripting' in Script Editor. The URL is the text returned from the result. So by typing open url(text returnedofresult) we can have AppleScript open the URL in our default browser. We've completed the first action. Type else and then we'll work on the second action. We'll inform the user that he or she didn't type in a URL. A standard dialog box such as display dialog 'You didn't enter a URL.' will work. We'll limit the only button to OK and make it the default button by typing buttons['OK'] default button1. Close up the if handler with end if, save it as an application (selecting never show startup screen), and you're done.
The finished script should look like this:
display dialog 'Type in a URL.'with icon129default answer 'http://www.macobserver.com'buttons['Cancel', 'Connect']default button2
iftext returnedofresult–'then
open URL(text returnedofresult)
else
display dialog 'You didn't enter a URL.'buttons['OK'] default button1
endif
Bonus Points...
If you thought this did the same as the 'Connect To...' application, you're right! The Connect To application is just an AppleScript similar to what we have created. Doesn't that make you feel good to know that you have created an application worthy of being on every Macintosh?Explore
Feeling a little adventurous? There is a scripting addition called Dialog Director that allows you to create different types of dialog boxes. To use it, drop it onto your closed System folder to use it. The problem with Dialog Director is it can be difficult to use. Some genius decided to make a graphic interface for it. It makes it much easier to create cool dialogs now. It's called Dialog Studio.What We Covered:
- Reviewed the if handler.
- Different Types Of Dialog Boxes.
- Using Data from the Result.
Next Time:
I'll take a break from the tutorials to write up a review of AppleScript on Mac OS X for everyone. I've played with it and so far, I see that it's going to be different, but it is going to rock!
Macos App Development And Dialogue Box For User Input In Word
Comments or Questions? Is this column going to slow or fast for you? Do you want to script something, but don't know how? Do you need something explained or have a question about a script? My E-mail address, [email protected], is open 24 hours a day, 7 days a week.
Most Recent AppleScript Columns
Break Your Script Into Pieces with Subroutines
June 26th
Repeat Yourself With AppleScript
June 12th
AppleScript Lists
June 5th
AppleScriptArchives
Back to The Mac Observer For More Mac News!