Click here to Skip to main content
Click here to Skip to main content

Command Prompt Control

, 10 Aug 2006
Rate this:
Please Sign up or sign in to vote.
A command prompt which accepts commands from the user and shows the commands and messages in a RichTextBox along with AutoComplete and Tooltip facility
Sample Image - commandprompt.jpg

Introduction

I needed to write this control because I was involved in developing various engineering software. All of these projects had a common style of data entry through files or commands.

In order to allow the user to enter commands, I found that handling the Return key in the KeyDown event was not enough and a better user interface and command prompt were required. This control helped me to easily accept commands as input from the user at a command line. It also features an AutoComplete feature for previously used commands.

Using the Control

Like any other .NET control, for using the IDE, you should add the CommandPrompt control to the Toolbox panel. This can be accomplished by right-clicking on a Toolbox tab and selecting "Choose Items...", browsing to the CommandPrompt assembly, and selecting it. This will add the CommandPrompt control to the Toolbox so that it can be dragged/dropped to a Windows form. Once an instance is added to the form, select it and view its properties. In the form that you are using the control, also add the following line:

using CommandPrompt;

Layout and Design

The basic design of the control is pretty much like any command prompt you would encounter in applications and operating systems. CommandPrompt basically consists of three different regions.

Layout of CommandPrompt control

Properties

The following properties control the look and feel of the CommandPrompt control:

Commands

  • PromptString: String shown as the prompt (default=">")
  • CancelOnEsc: Indicates whether the input area is cleared on pressing the Escape key (default=true)
  • IgnoreBlankCommands: Determines whether the Command event fires for blank commands (default=true)
  • BorderInput: The border style around the input area
  • Delimiters: Contains an array of char delimiters using which the command entered by the user is split into parameters

Messages

  • ShowMessages: Indicates whether the messages list is shown (default=true)
  • MessageColor: Color of the messages added using the AddMessage method

AutoComplete

  • AutoComplete: Indicates text completion behaviour at the prompt (default=None)
  • AutoCompleteStore: Indicates whether commands are stored for AutoComplete feature (default=false)

Appearance

  • BackColor: The background color of both the input and messages areas
  • ForeColor: The foreground color of this control, used to display text
  • PromptColor: The foreground color of the prompt
  • Font: The font of both the commands and messages

Events

  • Command: Occurs when user enters a command
  • CommandEntering: Occurs when the text in the input area changes
  • ParameterEntered: Occurs when the user enters a delimiter specified in Delimiters

Methods

  • void AddMessage(string msg): Add a message to the message list
  • void ClearMessages(): Clear all messages from the message list
  • void AutoCompleteAdd(string msg): Add data to be used for AutoComplete feature
  • void AutoCompleteClear(): Clear all data used for AutoComplete
  • bool SaveMessages(string FileName): Save the messages list to a file
  • bool LoadMessages(string FileName): Load messages stored in a file to the messages list
  • void ShowToolTip(string tip): Shows a Tooltip containing tip
  • void HideToolTip(): Hides any Tooltip shown

Handling the Commands

The Command event fires whenever the user enters a command, i.e. types in the command and presses the enter key. In order to process the command in your application, you need to handle just this event. The code which checks for the enter key in the KeyDown event follows:

if (e.KeyCode == Keys.Return)
{
    if (txtInput.Text != "" && IgnoreBlankCommands)
    {
        // Raise the command event
        CommandEventArgs args = new CommandEventArgs(txtInput.Text);
        OnCommand(args);

        // Show command if not cancelled by code
        if (args.Cancel == false)
        {
            if (rtbMessages.Lines.Length > 0)
                rtbMessages.AppendText("\r\n" + lblPrompt.Text + " " + txtInput.Text);
            else
                rtbMessages.AppendText(lblPrompt.Text + " " + txtInput.Text);

            if (args.Message != "")
                AddMessage(args.Message);

            rtbMessages.ScrollToCaret();

            // Store for AutoComplete
            prevMessages.Add(txtInput.Text);
            if (autoCompleteStore == true && args.Record == true)
                txtInput.AutoCompleteCustomSource.Add(txtInput.Text);

            currentLine = prevMessages.Count - 1;
        }
        // Clear input box
        txtInput.Text = "";
    }
    e.Handled = true;
}

