Changing the text color of an F# Console Application

By default, console texts are displayed in white. To change the text color, use the Console object together with its ForegroundColor Property.

Syntax:
Console.ForegroundColor<-Color value
Color values are stored in the ConsoleColor object and has the following values:

1. Black
2. DarkBlue
3. DarkGreen
4. DarkCyan
5. DarkRed
6. DarkMagenta
7. DarkYellow

8. Gray
9. DarkGray
10. Cyan
11. Red
12. Yellow
13. White
 

To assign the ConsoleColor object as a value of the Console ForegroundColor property, use the following syntax:
Console.ForegroundColor<-ConsoleColor.Colorname
For the sake of example, let us make a console application that will display the text “I am cyan” in cyan text color by following these steps: 1. Click Start>All Programs>Microsoft Visual Studio 2008>Microsoft Visual Studio 2008. 2. Click File>New>Project>Select Visual F# in the project types>Select F# application in the Visual Studio installed templates category. 3. The following should then come into view: 4. Enter the following code after the line “// Learn more about F# at http://fsharp.net “:
//Use the F# Library
open System
//assigns Cyan color to our console text color
Console.ForegroundColor<-ConsoleColor.Cyan
//Create a function named myfunction()
let myfunction()=
//adds an action to our function
//in this case, displays an "I am Cyan" text
printfn "I am Cyan"
//executes our function        
myfunction()
5. Press Ctrl+F5 to execute the console application. You should now see the following output:
6. To add a background color, you can use the BackgroundColor property of the Console object which follows the same syntax as ForegroundColor property. That’s all. Thanks!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.