The Basics of VB.NET Through Text Game Development - Working with the Console continued
(Page 3 of 4 )
Write and WriteLine write to the screen wherever the cursor is at. Usually, the cursor will just move straight down the screen. A line will be written out, and then the cursor will move to the first column of the next row in the console in preparation for another line being written. This default behavior is of little use to us, but if Write follows around the cursor, then all we need to do is change the location of the cursor. Then we can write characters out anywhere.
We can move the cursor around using the SetCursorPosition procedure. It takes two Integer arguments, which basically form a standard (x, y) coordinate. The first argument indicates the horizontal position of the cursor (the column that the cursor is in) and the second argument indicates the vertical position of the cursor (the row that the cursor is in). Note that the top left edge of the console is the zeroth column of the zeroth row. So, to write something at the very top left, we'd do this:
Console.SetCursorPosition(0, 0)
Console.Write("Hello World.")
Note that after running the above code, the cursor will be immediately after the written text. So, if we write more text to the screen, it will follow right after “Hello World.”
Feel free to go ahead and play around a bit more with SetCursorPosition. Here, we write “Hello World” well off the top left edge of the screen:
Console.SetCursorPosition(10, 10)
Console.Write("Hello World.")
We can also set the position of the cursor through the CursorLeft and CursorTop properties of Console. The following code produces the same effect as the above code:
Console.CursorLeft = 10
Console.CursorTop = 10
Console.Write("Hello World.")
We can use these same two properties to read the position of the cursor. Here, we display the position of the cursor using Write and a format string:
Console.Write("The cursor is at ({0}, {1})", Console.CursorLeft, Console.CursorTop)
I'm going to switch topics for just a moment because this is a good time to introduce an aspect of Visual Basic's syntax. Notice how the above line is a little long. You may be tempted to break long lines of code into two or more lines. This is, of course, possible, but you can't just break them up with the return key. Instead, you have to mark line breaks with underscores, like this:
Console.Write("The cursor is at ({0}, {1}).", _
Console.CursorLeft, _
Console.CursorTop)
Notice how the underscore has a space before it. This is required.
Next: Changing Color >>
More Visual Basic.NET Articles
More By Peyton McCullough