The Command event is passed a CommandEventArgs object. The properties of CommandEventArgs are:

  • Cancel: Setting this to false results in the command and the corresponding message not being shown in the message list (default=true)
  • Command: The command entered by the user
  • Message: The message to be displayed in response to the command
  • Record: Indicates whether the command should be stored for AutoComplete (default=true)
  • Parameters: Contains the parameters in the command entered by the user which are split by the delimiters specified in Delimiters

Depending upon the command entered by the user, the developer may choose various responses and behaviour by modifying the values of the CommandEventArgs object. Some expected responses to commands are:

  • The command can be prevented from being displayed by setting the Cancel property to false.
  • The message to be displayed in response should be set in the Message property.
  • If the developer does not want to store any particular command for AutoComplete, then the Record property should be set to false.

The following code for the Command event handler checks if the command is "date". If the "date" command is entered then the date is displayed by setting the Message property. Otherwise an error message is displayed and the command is not stored for AutoComplete.

private void prompt1_Command(object sender, CommandEventArgs e)
{
    if (e.Command == "date")
    {
        e.Message = "  The current date is : " + 
            DateTime.Now.ToLongDateString();
        return;
    }

    // Show error message
    e.Message = "'" + e.Command + "' is an unrecognized command";
    // Don't store the command
    e.Record = false;
}

For ease of parsing the commands entered by the user, specify the delimiters to be used to split the command in Delimiters. If Delimiters contains {' ', ','} then the command "line 100,100,200,200" will be split into parameters: {"line","100","100","200","200"}.

The developer may also wish to show a Tooltip as the user keeps entering parameters such as:

This can be done by handling the ParameterEntered event which fires whenever the user enters a delimiter. It contains parameters similar to the Command event. The Tooltip to be shown is specified in the ToolTip parameter of the ParameterEnteredEventArgs object. Blank parameters are not included in the Parameters array. A detailed implementation is provided in the Paint demo project.

Another event, CommandEntering is provided which fires when the text in the input area changes. This is similar to handling the TextChanged event of a TextBox. The CommandEnteringEventArgs object also contains a ToolTip parameter. Setting this parameter will result in a Tooltip containing the string to be displayed. Using both the CommandEntering and the ParameterEntered events to display Tooltips is not recommended.

AutoComplete

The AutoComplete feature of the control can be changed by changing the AutoComplete and AutoCompleteStore properties. The AutoComplete property determines the type of AutoCompletion to be used in the input area. It can take the following values:

  • Append: Appends the remainder of the most likely candidate string to the existing characters, highlighting the appended characters.
  • None: Disables the automatic completion feature.
  • Suggest: Displays the auxiliary drop-down list associated with the control. This drop-down is populated with one or more suggested completion strings.
  • SuggestAppend: Applies both Suggest and Append options.

The AutoCompleteStore property determines whether the commands entered by the user are stored for AutoComplete. Individual commands can be ignored for storage by setting the Record property to false as described above. Setting the AutoComplete property to any value except None and the AutoCompleteStore property to true makes the control store all commands for AutoComplete and display suggestions to the user as he types.

The commands entered by the user are stored in an ArrayList, prevMessages. An integer currentLine keeps track of the current command entered by the user or displayed at the input area. If the user presses the Up arrow key, the previous stored message is shown, and if the Down arrow key is pressed, the next command is shown (if available). The code is present in the KeyDown event handler and really does not need any explanation.

Visual Appearance

Sometimes the developer might not want to show the messages list to the user. The messages list can be hidden by setting ShowMessages to false. The CommandPrompt resembles a TextBox as shown below. This does not affect any other operations of the control such as AutoComplete and storing the messages. When the message list is shown again, it contains all messages entered unless they have been cleared by the user.

CommandPrompt control without messages list

