C# - Virtual console integrated into a Windows application

By , 8/15/2012
(1 ratings)
This class allows you to integrate a 'discrete' console in your application. Extending the console with other commands is simple, just look into the class (ExecuteCommand()). It is accessed by the circumflex ^ key (Shift-6).

Notes:
- Your form has to inherit from IMessageFilter (Example: public partial class Form1 : Form, IMessageFilter)

- In your form constructor you'll have to call the following function: Application.AddMessageFilter(this);

- In the Form_Load event:
my_console = new VirtualConsole(this);
my_console.SetVisibility(false);

- And finally insert following function into the form, where the console will be displayed:
// Handle the pressed keys ^, PageUp, PageDown and others
public bool PreFilterMessage(ref Message msg)
{
if (msg.Msg != WM_KEYDOWN) //(WM_KEYDOWN is 256)
{
if (msg.WParam.ToString() == "220")
{
// Key ^
my_console.SetVisibility(!my_console.GetVisibility());
return true;
}
else
{
// Allow scrolling only when the console is visible
if (my_console.GetVisibility() == true)
{
if (msg.WParam.ToString() == "33")
{
// PageUp
my_console.Scroll_Up();
return true;
}
else if (msg.WParam.ToString() == "34")
{
// PageDown
my_console.Scroll_Down();
return true;
}
}
}
}

return false;
}

Author: Konstantin Gross, translation by Michael List
Translate to VB
/*
 * VirtualConsole - Virtual console integrated into a Windows application
 * --------------------------------------------------------------------
 * Version: 1.0
 * Copyright © 2007 Konstantin Gross
 * http://www.texturenland.de
 *
*/


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace TL.Console
{
    /// <summary>
    /// 'Virtual' console that can be integrated into a Windows application
    /// 
    /// VirtualConsole - © Konstantin Gross
    /// </summary>
    class VirtualConsole
    {
        delegate void EditLabelDelegate(Label lbl, string str);

        // Executed commands
        string[] cmd_history_list;
        int cmd_history_pointer;
        int cmd_scroll_index;

        // Console log screen
        string[] con_log_list;
        int con_log_pointer;
        int scroll_index;

        // Miscellaneous
        int displayed_line;
        Form parent_form;

        #region Form Controls

        System.Windows.Forms.Panel ConsolePanel;
        System.Windows.Forms.Label ConsoleLabel;
        System.Windows.Forms.TextBox ConsoleCommandTextBox;
        System.Windows.Forms.Label[] ConsoleTextBox;

        private void InitializeConsoleComponent()
        {
            ConsolePanel = new System.Windows.Forms.Panel();
            ConsoleTextBox = new System.Windows.Forms.Label[displayed_line];
            ConsoleCommandTextBox = new System.Windows.Forms.TextBox();
            ConsoleLabel = new System.Windows.Forms.Label();
            ConsolePanel.SuspendLayout();

            // 
            // ConsolePanel
            // 
            this.ConsolePanel.BackColor = System.Drawing.Color.MediumBlue;
            this.ConsolePanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

            for (int i = 0; i < ConsoleTextBox.Length; i++)
            {
                this.ConsoleTextBox[i] = new Label();
                this.ConsolePanel.Controls.Add(ConsoleTextBox[i]);
            }

            this.ConsolePanel.Controls.Add(this.ConsoleCommandTextBox);
            this.ConsolePanel.Controls.Add(this.ConsoleLabel);
            this.ConsolePanel.Dock = System.Windows.Forms.DockStyle.Top;
            this.ConsolePanel.Location = new System.Drawing.Point(0, 410);
            this.ConsolePanel.Name = "ConsolePanel";
            this.ConsolePanel.Size = new System.Drawing.Size(818, 35 + displayed_line * 18);
            this.ConsolePanel.TabIndex = 0;
            this.ConsolePanel.Visible = false;
            // 
            // ConsoleTextBox's
            // 
            for (int i = 0; i < ConsoleTextBox.Length; i++)
            {
                this.ConsoleTextBox[i].BackColor = System.Drawing.Color.MediumBlue;
                this.ConsoleTextBox[i].Dock = System.Windows.Forms.DockStyle.Top;
                this.ConsoleTextBox[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.ConsoleTextBox[i].ForeColor = System.Drawing.Color.White;
                this.ConsoleTextBox[i].Location = new System.Drawing.Point(0, i * 18);
                this.ConsoleTextBox[i].Name = "ConsoleLabel" + i;
                this.ConsoleTextBox[i].Size = new System.Drawing.Size(816, 18);
                this.ConsoleTextBox[i].Text = "" + i;
                this.ConsoleTextBox[i].Click += new System.EventHandler(this.ConsoleLabel_Click);
            }

            // 
            // ConsoleCommandTextBox
            // 
            this.ConsoleCommandTextBox.BackColor = System.Drawing.Color.Navy;
            this.ConsoleCommandTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.ConsoleCommandTextBox.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.ConsoleCommandTextBox.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.ConsoleCommandTextBox.ForeColor = System.Drawing.Color.White;
            this.ConsoleCommandTextBox.Location = new System.Drawing.Point(0, 89);
            this.ConsoleCommandTextBox.Name = "ConsoleCommandTextBox";
            this.ConsoleCommandTextBox.Size = new System.Drawing.Size(816, 15);
            this.ConsoleCommandTextBox.TabIndex = 2;
            this.ConsoleCommandTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ConsoleCommandTextBox_KeyDown);
            // 
            // ConsoleLabel
            // 
            this.ConsoleLabel.BackColor = System.Drawing.Color.Navy;
            this.ConsoleLabel.Dock = System.Windows.Forms.DockStyle.Top;
            this.ConsoleLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.ConsoleLabel.ForeColor = System.Drawing.Color.White;
            this.ConsoleLabel.Location = new System.Drawing.Point(0, 0);
            this.ConsoleLabel.Name = "ConsoleLabel";
            this.ConsoleLabel.Size = new System.Drawing.Size(816, 18);
            this.ConsoleLabel.TabIndex = 0;
            this.ConsoleLabel.Text = "- Console -";
            this.ConsoleLabel.Click += new System.EventHandler(this.ConsoleLabel_Click);

            this.ConsolePanel.ResumeLayout(false);
            this.ConsolePanel.PerformLayout();

            parent_form.Controls.Add(this.ConsolePanel);
        }

        private void ConsoleTextBox_Click(object sender, EventArgs e)
        {
            ConsoleCommandTextBox.Focus();
        }

        private void ConsoleLabel_Click(object sender, EventArgs e)
        {
            ConsoleCommandTextBox.Focus();
        }

        private void ConsoleCommandTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                // Execute the command if RETURN was pressed
                string cmd = ConsoleCommandTextBox.Text;
                ConsoleCommandTextBox.Text = "";
                ExecuteCommand(cmd);
            }
            else if (e.KeyValue == 38)
            {
                // Go up in the history list
                cmd_scroll_index--;
                if (cmd_scroll_index < 0) cmd_scroll_index = cmd_history_list.Length - 1;


                // Display command in testbox
                int projected_index = (cmd_history_list.Length + cmd_history_pointer + cmd_scroll_index) % (cmd_history_list.Length);
                ConsoleCommandTextBox.Text = cmd_history_list[projected_index];
            }
            else if (e.KeyValue == 40)
            {
                // Go down in the history list
                cmd_scroll_index++;
                if (cmd_scroll_index > cmd_history_list.Length - 1) cmd_scroll_index = 0;

                // Display command in testbox
                int projected_index = (cmd_history_list.Length + cmd_history_pointer + cmd_scroll_index) % (cmd_history_list.Length);
                ConsoleCommandTextBox.Text = cmd_history_list[projected_index];
            }
        }


        #endregion

        /// <summary>
        /// Where should the console be displayed?
        /// </summary>
        /// <param name="parent">Form where the console will be displayed.</param>
        public VirtualConsole(Form parent)
        {
            parent_form = parent;

            // Constructor with default values
            con_log_list = new String[100];
            con_log_pointer = 0;
            scroll_index = 0;

            // Executed commands
            cmd_history_list = new String[50];
            cmd_history_pointer = 0;
            cmd_scroll_index = 0;

            displayed_line = 6;

            InitializeConsoleComponent();

            WriteLine("Type help to display a list of avaliable commands");
            WriteLine("----------------------------------------------------------");
            WriteLine(" - Use ^ to show/hide the console");
            WriteLine(" - Use Up/Down to view the last commands");
            WriteLine(" - Use PageUp/PageDown to scroll the console log");
            WriteLine("- © 2007 Konstantin Gross - www.texturenland.de -");
        }

        /// <summary>
        /// Sets the visibility of the console.
        /// </summary>
        /// <param name="visible">Should the console be visible?</param>
        public void SetVisibility(bool visible)
        {
            ConsolePanel.Visible = visible;

            if (visible == true)
            {
                ConsoleCommandTextBox.Focus();
            }
            else
            {
                parent_form.Focus();
            }
        }

        /// <summary>
        /// Is executed when scrolling up the console log.
        /// </summary>
        public void Scroll_Up()
        {
            if (scroll_index >= con_log_list.Length - 1 - displayed_line) return;
            scroll_index++;

            RefreshLayout();
        }

        /// <summary>
        /// Is executed when scrolling down the console log.
        /// </summary>
        public void Scroll_Down()
        {
            if (scroll_index <= 0) return;

            scroll_index--;

            RefreshLayout();
        }

        /// <summary>
        /// Gets the current visibility state of the console.
        /// </summary>
        /// <returns>Is the console visible?</returns>
        public bool GetVisibility()
        {
            return ConsolePanel.Visible;
        }

        /// <summary>
        /// Executes the entered commands.
        /// </summary>
        /// <param name="command">Command</param>
        private void ExecuteCommand(String command)
        {
            cmd_scroll_index = 0;

            // Exit if no command was entered =)
            if (command == "") return;

            scroll_index = 0;

            // Save commands in the history
            cmd_history_list[cmd_history_pointer] = command;
            cmd_history_pointer++;

            if (cmd_history_pointer > cmd_history_list.Length - 1)
                cmd_history_pointer = 0;

            WriteLine(">" + command);
            command = command.ToLower();

            // Execute the command (if it exists)
            switch (command)
            {
                case "exit":
                    Application.Exit();
                    break;

                case "help":
                    WriteLine("This is a list of avaliable commands:");
                    WriteLine(" - help : This screen.");
                    WriteLine(" - version : Outputs the version of the program.");
                    WriteLine(" - hide : Hide the console.");
                    WriteLine(" - clear : Delete all text in the console.");
                    WriteLine(" - message : Displays a MessageBox.");
                    WriteLine(" - test : Test an internal function.");
                    WriteLine(" - exit : Exit the application.");
                    break;

                case "hide":
                    SetVisibility(false);
                    break;

                case "clear":
                    Clear();
                    break;

                case "version":
                    WriteLine(Application.ProductName + " - v" + Application.ProductVersion);
                    break;

                case "message":
                    MessageBox.Show("I AM ALIVE!!!!!");
                    break;

                case "test":
                    for (int i = 0; i <= 100; i++)
                    {
                        for (int j = 0; j <= 500; j++)
                        {
                            Application.DoEvents();
                        }

                        WriteLineForProgressive("Wow a progress", i, 100);
                    }
                    break;


                default:
                    WriteLine("Unrecognized command '" + command + "'.");
                    break;
            }
        }

        /// <summary>
        /// Write a text line to the console.
        /// </summary>
        /// <param name="str">Obtainable text</param>
        public void WriteLine(string str)
        {
            con_log_list[con_log_pointer] = str;

            con_log_pointer++;

            if (con_log_pointer > con_log_list.Length - 1)
                con_log_pointer = 0;

            RefreshLayout();
        }

        /// <summary>
        /// Write a text with a progress indicator.
        /// </summary>
        /// <param name="str">Obtainable text</param>
        /// <param name="progress">Progress</param>
        /// <param name="total">Maximum</param>
        public void WriteLineForProgressive(string str, int progress, int total)
        {
            // Message in more states
            if ((ReadlastLine() != null) && (ReadlastLine().Length >= str.Length) && ((ReadlastLine()).Substring(0, str.Length) == str))
            {
                int percent = (progress * 100) / total;
                WriteErasingCurrentLine(str + " [" + percent + "%]");
            }
            else
            {
                int percent = (progress * 100) / total;
                WriteLine(str + " [" + percent + "%]");
            }
        }

        /// <summary>
        /// Reads last line in the console.
        /// </summary>
        /// <returns>Last line in the console</returns>
        private String ReadlastLine()
        {
            return con_log_list[(con_log_pointer == 0 ? con_log_list.Length - 1 : con_log_pointer - 1)];
        }

        /// <summary>
        /// Write a text to the console.
        /// </summary>
        /// <param name="str">Obtainable text</param>
        public void Write(String str)
        {
            con_log_list[con_log_pointer] = con_log_list[con_log_pointer] + str;
            RefreshLayout();
        }

        /// <summary>
        /// Delete current line.
        /// </summary>
        /// <param name="str">Text to be deleted</param>
        private void WriteErasingCurrentLine(String str)
        {
            con_log_list[(con_log_pointer == 0 ? con_log_list.Length - 1 : con_log_pointer - 1)] = str;
            RefreshLayout();
        }

        /// <summary>
        /// Deletes the text in the console.
        /// </summary>
        public void Clear()
        {
            con_log_list = new String[50];
            con_log_pointer = 0;

            RefreshLayout();
        }

        /// <summary>
        /// Refresh all controls.
        /// </summary>
        private void RefreshLayout()
        {
            int projected_index = 0;
            for (int line_counter = 0; line_counter < displayed_line; line_counter++)
            {
                projected_index = ((con_log_list.Length - 1) + con_log_pointer - line_counter - scroll_index) % (con_log_list.Length);
                parent_form.Invoke(new EditLabelDelegate(EditLabel), ConsoleTextBox[line_counter], con_log_list[projected_index]);
            }
        }

        private void EditLabel(Label lbl, String str)
        {
            lbl.Text = str;
        }
    }
}
Tagged with console, virtual, shell, Konsole, virtuell.

Comments

 

Log in, to comment!