Bits & Bytes

Posts Tagged ‘C Sharp’

Using WPF in a C# Console Application

In this blog post, I demonstrate how to create a C# console application that can open a Windows Presentation Foundation window so that we can draw WPF graphics in a console program. The methodology is important because it can be used to add Windows Presentation Foundation classes to any type of C# project.

  1. To start, you should have a default C# Console Application project open. If you do not know how to create a C# console application project, you can consult our prior blog post on that topic.
    OpenProject
  2. Once you have a console application project open, it should have a Program.cs file with the following code inside it:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication {
        class Program {
            static void Main(string[] args) {
            }
        }
    }
    

    As the namespace indicates, the project was created using the default project name ConsoleApplication.

  3. We need to change some of the code. Begin by replacing the lines
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    

    with the line

    using System.Windows;
    
  4. Directly after the line
    class Program {

    add this line

    [STAThread]
  5. Directly after the line
    static void Main(string[] args) {

    add the following lines of code:

    Window qWindow = new Window();
    qWindow.Title = "WPF in Console";
    qWindow.Width = 400;
    qWindow.Height = 300;
    qWindow.ShowDialog();
    

    The final program should look like this

    using System;
    using System.Windows;
    
    namespace ConsoleApplication {
        class Program {
            [STAThread]
            static void Main(string[] args) {
                Window qWindow = new Window();
                qWindow.Title = "WPF in Console";
                qWindow.Width = 400;
                qWindow.Height = 300;
                qWindow.ShowDialog();
            }
        }
    }
    
  6. That is all of the code. Next, we need to add the libraries that the program uses. To do this, right-click References in the Solution Explorer pane on the right of the screen, and left-click Add Reference… in the context menu that pops up.
  7. That will open the Reference Manager dialog shown below. Navigate to Assemblies->Framework by left-clicking them, and then left-click the check boxes next to PresentationCore, PresentationFramework, and WindowsBase. Finish by left-clicking the OK button.
    ReferenceManager
  8. Now the code and project are ready. To compile and execute the program, left-click DEBUG in the menubar and left-click Start Without Debugging in the submenu. When it finishes compiling, you should see this window:
    Output

Perhaps the most important line of code in this program is [STAThread]. Without this, you can not compile WPF code. STA stands for Single Threaded Apartment. It is a directive for COM. the Component Object Model. If that does not makes sense, feel free to ignore it.

The code inside the Main() function, creates a Window object, sets the text in the title bar, sets the size of the window to 400 by 300 pixels, and causes the window to be displayed with the call to ShowDialog().

Creating a C# Console Application in Visual Studio 2013

This post explains how to create a simple console application in C# and make it print out a message. Console applications are the simplest applications. So, this is the perfect place to start if you have no prior knowledge of C#.

  1. Navigate to the Start menu by left-clicking the Windows icon in the lower-left corner of your Desktop screen.
    Desktop
  2. Then left-click the down arrow in the lower-left corner to go the Apps section and find the Visual Studio 2013 icon.
  3. Left-click the Visual Studio 2013 icon to open the Visual Studio 2013 application.
    StartMenu
  4. Left-click FILE in the menubar, mouse over New in the submenu, and left-click Project in the submenu to open the New Project dialog.
    NewProject
  5. Select Installed->Templates->Visual C#->Windows in the left-hand pane.
    Installed_Templates
  6. Then left-click Console Application in the center pane.
    ConsoleAppplication
  7. If you want to accept the default project name and location, left-click the OK button to finish creating the console application. Otherwise, you can first:
    1. Set the name of the project in the field next to “Name:” near the bottom of the dialog.
    2. Select a location by left-clicking the “Browse” button.
  8. Now the project is created. To get the program to do something, add the line
    Console.WriteLine("God is Love!");

    to the code file “Program.cs” so that the final code looks like this:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication {
        class Program {
            static void Main(string[] args) {
                Console.WriteLine("God is Love!");
            }
        }
    }
    
  9. To compile and run the program, left-click DEBUG in the menubar and left-click Start Without Debugging in the submenu.
    StartWithoutDebugging
  10. When the program finishes compiling and runs, a console window should open like this one with the message “God is Love!” inside of it.
    Output

Using Rectangular and Jagged Arrays in C#

One of the unique and problematic features of C# is its usage of arrays. There are two different and distinct styles of syntax: comma delimited indices for rectangular arrays and repeated bracket operators for jagged arrays. These are written as “MyArray[2,4]” and “MyArray[2][4]”, respectively.

The program below demonstrates how to use both of these types of arrays by creating an example of each. Under the comment Rectangular Array Example, I declare and allocate a rectangular 2-dimensional array of stock price closes a few companies; the first dimension of the array is indexed by company and the second is indexed by the date. Under the comment Jagged Array Example, I declare and allocate a 2-dimensional jagged array of stock trades; the first dimension of the array is indexed by the ticker symbol and the second is indexed by the trade number for that symbol. These arrays could be of any number of dimensions; I have used the simple case of 2 dimensions for illustration.

For the first array, we have a 3 by 5 rectangular array of 5 stock price closes each for 3 companies. The entire 2-dimensional array is allocated all at once. Notice that indices are comma delimited, which is unusual for computer programming. Also, notice the nesting pattern for the braces where I have initialized the array entries. Inside the for-loops, I used the GetLength() function along with the dimensional index to get the length along any given dimension.

For the second array, we have 2 entries along the first dimension and 2 and 3 along the second dimension to specify 2 and 3 trades for each of the 2 symbols. The first dimension is allocated at the declaration; below that, each of the second dimensions are allocated and assigned values separately. The values of the arrays represent sells with positive numbers and buys with negative numbers. Inside the for-loops, I access the Length property to get the size along the first dimension. Then I access the Length property with each index by using the bracket operator to get the varying length along the second dimension. Notice that the more common repeated bracket syntax has replaced the comma delimited syntax in this second example.

The output from running the code is shown below the program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Arrays {
    class Program {
        static void Main(string[] args) {
            // ***** Rectangular Array Example *****
            // The stock price close for 3 companies for a week
            double[,] daaStockPriceClose = new double[3, 5]{
                {576.11, 585.00, 585.88, 583.82, 583.59},
                {44.94, 44.97, 45.34, 44.84, 45.35},
                {98.49, 99.41, 100.44, 100.57, 100.29}
            };

            for (int iCompany = 0; iCompany < daaStockPriceClose.GetLength(0); ++iCompany) {
                Console.Write("Company #" + iCompany + ":  ");
                for (int iDay = 0; iDay < daaStockPriceClose.GetLength(1); ++iDay) {
                    Console.Write(daaStockPriceClose[iCompany ,iDay] + "  ");
                }
                Console.WriteLine("");
            }
            Console.WriteLine("");

            // ***** Jagged Array Example *****
            // The stock set of stock trades
            double[][] dppStockTrades = new double[2][];
            dppStockTrades[0] = new double[3]{10265.82, -4925.39, -3096.72};
            dppStockTrades[1] = new double[2]{6636.96, -9746.58};
            for (int iSymbol = 0; iSymbol < dppStockTrades.Length; ++iSymbol) {
                Console.Write("Symbol #" + iSymbol + ":  ");
                for (int iTrade = 0; iTrade < dppStockTrades[iSymbol].Length; ++iTrade) {
                    Console.Write("Trade #" + iTrade + ": " + dppStockTrades[iSymbol][iTrade] + "  ");
                }
                Console.WriteLine("");
            }
            Console.WriteLine("");
        }
    }
}

ArraysOutput

 

© 2007–2024 XoaX.net LLC. All rights reserved.