The PromptString property determines what is displayed as the prompt to the user. This can be changed in response to messages also.

private void prompt1_Command(object sender, CommandEventArgs e)
{
    if (e.Command == "cd..")
    {
        if (dirInfo.Parent != null)
            dirInfo = dirInfo.Parent;
        prompt1.PromptString = dirInfo.FullName + ">";
        return;
    }
}

In the above code, the DirectoryInfo dirInfo variable stores the current working directory. In response to the "cd.." command the dirInfo variable is updated and the prompt is changed to reflect it.

The BackColor, Font and ForeColor properties of the control affect both the input area and the messages list. The ForeColor property determines the color of the commands that are shown in the messages list, whereas MessageColor determines the color of the messages in the message list shown in response to the commands.

A linux style command prompt

The above figure was an attempt to make a linux command line. As I am not a linux user, the attempt was a lame oneSmile | :) .

Conclusion

This is the first control I am posting on The Code Project. The updated version of the control is uploaded. Please send in your suggestions and request for features.

Control History

  • 23rd July, 2006
    • Control uploaded
  • 10th August, 2006 (ver 1.1)
    • Scrolling feature added to control
    • CommandEntering and ParameterEntered events added
    • Tooltip added to control
    • PromptColor and Delimiters properties added

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

vikashparida

India India
I am currently working with D. E. Shaw and Co. in Hyderabad. I completed my B.Tech. at Indian Institute of Technology, Kharagpur majoring in Manufacturing Science and Engineering.
 
I am a really hardcore gamer and play all sorts of computer games. I love to watch and play football.

Comments and Discussions

 
Questionis there a way to add highlighting function that highlight some keywords etc ... ? PinmemberZangetsuZ2-Jan-13 3:09 
QuestionYEAH!! Pinmemberraulkist12-Sep-12 7:39 
GeneralForeach PinmemberFullmetal9901217-Mar-10 14:18 
GeneralRe: Foreach Pinmembervikashparida22-Mar-10 15:27 
GeneralCool control, deserves to be in MS Controls PinmemberAnandChavali31-Jul-09 20:09 
GeneralMessage Buffer clear PinmemberKestor24-Apr-08 11:18 
GeneralRe: Message Buffer clear Pinmembervikashparida24-Apr-08 19:47 
GeneralRe: Message Buffer clear PinmemberKestor25-Apr-08 3:02 
GeneralRe: Message Buffer clear Pinmembervikashparida25-Apr-08 7:37 
Generalerror in VC++ PinmemberJacek762-Jul-07 13:27 
GeneralDrive change does not work!! PinmemberMonirTigerit11-Aug-06 18:18 
GeneralRe: Drive change does not work!! Pinmembervikashparida12-Aug-06 2:54 
QuestionHow to Close MdiChild PinmemberVäinölä Harri10-Aug-06 23:44 
AnswerRe: How to Close MdiChild Pinmembervikashparida11-Aug-06 5:55 
GeneralGreat, Thanks !! PinmemberMarcos Meli10-Aug-06 9:15 
GeneralRe: Great, Thanks !! Pinmembervikashparida10-Aug-06 10:11 
GeneralRe: Great, Thanks !! PinmemberMarcos Meli10-Aug-06 13:39 
QuestionTraditional Prompt Interface PinmemberHerbert Sauro24-Jul-06 14:53 
AnswerRe: Traditional Prompt Interface Pinmembervikashparida24-Jul-06 18:58 
GeneralRe: Traditional Prompt Interface PinmemberHerbert Sauro25-Jul-06 12:20 
GeneralGood tool PinmemberMohammad Nazir23-Jul-06 23:41 
GeneralRe: Good tool Pinmembervikashparida24-Jul-06 3:28 
GeneralCool! PinmemberAlexey A. Popov23-Jul-06 20:33 
GeneralRe: Cool! Pinmembervikashparida23-Jul-06 21:40 
GeneralRe: Cool! PinmemberAlexey A. Popov24-Jul-06 2:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 10 Aug 2006
Article Copyright 2006 by vikashparida
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid